mirror of https://github.com/vladmandic/human
8018 lines
1.6 MiB
8018 lines
1.6 MiB
/*
|
|
Human
|
|
homepage: <https://github.com/vladmandic/human>
|
|
author: <https://github.com/vladmandic>'
|
|
*/
|
|
|
|
var Human=(()=>{var kc=Object.defineProperty;var J9=Object.getOwnPropertyDescriptor;var Q9=Object.getOwnPropertyNames;var eE=Object.prototype.hasOwnProperty;var tE=(e,t,r)=>t in e?kc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var rE=e=>kc(e,"__esModule",{value:!0});var Qd=(e,t)=>{for(var r in t)kc(e,r,{get:t[r],enumerable:!0})},aE=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of Q9(t))!eE.call(e,n)&&(r||n!=="default")&&kc(e,n,{get:()=>t[n],enumerable:!(a=J9(t,n))||a.enumerable});return e};var nE=(e=>(t,r)=>e&&e.get(t)||(r=aE(rE({}),t,1),e&&e.set(t,r),r))(typeof WeakMap!="undefined"?new WeakMap:0);var fe=(e,t,r)=>(tE(e,typeof t!="symbol"?t+"":t,r),r),L5=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var ep=(e,t,r)=>(L5(e,t,"read from private field"),r?r.call(e):t.get(e)),tp=(e,t,r)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,r)},rp=(e,t,r,a)=>(L5(e,t,"write to private field"),a?a.call(e,r):t.set(e,r),r);var Z2e={};Qd(Z2e,{Human:()=>r9,default:()=>r9,defaults:()=>xs,env:()=>ce});function se(...e){let t=new Date,r=`${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(r,"Human:",...e)}function B5(e,t){let r=e.endsWith("/")?"":"/",n=t.startsWith(".")||t.startsWith("/")||t.startsWith("http:")||t.startsWith("https:")||t.startsWith("file:")?`${t}`:`${e}${r}${t}`;if(!n.toLocaleLowerCase().includes(".json"))throw new Error(`modelpath error: expecting json file: ${n}`);return n}var oe=()=>typeof performance!="undefined"?performance.now():parseInt((Number(process.hrtime.bigint())/1e3/1e3).toString());function m1(e,t,r="config",a=[]){for(let n of Object.keys(t))if(typeof t[n]=="object")m1(e[n],t[n],n,a);else{let s=e&&typeof e[n]!="undefined";s||a.push({reason:"unknown property",where:`${r}.${n} = ${t[n]}`});let i=e&&typeof e[n]==typeof t[n];s&&!i&&a.push({reason:"property type mismatch",where:`${r}.${n} = ${t[n]}`,expected:typeof e[n]})}return t.debug&&r==="config"&&a.length>0&&se("invalid configuration",a),a}function vr(...e){let t=r=>r&&typeof r=="object";return e.reduce((r,a)=>(Object.keys(a||{}).forEach(n=>{let s=r[n],i=a[n];Array.isArray(s)&&Array.isArray(i)?r[n]=s.concat(...i):t(s)&&t(i)?r[n]=vr(s,i):r[n]=i}),r),{})}var xs={backend:"",modelBasePath:"",cacheModels:!0,wasmPath:"",wasmPlatformFetch:!1,debug:!0,async:!0,warmup:"full",cacheSensitivity:.7,skipAllowed:!1,deallocate:!1,filter:{enabled:!0,equalization:!1,width:0,height:0,flip:!1,return:!0,brightness:0,contrast:0,sharpness:0,blur:0,saturation:0,hue:0,negative:!1,sepia:!1,vintage:!1,kodachrome:!1,technicolor:!1,polaroid:!1,pixelate:0},gesture:{enabled:!0},face:{enabled:!0,detector:{modelPath:"blazeface.json",rotation:!0,maxDetected:1,skipFrames:99,skipTime:2500,minConfidence:.2,iouThreshold:.1,mask:!1,return:!1},mesh:{enabled:!0,modelPath:"facemesh.json"},iris:{enabled:!0,modelPath:"iris.json"},emotion:{enabled:!0,minConfidence:.1,skipFrames:99,skipTime:1500,modelPath:"emotion.json"},description:{enabled:!0,modelPath:"faceres.json",skipFrames:99,skipTime:3e3,minConfidence:.1},antispoof:{enabled:!1,skipFrames:99,skipTime:4e3,modelPath:"antispoof.json"},liveness:{enabled:!1,skipFrames:99,skipTime:4e3,modelPath:"liveness.json"}},body:{enabled:!0,modelPath:"movenet-lightning.json",maxDetected:-1,minConfidence:.3,skipFrames:1,skipTime:200},hand:{enabled:!0,rotation:!0,skipFrames:99,skipTime:1e3,minConfidence:.5,iouThreshold:.2,maxDetected:-1,landmarks:!0,detector:{modelPath:"handtrack.json"},skeleton:{modelPath:"handlandmark-full.json"}},object:{enabled:!1,modelPath:"mb3-centernet.json",minConfidence:.2,iouThreshold:.4,maxDetected:10,skipFrames:99,skipTime:2e3},segmentation:{enabled:!1,modelPath:"selfie.json",blur:8}};var We={};Qd(We,{Abs:()=>Fo,Acos:()=>Tu,Acosh:()=>Cu,AdadeltaOptimizer:()=>xm,AdagradOptimizer:()=>bm,AdamOptimizer:()=>vm,AdamaxOptimizer:()=>wm,Add:()=>qn,AddN:()=>js,All:()=>Nu,Any:()=>Eu,ArgMax:()=>Hs,ArgMin:()=>Ru,Asin:()=>Fu,Asinh:()=>Mu,Atan:()=>$u,Atan2:()=>Ou,Atanh:()=>Pu,AvgPool:()=>qs,AvgPool3D:()=>_p,AvgPool3DGrad:()=>Cf,AvgPoolGrad:()=>Tf,BackendWasm:()=>uT,BatchMatMul:()=>Ks,BatchToSpaceND:()=>Mo,Bincount:()=>Nf,BroadcastArgs:()=>Ef,BroadcastTo:()=>Ov,Callback:()=>u4,CallbackList:()=>u7,Cast:()=>Xs,Ceil:()=>Zs,ClipByValue:()=>Kn,Complex:()=>Lp,ComplexAbs:()=>Bp,Concat:()=>$o,Conv2D:()=>Ys,Conv2DBackpropFilter:()=>Rf,Conv2DBackpropInput:()=>Js,Conv3D:()=>Wp,Conv3DBackpropFilterV2:()=>Ff,Conv3DBackpropInputV2:()=>Mf,Cos:()=>Qs,Cosh:()=>ei,CropAndResize:()=>Oo,Cumsum:()=>Po,CustomCallback:()=>p7,DataStorage:()=>Dp,DenseBincount:()=>$f,DepthToSpace:()=>zo,DepthwiseConv2dNative:()=>ti,DepthwiseConv2dNativeBackpropFilter:()=>Pf,DepthwiseConv2dNativeBackpropInput:()=>Of,Diag:()=>zf,Dilation2D:()=>Vp,Dilation2DBackpropFilter:()=>Zc,Dilation2DBackpropInput:()=>Xc,ENV:()=>hn,EarlyStopping:()=>d4,Einsum:()=>Up,Elu:()=>ai,EluGrad:()=>Df,Environment:()=>$v,Equal:()=>Do,Erf:()=>zu,Exp:()=>ni,ExpandDims:()=>_o,Expm1:()=>Lo,FFT:()=>_f,Fill:()=>Du,FlipLeftRight:()=>Bo,Floor:()=>si,FloorDiv:()=>ii,FromPixels:()=>Ip,FusedBatchNorm:()=>oi,FusedConv2D:()=>Fs,FusedDepthwiseConv2D:()=>Ms,GPGPUContext:()=>uu,GatherNd:()=>Vo,GatherV2:()=>Wo,GraphModel:()=>qm,Greater:()=>Uo,GreaterEqual:()=>li,History:()=>d7,IFFT:()=>Lf,Identity:()=>ui,Imag:()=>Gp,InputSpec:()=>qt,IsFinite:()=>_u,IsInf:()=>Lu,IsNan:()=>Bu,KernelBackend:()=>Iu,LRN:()=>Hp,LRNGrad:()=>Wf,LayerVariable:()=>s7,LayersModel:()=>jn,LeakyRelu:()=>di,Less:()=>Go,LessEqual:()=>jo,LinSpace:()=>Bf,Log:()=>pi,Log1p:()=>Wu,LogSoftmax:()=>zv,LogicalAnd:()=>Ho,LogicalNot:()=>Vu,LogicalOr:()=>jp,MathBackendCPU:()=>fx,MathBackendWebGL:()=>Nh,Max:()=>hi,MaxPool:()=>fi,MaxPool3D:()=>qp,MaxPool3DGrad:()=>Uf,MaxPoolGrad:()=>Vf,MaxPoolWithArgmax:()=>Gf,Maximum:()=>ci,Mean:()=>mi,Min:()=>gi,Minimum:()=>yi,MirrorPad:()=>Ai,Mod:()=>Uu,MomentumOptimizer:()=>km,Multinomial:()=>jf,Multiply:()=>xi,Neg:()=>qo,NonMaxSuppressionV3:()=>Xo,NonMaxSuppressionV4:()=>Gu,NonMaxSuppressionV5:()=>Zo,NotEqual:()=>Ko,OP_SCOPE_SUFFIX:()=>Yv,OneHot:()=>Jo,OnesLike:()=>Yo,Optimizer:()=>Jn,OptimizerConstructors:()=>vs,Pack:()=>Qo,PadV2:()=>bi,Pool:()=>XE,Pow:()=>vi,Prelu:()=>wi,Prod:()=>el,RMSPropOptimizer:()=>Im,RNN:()=>Qn,Range:()=>ju,Rank:()=>Wv,Real:()=>Kp,RealDiv:()=>ri,Reciprocal:()=>Hu,Reduction:()=>_k,Relu:()=>ki,Relu6:()=>Si,Reshape:()=>tl,ResizeBilinear:()=>Ii,ResizeBilinearGrad:()=>qf,ResizeNearestNeighbor:()=>qu,ResizeNearestNeighborGrad:()=>Hf,Reverse:()=>rl,RotateWithOffset:()=>gl,Round:()=>al,Rsqrt:()=>Ti,SGDOptimizer:()=>ch,ScatterNd:()=>nl,Select:()=>sl,Selu:()=>Ku,Sequential:()=>_m,Sigmoid:()=>Ni,Sign:()=>Xu,Sin:()=>Ci,Sinh:()=>ol,Slice:()=>il,Softmax:()=>Fi,Softplus:()=>Zu,SpaceToBatchND:()=>ll,SparseFillEmptyRows:()=>Xp,SparseReshape:()=>Yu,SparseSegmentMean:()=>Zp,SparseSegmentSum:()=>Yp,SparseToDense:()=>Jp,SplitV:()=>ul,Sqrt:()=>Ei,Square:()=>Ju,SquaredDifference:()=>Mi,Step:()=>zi,StridedSlice:()=>dl,StringNGrams:()=>Qp,StringSplit:()=>Kf,StringToHashBucketFast:()=>Xf,Sub:()=>$i,Sum:()=>Ri,SymbolicTensor:()=>tn,Tan:()=>pl,Tanh:()=>Pi,Tensor:()=>et,TensorBuffer:()=>tr,Tile:()=>Xn,TopK:()=>hl,Transform:()=>cl,Transpose:()=>Oi,Unique:()=>Zf,Unpack:()=>fl,UnsortedSegmentSum:()=>eh,Variable:()=>Cp,ZerosLike:()=>ml,_FusedMatMul:()=>Rs,abs:()=>Qt,acos:()=>Rw,acosh:()=>Fw,add:()=>ue,addN:()=>Jf,all:()=>t2,any:()=>rf,argMax:()=>Ta,argMin:()=>Mw,asin:()=>$w,asinh:()=>Pw,atan:()=>Ow,atan2:()=>zw,atanh:()=>Dw,avgPool:()=>Qf,avgPool3d:()=>a2,backend:()=>cn,backend_util:()=>N,basicLSTMCell:()=>zM,batchNorm:()=>cu,batchNorm2d:()=>Ww,batchNorm3d:()=>Vw,batchNorm4d:()=>Uw,batchToSpaceND:()=>em,bincount:()=>n2,booleanMaskAsync:()=>KO,broadcastArgs:()=>Gw,broadcastTo:()=>xp,broadcast_util:()=>yl,browser:()=>$a,buffer:()=>Le,callbacks:()=>vG,cast:()=>me,ceil:()=>jw,clipByValue:()=>pa,clone:()=>Pr,complex:()=>$s,concat:()=>kt,concat1d:()=>Hw,concat2d:()=>ed,concat3d:()=>qw,concat4d:()=>Kw,constraints:()=>Hk,conv1d:()=>s2,conv2d:()=>Os,conv2dTranspose:()=>o2,conv3d:()=>l2,conv3dTranspose:()=>Zw,copyRegisteredKernels:()=>QE,cos:()=>tm,cosh:()=>u2,cosineWindow:()=>$2,cumsum:()=>d2,customGrad:()=>Nn,data:()=>O4,denseBincount:()=>Yw,deprecationWarn:()=>Jy,depthToSpace:()=>Jw,depthwiseConv2d:()=>lh,deregisterOp:()=>IG,device_util:()=>nh,diag:()=>h$,dilation2d:()=>Qw,disableDeprecationWarnings:()=>JF,dispose:()=>re,disposeVariables:()=>QF,div:()=>pe,divNoNan:()=>ek,dot:()=>x$,dropout:()=>Ek,einsum:()=>tk,elu:()=>uh,enableDebugMode:()=>YF,enableProdMode:()=>Yy,enclosingPowerOfTwo:()=>Rk,engine:()=>kr,env:()=>Y,equal:()=>Ca,erf:()=>rk,exp:()=>Na,expandDims:()=>Ht,expm1:()=>ak,eye:()=>p2,fft:()=>hm,fill:()=>td,findBackend:()=>e2,findBackendFactory:()=>aM,floor:()=>dh,floorDiv:()=>ih,forceHalfFloat:()=>r8,fused:()=>_s,gather:()=>fu,gatherND:()=>Nk,gather_util:()=>Gy,getBackend:()=>ca,getGradient:()=>M1,getKernel:()=>Yc,getKernelsForBackend:()=>Tn,getThreadsCount:()=>gye,gpgpu_util:()=>$I,grad:()=>G$,grads:()=>j$,greater:()=>fa,greaterEqual:()=>xl,ifft:()=>Fp,imag:()=>rm,image:()=>Ie,inTopKAsync:()=>sz,initializers:()=>Zk,input:()=>S7,io:()=>Ir,irfft:()=>N2,isFinite:()=>P$,isInf:()=>z$,isNaN:()=>nk,keep:()=>dr,kernel_impls:()=>Ha,layers:()=>a7,leakyRelu:()=>am,less:()=>h2,lessEqual:()=>bl,linalg:()=>Lk,linspace:()=>sk,loadGraphModel:()=>Cj,loadLayersModel:()=>MV,localResponseNormalization:()=>ik,log:()=>Ea,log1p:()=>nm,logSigmoid:()=>Y$,logSoftmax:()=>c2,logSumExp:()=>pk,logicalAnd:()=>ln,logicalNot:()=>im,logicalOr:()=>g2,logicalXor:()=>uP,losses:()=>UD,matMul:()=>Ke,math:()=>pw,max:()=>hr,maxPool:()=>om,maxPool3d:()=>y2,maxPoolWithArgmax:()=>hk,maximum:()=>Zn,mean:()=>Wt,memory:()=>tf,meshgrid:()=>mP,metrics:()=>i4,min:()=>zs,minimum:()=>ph,mirrorPad:()=>ck,mod:()=>ad,model:()=>RV,models:()=>o4,moments:()=>lm,movingAverage:()=>YO,mul:()=>L,multiRNNCell:()=>kP,multinomial:()=>fk,neg:()=>zt,nextFrame:()=>Bk,norm:()=>F2,notEqual:()=>mu,oneHot:()=>Ep,ones:()=>da,onesLike:()=>Ra,op:()=>V,outerProduct:()=>NP,pad:()=>ja,pad1d:()=>FP,pad2d:()=>$P,pad3d:()=>OP,pad4d:()=>DP,pool:()=>VP,pow:()=>Ds,prelu:()=>dm,print:()=>ow,prod:()=>A2,profile:()=>eM,rand:()=>qP,randomGamma:()=>YP,randomNormal:()=>mk,randomUniform:()=>nd,range:()=>gu,ready:()=>Qu,real:()=>Rp,reciprocal:()=>gk,registerBackend:()=>Al,registerCallbackConstructor:()=>$V,registerGradient:()=>Dv,registerKernel:()=>Ga,registerOp:()=>kG,regularizers:()=>l4,relu:()=>Fn,relu6:()=>v2,removeBackend:()=>rM,reshape:()=>U,reverse:()=>Fa,reverse1d:()=>iO,reverse2d:()=>lO,reverse3d:()=>dO,reverse4d:()=>hO,rfft:()=>cm,round:()=>w2,rsqrt:()=>k2,scalar:()=>Se,scatterND:()=>Ck,scatter_util:()=>jy,selu:()=>I2,separableConv2d:()=>yk,sequential:()=>FV,serialization:()=>de,setBackend:()=>Qy,setPlatform:()=>nM,setThreadsCount:()=>mye,setWasmPath:()=>fye,setWasmPaths:()=>Xx,setWebGLContext:()=>Zm,setdiff1dAsync:()=>Ak,shared:()=>Km,sigmoid:()=>Sr,sign:()=>xk,signal:()=>VD,sin:()=>S2,sinh:()=>T2,slice:()=>Oe,slice1d:()=>pm,slice2d:()=>C2,slice3d:()=>vl,slice4d:()=>wo,slice_util:()=>Ot,softmax:()=>sd,softplus:()=>rd,spaceToBatchND:()=>um,sparse:()=>up,sparseToDense:()=>M2,spectral:()=>WD,split:()=>Kt,sqrt:()=>Tr,square:()=>At,squaredDifference:()=>E2,squeeze:()=>Ye,stack:()=>nr,step:()=>hh,stridedSlice:()=>bk,string:()=>Dc,sub:()=>he,sum:()=>ke,sumOutType:()=>ah,tan:()=>vk,tanh:()=>hu,tensor:()=>pt,tensor1d:()=>St,tensor2d:()=>an,tensor3d:()=>cw,tensor4d:()=>_O,tensor5d:()=>LO,tensor6d:()=>BO,tensor_util:()=>rn,test_util:()=>Cw,tidy:()=>q,tile:()=>Wa,time:()=>tM,topk:()=>wk,train:()=>so,transpose:()=>rt,truncatedNormal:()=>fm,unique:()=>j1,unregisterGradient:()=>JE,unregisterKernel:()=>YE,unsortedSegmentSum:()=>kk,unstack:()=>ra,upcastType:()=>Or,util:()=>w,valueAndGrad:()=>H$,valueAndGrads:()=>q$,variable:()=>Ik,variableGrads:()=>ok,version:()=>Dh,version_converter:()=>Nj,version_core:()=>Zy,version_cpu:()=>fq,version_layers:()=>nA,version_wasm:()=>yye,version_webgl:()=>Dee,webgl:()=>_ee,webgl_util:()=>nI,webgpu:()=>sS,where:()=>zr,whereAsync:()=>R2,zeros:()=>Vt,zerosLike:()=>at});var sE=Object.create,wf=Object.defineProperty,iE=Object.getOwnPropertyDescriptor,vv=Object.getOwnPropertyNames,oE=Object.getPrototypeOf,lE=Object.prototype.hasOwnProperty,uE=e=>wf(e,"__esModule",{value:!0}),sr=(e,t)=>function(){return t||(0,e[vv(e)[0]])((t={exports:{}}).exports,t),t.exports},De=(e,t)=>{for(var r in t)wf(e,r,{get:t[r],enumerable:!0})},dE=(e,t,r,a)=>{if(t&&typeof t=="object"||typeof t=="function")for(let n of vv(t))!lE.call(e,n)&&(r||n!=="default")&&wf(e,n,{get:()=>t[n],enumerable:!(a=iE(t,n))||a.enumerable});return e},Eo=(e,t)=>dE(uE(wf(e!=null?sE(oE(e)):{},"default",!t&&e&&e.__esModule?{get:()=>e.default,enumerable:!0}:{value:e,enumerable:!0})),e),pE=sr({"src/node_modules/long/src/long.js"(e,t){t.exports=a;var r=null;try{r=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(I){}function a(I,D,O){this.low=I|0,this.high=D|0,this.unsigned=!!O}a.prototype.__isLong__,Object.defineProperty(a.prototype,"__isLong__",{value:!0});function n(I){return(I&&I.__isLong__)===!0}a.isLong=n;var s={},i={};function o(I,D){var O,j,X;return D?(I>>>=0,(X=0<=I&&I<256)&&(j=i[I],j)?j:(O=d(I,(I|0)<0?-1:0,!0),X&&(i[I]=O),O)):(I|=0,(X=-128<=I&&I<128)&&(j=s[I],j)?j:(O=d(I,I<0?-1:0,!1),X&&(s[I]=O),O))}a.fromInt=o;function l(I,D){if(isNaN(I))return D?b:x;if(D){if(I<0)return b;if(I>=g)return R}else{if(I<=-y)return z;if(I+1>=y)return E}return I<0?l(-I,D).neg():d(I%m|0,I/m|0,D)}a.fromNumber=l;function d(I,D,O){return new a(I,D,O)}a.fromBits=d;var u=Math.pow;function p(I,D,O){if(I.length===0)throw Error("empty string");if(I==="NaN"||I==="Infinity"||I==="+Infinity"||I==="-Infinity")return x;if(typeof D=="number"?(O=D,D=!1):D=!!D,O=O||10,O<2||36<O)throw RangeError("radix");var j;if((j=I.indexOf("-"))>0)throw Error("interior hyphen");if(j===0)return p(I.substring(1),D,O).neg();for(var X=l(u(O,8)),_=x,K=0;K<I.length;K+=8){var W=Math.min(8,I.length-K),ee=parseInt(I.substring(K,K+W),O);if(W<8){var Q=l(u(O,W));_=_.mul(Q).add(l(ee))}else _=_.mul(X),_=_.add(l(ee))}return _.unsigned=D,_}a.fromString=p;function h(I,D){return typeof I=="number"?l(I,D):typeof I=="string"?p(I,D):d(I.low,I.high,typeof D=="boolean"?D:I.unsigned)}a.fromValue=h;var c=1<<16,f=1<<24,m=c*c,g=m*m,y=g/2,A=o(f),x=o(0);a.ZERO=x;var b=o(0,!0);a.UZERO=b;var v=o(1);a.ONE=v;var C=o(1,!0);a.UONE=C;var T=o(-1);a.NEG_ONE=T;var E=d(-1,2147483647,!1);a.MAX_VALUE=E;var R=d(-1,-1,!0);a.MAX_UNSIGNED_VALUE=R;var z=d(0,-2147483648,!1);a.MIN_VALUE=z;var M=a.prototype;M.toInt=function(){return this.unsigned?this.low>>>0:this.low},M.toNumber=function(){return this.unsigned?(this.high>>>0)*m+(this.low>>>0):this.high*m+(this.low>>>0)},M.toString=function(I){if(I=I||10,I<2||36<I)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(z)){var D=l(I),O=this.div(D),j=O.mul(D).sub(this);return O.toString(I)+j.toInt().toString(I)}else return"-"+this.neg().toString(I);for(var X=l(u(I,6),this.unsigned),_=this,K="";;){var W=_.div(X),ee=_.sub(W.mul(X)).toInt()>>>0,Q=ee.toString(I);if(_=W,_.isZero())return Q+K;for(;Q.length<6;)Q="0"+Q;K=""+Q+K}},M.getHighBits=function(){return this.high},M.getHighBitsUnsigned=function(){return this.high>>>0},M.getLowBits=function(){return this.low},M.getLowBitsUnsigned=function(){return this.low>>>0},M.getNumBitsAbs=function(){if(this.isNegative())return this.eq(z)?64:this.neg().getNumBitsAbs();for(var I=this.high!=0?this.high:this.low,D=31;D>0&&(I&1<<D)==0;D--);return this.high!=0?D+33:D+1},M.isZero=function(){return this.high===0&&this.low===0},M.eqz=M.isZero,M.isNegative=function(){return!this.unsigned&&this.high<0},M.isPositive=function(){return this.unsigned||this.high>=0},M.isOdd=function(){return(this.low&1)===1},M.isEven=function(){return(this.low&1)===0},M.equals=function(I){return n(I)||(I=h(I)),this.unsigned!==I.unsigned&&this.high>>>31===1&&I.high>>>31===1?!1:this.high===I.high&&this.low===I.low},M.eq=M.equals,M.notEquals=function(I){return!this.eq(I)},M.neq=M.notEquals,M.ne=M.notEquals,M.lessThan=function(I){return this.comp(I)<0},M.lt=M.lessThan,M.lessThanOrEqual=function(I){return this.comp(I)<=0},M.lte=M.lessThanOrEqual,M.le=M.lessThanOrEqual,M.greaterThan=function(I){return this.comp(I)>0},M.gt=M.greaterThan,M.greaterThanOrEqual=function(I){return this.comp(I)>=0},M.gte=M.greaterThanOrEqual,M.ge=M.greaterThanOrEqual,M.compare=function(I){if(n(I)||(I=h(I)),this.eq(I))return 0;var D=this.isNegative(),O=I.isNegative();return D&&!O?-1:!D&&O?1:this.unsigned?I.high>>>0>this.high>>>0||I.high===this.high&&I.low>>>0>this.low>>>0?-1:1:this.sub(I).isNegative()?-1:1},M.comp=M.compare,M.negate=function(){return!this.unsigned&&this.eq(z)?z:this.not().add(v)},M.neg=M.negate,M.add=function(I){n(I)||(I=h(I));var D=this.high>>>16,O=this.high&65535,j=this.low>>>16,X=this.low&65535,_=I.high>>>16,K=I.high&65535,W=I.low>>>16,ee=I.low&65535,Q=0,ne=0,Z=0,ae=0;return ae+=X+ee,Z+=ae>>>16,ae&=65535,Z+=j+W,ne+=Z>>>16,Z&=65535,ne+=O+K,Q+=ne>>>16,ne&=65535,Q+=D+_,Q&=65535,d(Z<<16|ae,Q<<16|ne,this.unsigned)},M.subtract=function(I){return n(I)||(I=h(I)),this.add(I.neg())},M.sub=M.subtract,M.multiply=function(I){if(this.isZero())return x;if(n(I)||(I=h(I)),r){var D=r.mul(this.low,this.high,I.low,I.high);return d(D,r.get_high(),this.unsigned)}if(I.isZero())return x;if(this.eq(z))return I.isOdd()?z:x;if(I.eq(z))return this.isOdd()?z:x;if(this.isNegative())return I.isNegative()?this.neg().mul(I.neg()):this.neg().mul(I).neg();if(I.isNegative())return this.mul(I.neg()).neg();if(this.lt(A)&&I.lt(A))return l(this.toNumber()*I.toNumber(),this.unsigned);var O=this.high>>>16,j=this.high&65535,X=this.low>>>16,_=this.low&65535,K=I.high>>>16,W=I.high&65535,ee=I.low>>>16,Q=I.low&65535,ne=0,Z=0,ae=0,ie=0;return ie+=_*Q,ae+=ie>>>16,ie&=65535,ae+=X*Q,Z+=ae>>>16,ae&=65535,ae+=_*ee,Z+=ae>>>16,ae&=65535,Z+=j*Q,ne+=Z>>>16,Z&=65535,Z+=X*ee,ne+=Z>>>16,Z&=65535,Z+=_*W,ne+=Z>>>16,Z&=65535,ne+=O*Q+j*ee+X*W+_*K,ne&=65535,d(ae<<16|ie,ne<<16|Z,this.unsigned)},M.mul=M.multiply,M.divide=function(I){if(n(I)||(I=h(I)),I.isZero())throw Error("division by zero");if(r){if(!this.unsigned&&this.high===-2147483648&&I.low===-1&&I.high===-1)return this;var D=(this.unsigned?r.div_u:r.div_s)(this.low,this.high,I.low,I.high);return d(D,r.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?b:x;var O,j,X;if(this.unsigned){if(I.unsigned||(I=I.toUnsigned()),I.gt(this))return b;if(I.gt(this.shru(1)))return C;X=b}else{if(this.eq(z)){if(I.eq(v)||I.eq(T))return z;if(I.eq(z))return v;var _=this.shr(1);return O=_.div(I).shl(1),O.eq(x)?I.isNegative()?v:T:(j=this.sub(I.mul(O)),X=O.add(j.div(I)),X)}else if(I.eq(z))return this.unsigned?b:x;if(this.isNegative())return I.isNegative()?this.neg().div(I.neg()):this.neg().div(I).neg();if(I.isNegative())return this.div(I.neg()).neg();X=x}for(j=this;j.gte(I);){O=Math.max(1,Math.floor(j.toNumber()/I.toNumber()));for(var K=Math.ceil(Math.log(O)/Math.LN2),W=K<=48?1:u(2,K-48),ee=l(O),Q=ee.mul(I);Q.isNegative()||Q.gt(j);)O-=W,ee=l(O,this.unsigned),Q=ee.mul(I);ee.isZero()&&(ee=v),X=X.add(ee),j=j.sub(Q)}return X},M.div=M.divide,M.modulo=function(I){if(n(I)||(I=h(I)),r){var D=(this.unsigned?r.rem_u:r.rem_s)(this.low,this.high,I.low,I.high);return d(D,r.get_high(),this.unsigned)}return this.sub(this.div(I).mul(I))},M.mod=M.modulo,M.rem=M.modulo,M.not=function(){return d(~this.low,~this.high,this.unsigned)},M.and=function(I){return n(I)||(I=h(I)),d(this.low&I.low,this.high&I.high,this.unsigned)},M.or=function(I){return n(I)||(I=h(I)),d(this.low|I.low,this.high|I.high,this.unsigned)},M.xor=function(I){return n(I)||(I=h(I)),d(this.low^I.low,this.high^I.high,this.unsigned)},M.shiftLeft=function(I){return n(I)&&(I=I.toInt()),(I&=63)===0?this:I<32?d(this.low<<I,this.high<<I|this.low>>>32-I,this.unsigned):d(0,this.low<<I-32,this.unsigned)},M.shl=M.shiftLeft,M.shiftRight=function(I){return n(I)&&(I=I.toInt()),(I&=63)===0?this:I<32?d(this.low>>>I|this.high<<32-I,this.high>>I,this.unsigned):d(this.high>>I-32,this.high>=0?0:-1,this.unsigned)},M.shr=M.shiftRight,M.shiftRightUnsigned=function(I){if(n(I)&&(I=I.toInt()),I&=63,I===0)return this;var D=this.high;if(I<32){var O=this.low;return d(O>>>I|D<<32-I,D>>>I,this.unsigned)}else return I===32?d(D,0,this.unsigned):d(D>>>I-32,0,this.unsigned)},M.shru=M.shiftRightUnsigned,M.shr_u=M.shiftRightUnsigned,M.toSigned=function(){return this.unsigned?d(this.low,this.high,!1):this},M.toUnsigned=function(){return this.unsigned?this:d(this.low,this.high,!0)},M.toBytes=function(I){return I?this.toBytesLE():this.toBytesBE()},M.toBytesLE=function(){var I=this.high,D=this.low;return[D&255,D>>>8&255,D>>>16&255,D>>>24,I&255,I>>>8&255,I>>>16&255,I>>>24]},M.toBytesBE=function(){var I=this.high,D=this.low;return[I>>>24,I>>>16&255,I>>>8&255,I&255,D>>>24,D>>>16&255,D>>>8&255,D&255]},a.fromBytes=function(I,D,O){return O?a.fromBytesLE(I,D):a.fromBytesBE(I,D)},a.fromBytesLE=function(I,D){return new a(I[0]|I[1]<<8|I[2]<<16|I[3]<<24,I[4]|I[5]<<8|I[6]<<16|I[7]<<24,D)},a.fromBytesBE=function(I,D){return new a(I[4]<<24|I[5]<<16|I[6]<<8|I[7],I[0]<<24|I[1]<<16|I[2]<<8|I[3],D)}}}),hE=sr({"(disabled):src/node_modules/node-fetch/browser.js"(){}}),cE=sr({"(disabled):util"(){}}),fE=sr({"src/node_modules/seedrandom/lib/alea.js"(e,t){(function(r,a,n){function s(d){var u=this,p=l();u.next=function(){var h=2091639*u.s0+u.c*23283064365386963e-26;return u.s0=u.s1,u.s1=u.s2,u.s2=h-(u.c=h|0)},u.c=1,u.s0=p(" "),u.s1=p(" "),u.s2=p(" "),u.s0-=p(d),u.s0<0&&(u.s0+=1),u.s1-=p(d),u.s1<0&&(u.s1+=1),u.s2-=p(d),u.s2<0&&(u.s2+=1),p=null}function i(d,u){return u.c=d.c,u.s0=d.s0,u.s1=d.s1,u.s2=d.s2,u}function o(d,u){var p=new s(d),h=u&&u.state,c=p.next;return c.int32=function(){return p.next()*4294967296|0},c.double=function(){return c()+(c()*2097152|0)*11102230246251565e-32},c.quick=c,h&&(typeof h=="object"&&i(h,p),c.state=function(){return i(p,{})}),c}function l(){var d=4022871197,u=function(p){p=String(p);for(var h=0;h<p.length;h++){d+=p.charCodeAt(h);var c=.02519603282416938*d;d=c>>>0,c-=d,c*=d,d=c>>>0,c-=d,d+=c*4294967296}return(d>>>0)*23283064365386963e-26};return u}a&&a.exports?a.exports=o:n&&n.amd?n(function(){return o}):this.alea=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),mE=sr({"src/node_modules/seedrandom/lib/xor128.js"(e,t){(function(r,a,n){function s(l){var d=this,u="";d.x=0,d.y=0,d.z=0,d.w=0,d.next=function(){var h=d.x^d.x<<11;return d.x=d.y,d.y=d.z,d.z=d.w,d.w^=d.w>>>19^h^h>>>8},l===(l|0)?d.x=l:u+=l;for(var p=0;p<u.length+64;p++)d.x^=u.charCodeAt(p)|0,d.next()}function i(l,d){return d.x=l.x,d.y=l.y,d.z=l.z,d.w=l.w,d}function o(l,d){var u=new s(l),p=d&&d.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var c=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(c+f)/(1<<21);while(m===0);return m},h.int32=u.next,h.quick=h,p&&(typeof p=="object"&&i(p,u),h.state=function(){return i(u,{})}),h}a&&a.exports?a.exports=o:n&&n.amd?n(function(){return o}):this.xor128=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),gE=sr({"src/node_modules/seedrandom/lib/xorwow.js"(e,t){(function(r,a,n){function s(l){var d=this,u="";d.next=function(){var h=d.x^d.x>>>2;return d.x=d.y,d.y=d.z,d.z=d.w,d.w=d.v,(d.d=d.d+362437|0)+(d.v=d.v^d.v<<4^(h^h<<1))|0},d.x=0,d.y=0,d.z=0,d.w=0,d.v=0,l===(l|0)?d.x=l:u+=l;for(var p=0;p<u.length+64;p++)d.x^=u.charCodeAt(p)|0,p==u.length&&(d.d=d.x<<10^d.x>>>4),d.next()}function i(l,d){return d.x=l.x,d.y=l.y,d.z=l.z,d.w=l.w,d.v=l.v,d.d=l.d,d}function o(l,d){var u=new s(l),p=d&&d.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var c=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(c+f)/(1<<21);while(m===0);return m},h.int32=u.next,h.quick=h,p&&(typeof p=="object"&&i(p,u),h.state=function(){return i(u,{})}),h}a&&a.exports?a.exports=o:n&&n.amd?n(function(){return o}):this.xorwow=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),yE=sr({"src/node_modules/seedrandom/lib/xorshift7.js"(e,t){(function(r,a,n){function s(l){var d=this;d.next=function(){var p=d.x,h=d.i,c,f,m;return c=p[h],c^=c>>>7,f=c^c<<24,c=p[h+1&7],f^=c^c>>>10,c=p[h+3&7],f^=c^c>>>3,c=p[h+4&7],f^=c^c<<7,c=p[h+7&7],c=c^c<<13,f^=c^c<<9,p[h]=f,d.i=h+1&7,f};function u(p,h){var c,f,m=[];if(h===(h|0))f=m[0]=h;else for(h=""+h,c=0;c<h.length;++c)m[c&7]=m[c&7]<<15^h.charCodeAt(c)+m[c+1&7]<<13;for(;m.length<8;)m.push(0);for(c=0;c<8&&m[c]===0;++c);for(c==8?f=m[7]=-1:f=m[c],p.x=m,p.i=0,c=256;c>0;--c)p.next()}u(d,l)}function i(l,d){return d.x=l.x.slice(),d.i=l.i,d}function o(l,d){l==null&&(l=+new Date);var u=new s(l),p=d&&d.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var c=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(c+f)/(1<<21);while(m===0);return m},h.int32=u.next,h.quick=h,p&&(p.x&&i(p,u),h.state=function(){return i(u,{})}),h}a&&a.exports?a.exports=o:n&&n.amd?n(function(){return o}):this.xorshift7=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),AE=sr({"src/node_modules/seedrandom/lib/xor4096.js"(e,t){(function(r,a,n){function s(l){var d=this;d.next=function(){var p=d.w,h=d.X,c=d.i,f,m;return d.w=p=p+1640531527|0,m=h[c+34&127],f=h[c=c+1&127],m^=m<<13,f^=f<<17,m^=m>>>15,f^=f>>>12,m=h[c]=m^f,d.i=c,m+(p^p>>>16)|0};function u(p,h){var c,f,m,g,y,A=[],x=128;for(h===(h|0)?(f=h,h=null):(h=h+"\0",f=0,x=Math.max(x,h.length)),m=0,g=-32;g<x;++g)h&&(f^=h.charCodeAt((g+32)%h.length)),g===0&&(y=f),f^=f<<10,f^=f>>>15,f^=f<<4,f^=f>>>13,g>=0&&(y=y+1640531527|0,c=A[g&127]^=f+y,m=c==0?m+1:0);for(m>=128&&(A[(h&&h.length||0)&127]=-1),m=127,g=4*128;g>0;--g)f=A[m+34&127],c=A[m=m+1&127],f^=f<<13,c^=c<<17,f^=f>>>15,c^=c>>>12,A[m]=f^c;p.w=y,p.X=A,p.i=m}u(d,l)}function i(l,d){return d.i=l.i,d.w=l.w,d.X=l.X.slice(),d}function o(l,d){l==null&&(l=+new Date);var u=new s(l),p=d&&d.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var c=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(c+f)/(1<<21);while(m===0);return m},h.int32=u.next,h.quick=h,p&&(p.X&&i(p,u),h.state=function(){return i(u,{})}),h}a&&a.exports?a.exports=o:n&&n.amd?n(function(){return o}):this.xor4096=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),xE=sr({"src/node_modules/seedrandom/lib/tychei.js"(e,t){(function(r,a,n){function s(l){var d=this,u="";d.next=function(){var h=d.b,c=d.c,f=d.d,m=d.a;return h=h<<25^h>>>7^c,c=c-f|0,f=f<<24^f>>>8^m,m=m-h|0,d.b=h=h<<20^h>>>12^c,d.c=c=c-f|0,d.d=f<<16^c>>>16^m,d.a=m-h|0},d.a=0,d.b=0,d.c=-1640531527,d.d=1367130551,l===Math.floor(l)?(d.a=l/4294967296|0,d.b=l|0):u+=l;for(var p=0;p<u.length+20;p++)d.b^=u.charCodeAt(p)|0,d.next()}function i(l,d){return d.a=l.a,d.b=l.b,d.c=l.c,d.d=l.d,d}function o(l,d){var u=new s(l),p=d&&d.state,h=function(){return(u.next()>>>0)/4294967296};return h.double=function(){do var c=u.next()>>>11,f=(u.next()>>>0)/4294967296,m=(c+f)/(1<<21);while(m===0);return m},h.int32=u.next,h.quick=h,p&&(typeof p=="object"&&i(p,u),h.state=function(){return i(u,{})}),h}a&&a.exports?a.exports=o:n&&n.amd?n(function(){return o}):this.tychei=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),bE=sr({"(disabled):crypto"(){}}),vE=sr({"src/node_modules/seedrandom/seedrandom.js"(e,t){(function(r,a,n){var s=256,i=6,o=52,l="random",d=n.pow(s,i),u=n.pow(2,o),p=u*2,h=s-1,c;function f(v,C,T){var E=[];C=C==!0?{entropy:!0}:C||{};var R=A(y(C.entropy?[v,b(a)]:v==null?x():v,3),E),z=new m(E),M=function(){for(var I=z.g(i),D=d,O=0;I<u;)I=(I+O)*s,D*=s,O=z.g(1);for(;I>=p;)I/=2,D/=2,O>>>=1;return(I+O)/D};return M.int32=function(){return z.g(4)|0},M.quick=function(){return z.g(4)/4294967296},M.double=M,A(b(z.S),a),(C.pass||T||function(I,D,O,j){return j&&(j.S&&g(j,z),I.state=function(){return g(z,{})}),O?(n[l]=I,D):I})(M,R,"global"in C?C.global:this==n,C.state)}function m(v){var C,T=v.length,E=this,R=0,z=E.i=E.j=0,M=E.S=[];for(T||(v=[T++]);R<s;)M[R]=R++;for(R=0;R<s;R++)M[R]=M[z=h&z+v[R%T]+(C=M[R])],M[z]=C;(E.g=function(I){for(var D,O=0,j=E.i,X=E.j,_=E.S;I--;)D=_[j=h&j+1],O=O*s+_[h&(_[j]=_[X=h&X+D])+(_[X]=D)];return E.i=j,E.j=X,O})(s)}function g(v,C){return C.i=v.i,C.j=v.j,C.S=v.S.slice(),C}function y(v,C){var T=[],E=typeof v,R;if(C&&E=="object")for(R in v)try{T.push(y(v[R],C-1))}catch(z){}return T.length?T:E=="string"?v:v+"\0"}function A(v,C){for(var T=v+"",E,R=0;R<T.length;)C[h&R]=h&(E^=C[h&R]*19)+T.charCodeAt(R++);return b(C)}function x(){try{var v;return c&&(v=c.randomBytes)?v=v(s):(v=new Uint8Array(s),(r.crypto||r.msCrypto).getRandomValues(v)),b(v)}catch(E){var C=r.navigator,T=C&&C.plugins;return[+new Date,r,T,r.screen,b(a)]}}function b(v){return String.fromCharCode.apply(0,v)}if(A(n.random(),a),typeof t=="object"&&t.exports){t.exports=f;try{c=bE()}catch(v){}}else typeof define=="function"&&define.amd?define(function(){return f}):n["seed"+l]=f})(typeof self!="undefined"?self:e,[],Math)}}),kf=sr({"src/node_modules/seedrandom/index.js"(e,t){var r=fE(),a=mE(),n=gE(),s=yE(),i=AE(),o=xE(),l=vE();l.alea=r,l.xor128=a,l.xorwow=n,l.xorshift7=s,l.xor4096=i,l.tychei=o,t.exports=l}}),wv=sr({"(disabled):src/node_modules/string_decoder/index.js"(){}}),Hc=sr({"(disabled):fs"(){}}),yp=sr({"(disabled):path"(){}}),wE=sr({"(disabled):worker_threads"(){}}),kE=sr({"(disabled):perf_hooks"(){}}),IE=sr({"(disabled):os"(){}}),SE=sr({"src/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm-threaded-simd.js"(e,t){var r=function(){var a=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(a=a||__filename),function(n){n=n||{};function s(){return ie.buffer!=ut&&ia(ie.buffer),qr}function i(){return ie.buffer!=ut&&ia(ie.buffer),gr}function o(){return ie.buffer!=ut&&ia(ie.buffer),Xr}function l(){return ie.buffer!=ut&&ia(ie.buffer),Rr}function d(){return ie.buffer!=ut&&ia(ie.buffer),xn}var u=typeof n!="undefined"?n:{},p,h;u.ready=new Promise(function(S,F){p=S,h=F});var c;typeof process!="undefined"&&process.listeners&&(c={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var f={},m;for(m in u)u.hasOwnProperty(m)&&(f[m]=u[m]);var g=[],y="./this.program",A=function(S,F){throw F},x=!1,b=!1,v=!1,C=!1;x=typeof window=="object",b=typeof importScripts=="function",v=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",C=!x&&!v&&!b;var T=u.ENVIRONMENT_IS_PTHREAD||!1;T&&(ut=u.buffer);var E="";function R(S){return u.locateFile?u.locateFile(S,E):E+S}var z,M,I,D,O,j;if(v){b?E=yp().dirname(E)+"/":E=__dirname+"/",z=function(S,F){return O||(O=Hc()),j||(j=yp()),S=j.normalize(S),O.readFileSync(S,F?null:"utf8")},I=function(S){var F=z(S,!0);return F.buffer||(F=new Uint8Array(F)),Re(F.buffer),F},process.argv.length>1&&(y=process.argv[1].replace(/\\/g,"/")),g=process.argv.slice(2),process.on("uncaughtException",function(S){if(!(S instanceof Jd))throw S}),process.on("unhandledRejection",Dn),A=function(S){process.exit(S)},u.inspect=function(){return"[Emscripten Module object]"};var X;try{X=wE()}catch(S){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),S}global.Worker=X.Worker}else C?(typeof read!="undefined"&&(z=function(S){return read(S)}),I=function(S){var F;return typeof readbuffer=="function"?new Uint8Array(readbuffer(S)):(F=read(S,"binary"),Re(typeof F=="object"),F)},typeof scriptArgs!="undefined"?g=scriptArgs:typeof arguments!="undefined"&&(g=arguments),typeof quit=="function"&&(A=function(S){quit(S)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(x||b)&&(b?E=self.location.href:typeof document!="undefined"&&document.currentScript&&(E=document.currentScript.src),typeof a!="undefined"&&a&&(E=a),E.indexOf("blob:")!==0?E=E.substr(0,E.lastIndexOf("/")+1):E="",v?(z=function(S,F){return O||(O=Hc()),j||(j=yp()),S=j.normalize(S),O.readFileSync(S,F?null:"utf8")},I=function(S){var F=z(S,!0);return F.buffer||(F=new Uint8Array(F)),Re(F.buffer),F}):(z=function(S){var F=new XMLHttpRequest;return F.open("GET",S,!1),F.send(null),F.responseText},b&&(I=function(S){var F=new XMLHttpRequest;return F.open("GET",S,!1),F.responseType="arraybuffer",F.send(null),new Uint8Array(F.response)}),M=function(S,F,G){var J=new XMLHttpRequest;J.open("GET",S,!0),J.responseType="arraybuffer",J.onload=function(){if(J.status==200||J.status==0&&J.response){F(J.response);return}G()},J.onerror=G,J.send(null)}),D=function(S){document.title=S});v&&typeof performance=="undefined"&&(global.performance=kE().performance);var _=u.print||console.log.bind(console),K=u.printErr||console.warn.bind(console);for(m in f)f.hasOwnProperty(m)&&(u[m]=f[m]);f=null,u.arguments&&(g=u.arguments),u.thisProgram&&(y=u.thisProgram),u.quit&&(A=u.quit);function W(S){W.shown||(W.shown={}),W.shown[S]||(W.shown[S]=1,K(S))}var ee=Atomics.load,Q=Atomics.store,ne=Atomics.compareExchange,Z;u.wasmBinary&&(Z=u.wasmBinary);var ae=u.noExitRuntime||!0;typeof WebAssembly!="object"&&Dn("no native wasm support detected");var ie,xe,be=!1,Te;function Re(S,F){S||Dn("Assertion failed: "+F)}function $e(S){var F=u["_"+S];return Re(F,"Cannot call unknown function "+S+", make sure it is exported"),F}function _e(S,F,G,J,Ae){var ge={string:function(Qr){var Kl=0;if(Qr!=null&&Qr!==0){var _5=(Qr.length<<2)+1;Kl=jl(_5),ct(Qr,Kl,_5)}return Kl},array:function(Qr){var Kl=jl(Qr.length);return Et(Qr,Kl),Kl}};function ye(Qr){return F==="string"?st(Qr):F==="boolean"?Boolean(Qr):Qr}var Ce=$e(S),ft=[],lr=0;if(J)for(var Jt=0;Jt<J.length;Jt++){var As=ge[G[Jt]];As?(lr===0&&(lr=Yd()),ft[Jt]=As(J[Jt])):ft[Jt]=J[Jt]}var ql=Ce.apply(null,ft);return ql=ye(ql),lr!==0&&Gl(lr),ql}function qe(S,F,G,J){G=G||[];var Ae=G.every(function(ye){return ye==="number"}),ge=F!=="string";return ge&&Ae&&!J?$e(S):function(){return _e(S,F,G,arguments,J)}}function Ze(S,F,G){for(var J=F+G,Ae="";!(F>=J);){var ge=S[F++];if(!ge)return Ae;if(!(ge&128)){Ae+=String.fromCharCode(ge);continue}var ye=S[F++]&63;if((ge&224)==192){Ae+=String.fromCharCode((ge&31)<<6|ye);continue}var Ce=S[F++]&63;if((ge&240)==224?ge=(ge&15)<<12|ye<<6|Ce:ge=(ge&7)<<18|ye<<12|Ce<<6|S[F++]&63,ge<65536)Ae+=String.fromCharCode(ge);else{var ft=ge-65536;Ae+=String.fromCharCode(55296|ft>>10,56320|ft&1023)}}return Ae}function st(S,F){return S?Ze(i(),S,F):""}function ht(S,F,G,J){if(!(J>0))return 0;for(var Ae=G,ge=G+J-1,ye=0;ye<S.length;++ye){var Ce=S.charCodeAt(ye);if(Ce>=55296&&Ce<=57343){var ft=S.charCodeAt(++ye);Ce=65536+((Ce&1023)<<10)|ft&1023}if(Ce<=127){if(G>=ge)break;F[G++]=Ce}else if(Ce<=2047){if(G+1>=ge)break;F[G++]=192|Ce>>6,F[G++]=128|Ce&63}else if(Ce<=65535){if(G+2>=ge)break;F[G++]=224|Ce>>12,F[G++]=128|Ce>>6&63,F[G++]=128|Ce&63}else{if(G+3>=ge)break;F[G++]=240|Ce>>18,F[G++]=128|Ce>>12&63,F[G++]=128|Ce>>6&63,F[G++]=128|Ce&63}}return F[G]=0,G-Ae}function ct(S,F,G){return ht(S,i(),F,G)}function yt(S){for(var F=0,G=0;G<S.length;++G){var J=S.charCodeAt(G);J>=55296&&J<=57343&&(J=65536+((J&1023)<<10)|S.charCodeAt(++G)&1023),J<=127?++F:J<=2047?F+=2:J<=65535?F+=3:F+=4}return F}function Et(S,F){s().set(S,F)}function Hr(S,F){return S%F>0&&(S+=F-S%F),S}var ut,qr,gr,Kr,za,Xr,Rr,Da,xn;function ia(S){ut=S,u.HEAP8=qr=new Int8Array(S),u.HEAP16=Kr=new Int16Array(S),u.HEAP32=Xr=new Int32Array(S),u.HEAPU8=gr=new Uint8Array(S),u.HEAPU16=za=new Uint16Array(S),u.HEAPU32=Rr=new Uint32Array(S),u.HEAPF32=Da=new Float32Array(S),u.HEAPF64=xn=new Float64Array(S)}var _l=u.INITIAL_MEMORY||16777216;if(T)ie=u.wasmMemory,ut=u.buffer;else if(u.wasmMemory)ie=u.wasmMemory;else if(ie=new WebAssembly.Memory({initial:_l/65536,maximum:32768,shared:!0}),!(ie.buffer instanceof SharedArrayBuffer))throw K("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),v&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");ie&&(ut=ie.buffer),_l=ut.byteLength,ia(ut);var Zr,hs=[],va=[],Bd=[],Wd=[],zn=[],Zh=!1,U0=!1;T||va.push({func:function(){fc()}});function Yh(){if(!T){if(u.preRun)for(typeof u.preRun=="function"&&(u.preRun=[u.preRun]);u.preRun.length;)G0(u.preRun.shift());Ll(hs)}}function Jh(){Zh=!0,!T&&Ll(va)}function Qh(){T||Ll(Bd)}function Yr(){T||(U0=!0)}function ec(){if(!T){if(u.postRun)for(typeof u.postRun=="function"&&(u.postRun=[u.postRun]);u.postRun.length;)j0(u.postRun.shift());Ll(zn)}}function G0(S){hs.unshift(S)}function j0(S){zn.unshift(S)}var _a=0,Vd=null,Ji=null;function H0(S){Re(!T,"addRunDependency cannot be used in a pthread worker"),_a++,u.monitorRunDependencies&&u.monitorRunDependencies(_a)}function q0(S){if(_a--,u.monitorRunDependencies&&u.monitorRunDependencies(_a),_a==0&&(Vd!==null&&(clearInterval(Vd),Vd=null),Ji)){var F=Ji;Ji=null,F()}}u.preloadedImages={},u.preloadedAudios={};function Dn(S){u.onAbort&&u.onAbort(S),T&&console.error("Pthread aborting at "+new Error().stack),S+="",K(S),be=!0,Te=1,S="abort("+S+"). Build with -s ASSERTIONS=1 for more info.";var F=new WebAssembly.RuntimeError(S);throw h(F),F}function Qi(S,F){return String.prototype.startsWith?S.startsWith(F):S.indexOf(F)===0}var K0="data:application/octet-stream;base64,";function tc(S){return Qi(S,K0)}var X0="file://";function rc(S){return Qi(S,X0)}var Jr="tfjs-backend-wasm-threaded-simd.wasm";tc(Jr)||(Jr=R(Jr));function Z0(S){try{if(S==Jr&&Z)return new Uint8Array(Z);if(I)return I(S);throw"both async and sync fetching of the wasm failed"}catch(F){Dn(F)}}function ac(){if(!Z&&(x||b)){if(typeof fetch=="function"&&!rc(Jr))return fetch(Jr,{credentials:"same-origin"}).then(function(S){if(!S.ok)throw"failed to load wasm binary file at '"+Jr+"'";return S.arrayBuffer()}).catch(function(){return Z0(Jr)});if(M)return new Promise(function(S,F){M(Jr,function(G){S(new Uint8Array(G))},F)})}return Promise.resolve().then(function(){return Z0(Jr)})}function Y0(){var S={a:Ug};function F(ye,Ce){var ft=ye.exports;if(u.asm=ft,Zr=u.asm.nb,xe=Ce,!T){var lr=Fe.unusedWorkers.length;Fe.unusedWorkers.forEach(function(Jt){Fe.loadWasmModuleToWorker(Jt,function(){--lr||q0("wasm-instantiate")})})}}T||H0("wasm-instantiate");function G(ye){F(ye.instance,ye.module)}function J(ye){return ac().then(function(Ce){return WebAssembly.instantiate(Ce,S)}).then(ye,function(Ce){K("failed to asynchronously prepare wasm: "+Ce),Dn(Ce)})}function Ae(){return!Z&&typeof WebAssembly.instantiateStreaming=="function"&&!tc(Jr)&&!rc(Jr)&&typeof fetch=="function"?fetch(Jr,{credentials:"same-origin"}).then(function(ye){var Ce=WebAssembly.instantiateStreaming(ye,S);return Ce.then(G,function(ft){return K("wasm streaming compile failed: "+ft),K("falling back to ArrayBuffer instantiation"),J(G)})}):J(G)}if(u.instantiateWasm)try{var ge=u.instantiateWasm(S,F);return ge}catch(ye){return K("Module.instantiateWasm callback failed with error: "+ye),!1}return Ae().catch(h),{}}var nc={10216:function(){throw"Canceled!"},10234:function(S,F){setTimeout(function(){M5(S,F)},0)}};function J0(){Fe.initRuntime()}function Ll(S){for(;S.length>0;){var F=S.shift();if(typeof F=="function"){F(u);continue}var G=F.func;typeof G=="number"?F.arg===void 0?Zr.get(G)():Zr.get(G)(F.arg):G(F.arg===void 0?null:F.arg)}}var cs={EPERM:63,ENOENT:44,ESRCH:71,EINTR:27,EIO:29,ENXIO:60,E2BIG:1,ENOEXEC:45,EBADF:8,ECHILD:12,EAGAIN:6,EWOULDBLOCK:6,ENOMEM:48,EACCES:2,EFAULT:21,ENOTBLK:105,EBUSY:10,EEXIST:20,EXDEV:75,ENODEV:43,ENOTDIR:54,EISDIR:31,EINVAL:28,ENFILE:41,EMFILE:33,ENOTTY:59,ETXTBSY:74,EFBIG:22,ENOSPC:51,ESPIPE:70,EROFS:69,EMLINK:34,EPIPE:64,EDOM:18,ERANGE:68,ENOMSG:49,EIDRM:24,ECHRNG:106,EL2NSYNC:156,EL3HLT:107,EL3RST:108,ELNRNG:109,EUNATCH:110,ENOCSI:111,EL2HLT:112,EDEADLK:16,ENOLCK:46,EBADE:113,EBADR:114,EXFULL:115,ENOANO:104,EBADRQC:103,EBADSLT:102,EDEADLOCK:16,EBFONT:101,ENOSTR:100,ENODATA:116,ETIME:117,ENOSR:118,ENONET:119,ENOPKG:120,EREMOTE:121,ENOLINK:47,EADV:122,ESRMNT:123,ECOMM:124,EPROTO:65,EMULTIHOP:36,EDOTDOT:125,EBADMSG:9,ENOTUNIQ:126,EBADFD:127,EREMCHG:128,ELIBACC:129,ELIBBAD:130,ELIBSCN:131,ELIBMAX:132,ELIBEXEC:133,ENOSYS:52,ENOTEMPTY:55,ENAMETOOLONG:37,ELOOP:32,EOPNOTSUPP:138,EPFNOSUPPORT:139,ECONNRESET:15,ENOBUFS:42,EAFNOSUPPORT:5,EPROTOTYPE:67,ENOTSOCK:57,ENOPROTOOPT:50,ESHUTDOWN:140,ECONNREFUSED:14,EADDRINUSE:3,ECONNABORTED:13,ENETUNREACH:40,ENETDOWN:38,ETIMEDOUT:73,EHOSTDOWN:142,EHOSTUNREACH:23,EINPROGRESS:26,EALREADY:7,EDESTADDRREQ:17,EMSGSIZE:35,EPROTONOSUPPORT:66,ESOCKTNOSUPPORT:137,EADDRNOTAVAIL:4,ENETRESET:39,EISCONN:30,ENOTCONN:53,ETOOMANYREFS:141,EUSERS:136,EDQUOT:19,ESTALE:72,ENOTSUP:138,ENOMEDIUM:148,EILSEQ:25,EOVERFLOW:61,ECANCELED:11,ENOTRECOVERABLE:56,EOWNERDEAD:62,ESTRPIPE:135};function Ud(S,F){if(S<=0||S>s().length||S&!0||F<0)return-28;if(F==0)return 0;F>=2147483647&&(F=1/0);var G=Atomics.load(o(),Hl>>2),J=0;if(G==S){var Ae=Atomics.compareExchange(o(),Hl>>2,G,0);if(Ae==G&&(--F,J=1,F<=0))return 1}var ge=Atomics.notify(o(),S>>2,F);if(ge>=0)return ge+J;throw"Atomics.notify returned an unexpected value "+ge}u._emscripten_futex_wake=Ud;function Q0(S){if(T)throw"Internal Error! killThread() can only ever be called from main application thread!";if(!S)throw"Internal Error! Null pthread_ptr in killThread!";o()[S+12>>2]=0;var F=Fe.pthreads[S];F.worker.terminate(),Fe.freeThreadData(F),Fe.runningWorkers.splice(Fe.runningWorkers.indexOf(F.worker),1),F.worker.pthread=void 0}function eg(S){if(T)throw"Internal Error! cancelThread() can only ever be called from main application thread!";if(!S)throw"Internal Error! Null pthread_ptr in cancelThread!";var F=Fe.pthreads[S];F.worker.postMessage({cmd:"cancel"})}function sc(S){if(T)throw"Internal Error! cleanupThread() can only ever be called from main application thread!";if(!S)throw"Internal Error! Null pthread_ptr in cleanupThread!";var F=Fe.pthreads[S];if(F){o()[S+12>>2]=0;var G=F.worker;Fe.returnWorkerToPool(G)}}var Fe={unusedWorkers:[],runningWorkers:[],initMainThreadBlock:function(){for(var S=8,F=0;F<S;++F)Fe.allocateUnusedWorker()},initRuntime:function(){for(var S=to(228),F=0;F<228/4;++F)l()[S/4+F]=0;o()[S+12>>2]=S;var G=S+152;o()[G>>2]=G;for(var J=to(512),F=0;F<128;++F)l()[J/4+F]=0;Atomics.store(l(),S+100>>2,J),Atomics.store(l(),S+40>>2,S),c1(S,!b,1),R5(S)},initWorker:function(){},pthreads:{},threadExitHandlers:[],setThreadStatus:function(){},runExitHandlers:function(){for(;Fe.threadExitHandlers.length>0;)Fe.threadExitHandlers.pop()();T&&ys()&&E5()},runExitHandlersAndDeinitThread:function(S,F){Atomics.store(l(),S+56>>2,1),Atomics.store(l(),S+60>>2,0),Fe.runExitHandlers(),Atomics.store(l(),S+4>>2,F),Atomics.store(l(),S+0>>2,1),Ud(S+0,2147483647),c1(0,0,0)},threadExit:function(S){var F=ys();F&&(Fe.runExitHandlersAndDeinitThread(F,S),T&&postMessage({cmd:"exit"}))},threadCancel:function(){Fe.runExitHandlersAndDeinitThread(ys(),-1),postMessage({cmd:"cancelDone"})},terminateAllThreads:function(){for(var S in Fe.pthreads){var F=Fe.pthreads[S];F&&F.worker&&Fe.returnWorkerToPool(F.worker)}Fe.pthreads={};for(var G=0;G<Fe.unusedWorkers.length;++G){var J=Fe.unusedWorkers[G];J.terminate()}Fe.unusedWorkers=[];for(var G=0;G<Fe.runningWorkers.length;++G){var J=Fe.runningWorkers[G],F=J.pthread;Fe.freeThreadData(F),J.terminate()}Fe.runningWorkers=[]},freeThreadData:function(S){if(S){if(S.threadInfoStruct){var F=o()[S.threadInfoStruct+100>>2];o()[S.threadInfoStruct+100>>2]=0,Zd(F),Zd(S.threadInfoStruct)}S.threadInfoStruct=0,S.allocatedOwnStack&&S.stackBase&&Zd(S.stackBase),S.stackBase=0,S.worker&&(S.worker.pthread=null)}},returnWorkerToPool:function(S){Fe.runWithoutMainThreadQueuedCalls(function(){delete Fe.pthreads[S.pthread.threadInfoStruct],Fe.unusedWorkers.push(S),Fe.runningWorkers.splice(Fe.runningWorkers.indexOf(S),1),Fe.freeThreadData(S.pthread),S.pthread=void 0})},runWithoutMainThreadQueuedCalls:function(S){o()[D5>>2]=0;try{S()}finally{o()[D5>>2]=1}},receiveObjectTransfer:function(S){},loadWasmModuleToWorker:function(S,F){S.onmessage=function(G){var J=G.data,Ae=J.cmd;if(S.pthread&&(Fe.currentProxiedOperationCallerThread=S.pthread.threadInfoStruct),J.targetThread&&J.targetThread!=ys()){var ge=Fe.pthreads[J.targetThread];ge?ge.worker.postMessage(G.data,J.transferList):console.error('Internal error! Worker sent a message "'+Ae+'" to target pthread '+J.targetThread+", but that thread no longer exists!"),Fe.currentProxiedOperationCallerThread=void 0;return}if(Ae==="processQueuedMainThreadWork")xc();else if(Ae==="spawnThread")hc(G.data);else if(Ae==="cleanupThread")sc(J.thread);else if(Ae==="killThread")Q0(J.thread);else if(Ae==="cancelThread")eg(J.thread);else if(Ae==="loaded")S.loaded=!0,F&&F(S),S.runPthread&&(S.runPthread(),delete S.runPthread);else if(Ae==="print")_("Thread "+J.threadId+": "+J.text);else if(Ae==="printErr")K("Thread "+J.threadId+": "+J.text);else if(Ae==="alert")alert("Thread "+J.threadId+": "+J.text);else if(Ae==="exit"){var ye=S.pthread&&Atomics.load(l(),S.pthread.threadInfoStruct+64>>2);ye&&Fe.returnWorkerToPool(S)}else if(Ae==="exitProcess")try{Z9(J.returnCode)}catch(Ce){if(Ce instanceof Jd)return;throw Ce}else Ae==="cancelDone"?Fe.returnWorkerToPool(S):Ae==="objectTransfer"?Fe.receiveObjectTransfer(G.data):G.data.target==="setimmediate"?S.postMessage(G.data):K("worker sent an unknown command "+Ae);Fe.currentProxiedOperationCallerThread=void 0},S.onerror=function(G){K("pthread sent an error! "+G.filename+":"+G.lineno+": "+G.message)},v&&(S.on("message",function(G){S.onmessage({data:G})}),S.on("error",function(G){S.onerror(G)}),S.on("exit",function(G){})),S.postMessage({cmd:"load",urlOrBlob:u.mainScriptUrlOrBlob||a,wasmMemory:ie,wasmModule:xe})},allocateUnusedWorker:function(){var S=R("tfjs-backend-wasm-threaded-simd.worker.js");Fe.unusedWorkers.push(new Worker(S))},getNewWorker:function(){return Fe.unusedWorkers.length==0&&(Fe.allocateUnusedWorker(),Fe.loadWasmModuleToWorker(Fe.unusedWorkers[0])),Fe.unusedWorkers.length>0?Fe.unusedWorkers.pop():null},busySpinWait:function(S){for(var F=performance.now()+S;performance.now()<F;);}};function tg(S,F){O5(S,F),Gl(S)}u.establishStackSpace=tg;function rg(){return ae}u.getNoExitRuntime=rg;function ag(S,F){return Zr.get(S)(F)}u.invokeEntryPoint=ag;function ng(S,F,G,J){Dn("Assertion failed: "+st(S)+", at: "+[F?st(F):"unknown filename",G,J?st(J):"unknown function"])}function sg(S,F){var G=_main(S,F)}var eo;v?eo=function(){var S=process.hrtime();return S[0]*1e3+S[1]/1e6}:T?eo=function(){return performance.now()-u.__performance_now_clock_drift}:typeof dateNow!="undefined"?eo=dateNow:eo=function(){return performance.now()};function ig(S){return o()[C5()>>2]=S,S}function og(S,F){if(T)return fs(1,1,S,F)}function lg(S,F){if(S==F)postMessage({cmd:"processQueuedMainThreadWork"});else if(T)postMessage({targetThread:S,cmd:"processThreadQueue"});else{var G=Fe.pthreads[S],J=G&&G.worker;if(!J)return;J.postMessage({cmd:"processThreadQueue"})}return 1}function ug(){Dn()}function dg(S,F,G){var J=fg(F,G);return nc[S].apply(null,J)}function pg(S,F){}function ic(S,F,G){if(S<=0||S>s().length||S&!0)return-28;if(x){if(Atomics.load(o(),S>>2)!=F)return-6;for(var J=performance.now(),Ae=J+G,ge=Atomics.exchange(o(),Hl>>2,S);;){if(J=performance.now(),J>Ae)return ge=Atomics.exchange(o(),Hl>>2,0),-73;if(ge=Atomics.exchange(o(),Hl>>2,0),ge==0)break;if(xc(),Atomics.load(o(),S>>2)!=F)return-6;ge=Atomics.exchange(o(),Hl>>2,S)}return 0}else{var ye=Atomics.wait(o(),S>>2,F,G);if(ye==="timed-out")return-73;if(ye==="not-equal")return-6;if(ye==="ok")return 0;throw"Atomics.wait returned an unexpected value "+ye}}function hg(S,F,G){i().copyWithin(S,F,F+G)}function cg(){return v?IE().cpus().length:navigator.hardwareConcurrency}function fs(S,F){for(var G=arguments.length-2,J=Yd(),Ae=G,ge=jl(Ae*8),ye=ge>>3,Ce=0;Ce<G;Ce++){var ft=arguments[2+Ce];d()[ye+Ce]=ft}var lr=P5(S,Ae,ge,F);return Gl(J),lr}var Gd=[],jd=[];function fg(S,F){jd.length=0;var G;for(F>>=2;G=i()[S++];){var J=G<105;J&&F&1&&F++,jd.push(J?d()[F++>>1]:o()[F]),++F}return jd}function mg(S,F,G){Gd.length=F;for(var J=G>>3,Ae=0;Ae<F;Ae++)Gd[Ae]=d()[J+Ae];var ge=S<0,ye=ge?nc[-S-1]:Vg[S];return ye.apply(null,Gd)}function gg(){return i().length}function yg(S){try{return ie.grow(S-ut.byteLength+65535>>>16),ia(ie.buffer),1}catch(F){}}function Ag(S){var F=gg();if(S<=F)return!1;var G=2147483648;if(S>G)return!1;for(var J=1;J<=4;J*=2){var Ae=F*(1+.2/J);Ae=Math.min(Ae,S+100663296);var ge=Math.min(G,Hr(Math.max(S,Ae),65536)),ye=yg(ge);if(ye)return!0}return!1}var je={inEventHandler:0,removeAllEventListeners:function(){for(var S=je.eventHandlers.length-1;S>=0;--S)je._removeHandler(S);je.eventHandlers=[],je.deferredCalls=[]},registerRemoveEventListeners:function(){je.removeEventListenersRegistered||(Wd.push(je.removeAllEventListeners),je.removeEventListenersRegistered=!0)},deferredCalls:[],deferCall:function(S,F,G){function J(ye,Ce){if(ye.length!=Ce.length)return!1;for(var ft in ye)if(ye[ft]!=Ce[ft])return!1;return!0}for(var Ae in je.deferredCalls){var ge=je.deferredCalls[Ae];if(ge.targetFunction==S&&J(ge.argsList,G))return}je.deferredCalls.push({targetFunction:S,precedence:F,argsList:G}),je.deferredCalls.sort(function(ye,Ce){return ye.precedence<Ce.precedence})},removeDeferredCalls:function(S){for(var F=0;F<je.deferredCalls.length;++F)je.deferredCalls[F].targetFunction==S&&(je.deferredCalls.splice(F,1),--F)},canPerformEventHandlerRequests:function(){return je.inEventHandler&&je.currentEventHandler.allowsDeferredCalls},runDeferredCalls:function(){if(je.canPerformEventHandlerRequests())for(var S=0;S<je.deferredCalls.length;++S){var F=je.deferredCalls[S];je.deferredCalls.splice(S,1),--S,F.targetFunction.apply(null,F.argsList)}},eventHandlers:[],removeAllHandlersOnTarget:function(S,F){for(var G=0;G<je.eventHandlers.length;++G)je.eventHandlers[G].target==S&&(!F||F==je.eventHandlers[G].eventTypeString)&&je._removeHandler(G--)},_removeHandler:function(S){var F=je.eventHandlers[S];F.target.removeEventListener(F.eventTypeString,F.eventListenerFunc,F.useCapture),je.eventHandlers.splice(S,1)},registerOrRemoveHandler:function(S){var F=function(J){++je.inEventHandler,je.currentEventHandler=S,je.runDeferredCalls(),S.handlerFunc(J),je.runDeferredCalls(),--je.inEventHandler};if(S.callbackfunc)S.eventListenerFunc=F,S.target.addEventListener(S.eventTypeString,F,S.useCapture),je.eventHandlers.push(S),je.registerRemoveEventListeners();else for(var G=0;G<je.eventHandlers.length;++G)je.eventHandlers[G].target==S.target&&je.eventHandlers[G].eventTypeString==S.eventTypeString&&je._removeHandler(G--)},queueEventHandlerOnThread_iiii:function(S,F,G,J,Ae){var ge=Yd(),ye=jl(12);o()[ye>>2]=G,o()[ye+4>>2]=J,o()[ye+8>>2]=Ae,h1(0,S,637534208,F,J,ye),Gl(ge)},getTargetThreadForEventCallback:function(S){switch(S){case 1:return 0;case 2:return Fe.currentProxiedOperationCallerThread;default:return S}},getNodeNameForTarget:function(S){return S?S==window?"#window":S==screen?"#screen":S&&S.nodeName?S.nodeName:"":""},fullscreenEnabled:function(){return document.fullscreenEnabled||document.webkitFullscreenEnabled}};function xg(S){var F=yt(S)+1,G=to(F);return ct(S,G,F),G}function bg(S,F,G,J){var Ae=Yd(),ge=jl(12),ye=0;F&&(ye=xg(F)),o()[ge>>2]=ye,o()[ge+4>>2]=G,o()[ge+8>>2]=J,h1(0,S,657457152,0,ye,ge),Gl(Ae)}function vg(S,F,G,J){F=F?st(F):"",bg(S,F,G,J)}function wg(S){return S>2?st(S):S}var kg=[0,typeof document!="undefined"?document:0,typeof window!="undefined"?window:0];function Ig(S){S=wg(S);var F=kg[S]||(typeof document!="undefined"?document.querySelector(S):void 0);return F}function Hd(S){return Ig(S)}function oc(S,F,G){var J=Hd(S);if(!J)return-4;if(J.canvasSharedPtr&&(o()[J.canvasSharedPtr>>2]=F,o()[J.canvasSharedPtr+4>>2]=G),J.offscreenCanvas||!J.controlTransferredOffscreen){J.offscreenCanvas&&(J=J.offscreenCanvas);var Ae=!1;if(J.GLctxObject&&J.GLctxObject.GLctx){var ge=J.GLctxObject.GLctx.getParameter(2978);Ae=ge[0]===0&&ge[1]===0&&ge[2]===J.width&&ge[3]===J.height}J.width=F,J.height=G,Ae&&J.GLctxObject.GLctx.viewport(0,0,F,G)}else if(J.canvasSharedPtr){var ye=o()[J.canvasSharedPtr+8>>2];return vg(ye,S,F,G),1}else return-4;return 0}function lc(S,F,G){return T?fs(2,1,S,F,G):oc(S,F,G)}function Sg(S,F,G){var J=Hd(S);return J?oc(S,F,G):lc(S,F,G)}function Tg(S){}function Cg(S,F){}function Ng(S){var F=S.getExtension("ANGLE_instanced_arrays");if(F)return S.vertexAttribDivisor=function(G,J){F.vertexAttribDivisorANGLE(G,J)},S.drawArraysInstanced=function(G,J,Ae,ge){F.drawArraysInstancedANGLE(G,J,Ae,ge)},S.drawElementsInstanced=function(G,J,Ae,ge,ye){F.drawElementsInstancedANGLE(G,J,Ae,ge,ye)},1}function Eg(S){var F=S.getExtension("OES_vertex_array_object");if(F)return S.createVertexArray=function(){return F.createVertexArrayOES()},S.deleteVertexArray=function(G){F.deleteVertexArrayOES(G)},S.bindVertexArray=function(G){F.bindVertexArrayOES(G)},S.isVertexArray=function(G){return F.isVertexArrayOES(G)},1}function Rg(S){var F=S.getExtension("WEBGL_draw_buffers");if(F)return S.drawBuffers=function(G,J){F.drawBuffersWEBGL(G,J)},1}function Fg(S){return!!(S.multiDrawWebgl=S.getExtension("WEBGL_multi_draw"))}var dt={counter:1,buffers:[],programs:[],framebuffers:[],renderbuffers:[],textures:[],uniforms:[],shaders:[],vaos:[],contexts:{},offscreenCanvases:{},timerQueriesEXT:[],programInfos:{},stringCache:{},unpackAlignment:4,recordError:function(S){dt.lastError||(dt.lastError=S)},getNewId:function(S){for(var F=dt.counter++,G=S.length;G<F;G++)S[G]=null;return F},getSource:function(S,F,G,J){for(var Ae="",ge=0;ge<F;++ge){var ye=J?o()[J+ge*4>>2]:-1;Ae+=st(o()[G+ge*4>>2],ye<0?void 0:ye)}return Ae},createContext:function(S,F){var G=S.getContext("webgl",F);if(!G)return 0;var J=dt.registerContext(G,F);return J},registerContext:function(S,F){var G=to(8);o()[G+4>>2]=ys();var J={handle:G,attributes:F,version:F.majorVersion,GLctx:S};return S.canvas&&(S.canvas.GLctxObject=J),dt.contexts[G]=J,(typeof F.enableExtensionsByDefault=="undefined"||F.enableExtensionsByDefault)&&dt.initExtensions(J),G},makeContextCurrent:function(S){return dt.currentContext=dt.contexts[S],u.ctx=ms=dt.currentContext&&dt.currentContext.GLctx,!(S&&!ms)},getContext:function(S){return dt.contexts[S]},deleteContext:function(S){dt.currentContext===dt.contexts[S]&&(dt.currentContext=null),typeof je=="object"&&je.removeAllHandlersOnTarget(dt.contexts[S].GLctx.canvas),dt.contexts[S]&&dt.contexts[S].GLctx.canvas&&(dt.contexts[S].GLctx.canvas.GLctxObject=void 0),Zd(dt.contexts[S].handle),dt.contexts[S]=null},initExtensions:function(S){if(S||(S=dt.currentContext),!S.initExtensionsDone){S.initExtensionsDone=!0;var F=S.GLctx;Ng(F),Eg(F),Rg(F),F.disjointTimerQueryExt=F.getExtension("EXT_disjoint_timer_query"),Fg(F);var G=F.getSupportedExtensions()||[];G.forEach(function(J){J.indexOf("lose_context")<0&&J.indexOf("debug")<0&&F.getExtension(J)})}},populateUniformTable:function(S){for(var F=dt.programs[S],G=dt.programInfos[S]={uniforms:{},maxUniformLength:0,maxAttributeLength:-1,maxUniformBlockNameLength:-1},J=G.uniforms,Ae=ms.getProgramParameter(F,35718),ge=0;ge<Ae;++ge){var ye=ms.getActiveUniform(F,ge),Ce=ye.name;G.maxUniformLength=Math.max(G.maxUniformLength,Ce.length+1),Ce.slice(-1)=="]"&&(Ce=Ce.slice(0,Ce.lastIndexOf("[")));var ft=ms.getUniformLocation(F,Ce);if(ft){var lr=dt.getNewId(dt.uniforms);J[Ce]=[ye.size,lr],dt.uniforms[lr]=ft;for(var Jt=1;Jt<ye.size;++Jt){var As=Ce+"["+Jt+"]";ft=ms.getUniformLocation(F,As),lr=dt.getNewId(dt.uniforms),dt.uniforms[lr]=ft}}}}},Mg=["default","low-power","high-performance"];function $g(S,F){var G=F>>2,J=o()[G+6],Ae={alpha:!!o()[G+0],depth:!!o()[G+1],stencil:!!o()[G+2],antialias:!!o()[G+3],premultipliedAlpha:!!o()[G+4],preserveDrawingBuffer:!!o()[G+5],powerPreference:Mg[J],failIfMajorPerformanceCaveat:!!o()[G+7],majorVersion:o()[G+8],minorVersion:o()[G+9],enableExtensionsByDefault:o()[G+10],explicitSwapControl:o()[G+11],proxyContextToMainThread:o()[G+12],renderViaOffscreenBackBuffer:o()[G+13]},ge=Hd(S);if(!ge||Ae.explicitSwapControl)return 0;var ye=dt.createContext(ge,Ae);return ye}function Pg(S,F){return $g(S,F)}var Bl={mappings:{},buffers:[null,[],[]],printChar:function(S,F){var G=Bl.buffers[S];F===0||F===10?((S===1?_:K)(Ze(G,0)),G.length=0):G.push(F)},varargs:void 0,get:function(){Bl.varargs+=4;var S=o()[Bl.varargs-4>>2];return S},getStr:function(S){var F=st(S);return F},get64:function(S,F){return S}};function uc(S){return T?fs(3,1,S):0}function dc(S,F,G,J,Ae){if(T)return fs(4,1,S,F,G,J,Ae)}function pc(S,F,G,J){if(T)return fs(5,1,S,F,G,J);for(var Ae=0,ge=0;ge<G;ge++){for(var ye=o()[F+ge*8>>2],Ce=o()[F+(ge*8+4)>>2],ft=0;ft<Ce;ft++)Bl.printChar(S,i()[ye+ft]);Ae+=Ce}return o()[J>>2]=Ae,0}function Og(S){var F=Fe.threadExitHandlers.pop();S&&F()}function zg(S,F){Fe.threadExitHandlers.push(function(){Zr.get(S)(F)})}function hc(S){if(T)throw"Internal Error! spawnThread() can only ever be called from main application thread!";var F=Fe.getNewWorker();if(F.pthread!==void 0)throw"Internal error!";if(!S.pthread_ptr)throw"Internal error, no pthread ptr!";Fe.runningWorkers.push(F);for(var G=to(512),J=0;J<128;++J)o()[G+J*4>>2]=0;var Ae=S.stackBase+S.stackSize,ge=Fe.pthreads[S.pthread_ptr]={worker:F,stackBase:S.stackBase,stackSize:S.stackSize,allocatedOwnStack:S.allocatedOwnStack,threadInfoStruct:S.pthread_ptr},ye=ge.threadInfoStruct>>2;Atomics.store(l(),ye+16,S.detached),Atomics.store(l(),ye+25,G),Atomics.store(l(),ye+10,ge.threadInfoStruct),Atomics.store(l(),ye+20,S.stackSize),Atomics.store(l(),ye+19,Ae),Atomics.store(l(),ye+26,S.stackSize),Atomics.store(l(),ye+28,Ae),Atomics.store(l(),ye+29,S.detached);var Ce=N5(),ft=Ce+40;Atomics.store(l(),ye+43,ft),F.pthread=ge;var lr={cmd:"run",start_routine:S.startRoutine,arg:S.arg,threadInfoStruct:S.pthread_ptr,stackBase:S.stackBase,stackSize:S.stackSize};F.runPthread=function(){lr.time=performance.now(),F.postMessage(lr,S.transferList)},F.loaded&&(F.runPthread(),delete F.runPthread)}function Dg(S,F,G,J){if(typeof SharedArrayBuffer=="undefined")return K("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;if(!S)return K("pthread_create called with a null thread pointer!"),28;var Ae=[],ge=0;if(T&&(Ae.length===0||ge))return $5(687865856,S,F,G,J);if(ge)return ge;var ye=0,Ce=0,ft=0;F&&F!=-1?(ye=o()[F>>2],ye+=81920,Ce=o()[F+8>>2],ft=o()[F+12>>2]!==0):ye=2097152;var lr=Ce==0;lr?Ce=z5(16,ye):(Ce-=ye,Re(Ce>0));for(var Jt=to(228),As=0;As<57;++As)l()[(Jt>>2)+As]=0;o()[S>>2]=Jt,o()[Jt+12>>2]=Jt;var ql=Jt+152;o()[ql>>2]=ql;var Qr={stackBase:Ce,stackSize:ye,allocatedOwnStack:lr,detached:ft,startRoutine:G,pthread_ptr:Jt,arg:J,transferList:Ae};return T?(Qr.cmd="spawnThread",postMessage(Qr,Ae)):hc(Qr),0}function _g(){if(T){var S=ys();if(S){var F=Atomics.load(l(),S+56>>2);if(!F){var G=Atomics.load(l(),S+0>>2);if(G==2)throw"Canceled!"}}}}function Lg(){v||b||W("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread")}function Bg(S,F,G){if(!S)return K("pthread_join attempted on a null thread pointer!"),cs.ESRCH;if(T&&ys()==S)return K("PThread "+S+" is attempting to join to itself!"),cs.EDEADLK;if(!T&&F5()==S)return K("Main thread "+S+" is attempting to join to itself!"),cs.EDEADLK;var J=o()[S+12>>2];if(J!==S)return K("pthread_join attempted on thread "+S+", which does not point to a valid thread, or does not exist anymore!"),cs.ESRCH;var Ae=Atomics.load(l(),S+64>>2);if(Ae)return K("Attempted to join thread "+S+", which was already detached!"),cs.EINVAL;for(G&&Lg();;){var ge=Atomics.load(l(),S+0>>2);if(ge==1){var ye=Atomics.load(l(),S+4>>2);return F&&(o()[F>>2]=ye),Atomics.store(l(),S+64>>2,1),T?postMessage({cmd:"cleanupThread",thread:S}):sc(S),0}if(!G)return cs.EBUSY;_g(),T||xc(),ic(S+0,ge,T?100:1)}}function Wg(S,F){return Bg(S,F,!0)}function cc(S){if(T)return fs(6,1,S);switch(S){case 30:return 16384;case 85:var F=2147483648;return F/16384;case 132:case 133:case 12:case 137:case 138:case 15:case 235:case 16:case 17:case 18:case 19:case 20:case 149:case 13:case 10:case 236:case 153:case 9:case 21:case 22:case 159:case 154:case 14:case 77:case 78:case 139:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:return 200809;case 27:case 246:case 127:case 128:case 23:case 24:case 160:case 161:case 181:case 182:case 242:case 183:case 184:case 243:case 244:case 245:case 165:case 178:case 179:case 49:case 50:case 168:case 169:case 175:case 170:case 171:case 172:case 97:case 76:case 32:case 173:case 35:case 80:case 81:case 79:return-1;case 176:case 177:case 7:case 155:case 8:case 157:case 125:case 126:case 92:case 93:case 129:case 130:case 131:case 94:case 91:return 1;case 74:case 60:case 69:case 70:case 4:return 1024;case 31:case 42:case 72:return 32;case 87:case 26:case 33:return 2147483647;case 34:case 1:return 47839;case 38:case 36:return 99;case 43:case 37:return 2048;case 0:return 2097152;case 3:return 65536;case 28:return 32768;case 44:return 32767;case 75:return 16384;case 39:return 1e3;case 89:return 700;case 71:return 256;case 40:return 255;case 2:return 100;case 180:return 64;case 25:return 20;case 5:return 16;case 6:return 6;case 73:return 4;case 84:return typeof navigator=="object"&&navigator.hardwareConcurrency||1}return ig(28),-1}T||Fe.initMainThreadBlock();var ms,Vg=[null,og,lc,uc,dc,pc,cc],Ug={e:ng,r:sg,x:lg,b:ug,y:dg,j:pg,d:ic,c:Ud,f:eo,p:hg,A:cg,u:mg,q:Ag,v:Sg,i:Tg,s:Cg,w:Pg,l:uc,n:dc,g:pc,o:J0,a:ie||u.wasmMemory,z:Og,k:zg,h:Dg,m:Wg,t:cc},T5=Y0(),fc=u.___wasm_call_ctors=function(){return(fc=u.___wasm_call_ctors=u.asm.B).apply(null,arguments)},Gg=u._init=function(){return(Gg=u._init=u.asm.C).apply(null,arguments)},jg=u._init_with_threads_count=function(){return(jg=u._init_with_threads_count=u.asm.D).apply(null,arguments)},Hg=u._get_threads_count=function(){return(Hg=u._get_threads_count=u.asm.E).apply(null,arguments)},qg=u._register_tensor=function(){return(qg=u._register_tensor=u.asm.F).apply(null,arguments)},Kg=u._dispose_data=function(){return(Kg=u._dispose_data=u.asm.G).apply(null,arguments)},Xg=u._dispose=function(){return(Xg=u._dispose=u.asm.H).apply(null,arguments)},Zg=u._Abs=function(){return(Zg=u._Abs=u.asm.I).apply(null,arguments)},Yg=u._Add=function(){return(Yg=u._Add=u.asm.J).apply(null,arguments)},Jg=u._AddN=function(){return(Jg=u._AddN=u.asm.K).apply(null,arguments)},Qg=u._All=function(){return(Qg=u._All=u.asm.L).apply(null,arguments)},e1=u._Any=function(){return(e1=u._Any=u.asm.M).apply(null,arguments)},t1=u._ArgMax=function(){return(t1=u._ArgMax=u.asm.N).apply(null,arguments)},r1=u._AvgPool=function(){return(r1=u._AvgPool=u.asm.O).apply(null,arguments)},a1=u._BatchMatMul=function(){return(a1=u._BatchMatMul=u.asm.P).apply(null,arguments)},n1=u._Ceil=function(){return(n1=u._Ceil=u.asm.Q).apply(null,arguments)},s1=u._ClipByValue=function(){return(s1=u._ClipByValue=u.asm.R).apply(null,arguments)},i1=u._Conv2D=function(){return(i1=u._Conv2D=u.asm.S).apply(null,arguments)},o1=u._Conv2DBackpropInput=function(){return(o1=u._Conv2DBackpropInput=u.asm.T).apply(null,arguments)},l1=u._Cos=function(){return(l1=u._Cos=u.asm.U).apply(null,arguments)},u1=u._Cosh=function(){return(u1=u._Cosh=u.asm.V).apply(null,arguments)},mc=u._CropAndResize=function(){return(mc=u._CropAndResize=u.asm.W).apply(null,arguments)},gc=u._Cumsum=function(){return(gc=u._Cumsum=u.asm.X).apply(null,arguments)},qd=u._DepthToSpace=function(){return(qd=u._DepthToSpace=u.asm.Y).apply(null,arguments)},Wl=u._DepthwiseConv2dNative=function(){return(Wl=u._DepthwiseConv2dNative=u.asm.Z).apply(null,arguments)},d1=u._Elu=function(){return(d1=u._Elu=u.asm._).apply(null,arguments)},Kd=u._Equal=function(){return(Kd=u._Equal=u.asm.$).apply(null,arguments)},Vl=u._Exp=function(){return(Vl=u._Exp=u.asm.aa).apply(null,arguments)},Ul=u._FlipLeftRight=function(){return(Ul=u._FlipLeftRight=u.asm.ba).apply(null,arguments)},p1=u._Floor=function(){return(p1=u._Floor=u.asm.ca).apply(null,arguments)},te=u._FloorDiv=function(){return(te=u._FloorDiv=u.asm.da).apply(null,arguments)},le=u._FusedBatchNorm=function(){return(le=u._FusedBatchNorm=u.asm.ea).apply(null,arguments)},Me=u._FusedConv2D=function(){return(Me=u._FusedConv2D=u.asm.fa).apply(null,arguments)},ot=u._FusedDepthwiseConv2D=function(){return(ot=u._FusedDepthwiseConv2D=u.asm.ga).apply(null,arguments)},Lt=u._Gather=function(){return(Lt=u._Gather=u.asm.ha).apply(null,arguments)},Rt=u._GatherNd=function(){return(Rt=u._GatherNd=u.asm.ia).apply(null,arguments)},Qe=u._Greater=function(){return(Qe=u._Greater=u.asm.ja).apply(null,arguments)},tt=u._GreaterEqual=function(){return(tt=u._GreaterEqual=u.asm.ka).apply(null,arguments)},yr=u._LeakyRelu=function(){return(yr=u._LeakyRelu=u.asm.la).apply(null,arguments)},_n=u._Less=function(){return(_n=u._Less=u.asm.ma).apply(null,arguments)},Ln=u._LessEqual=function(){return(Ln=u._LessEqual=u.asm.na).apply(null,arguments)},yc=u._Log=function(){return(yc=u._Log=u.asm.oa).apply(null,arguments)},Xd=u._LogicalAnd=function(){return(Xd=u._LogicalAnd=u.asm.pa).apply(null,arguments)},wa=u._Max=function(){return(wa=u._Max=u.asm.qa).apply(null,arguments)},gs=u._MaxPool=function(){return(gs=u._MaxPool=u.asm.ra).apply(null,arguments)},Ac=u._Maximum=function(){return(Ac=u._Maximum=u.asm.sa).apply(null,arguments)},a9=u._Mean=function(){return(a9=u._Mean=u.asm.ta).apply(null,arguments)},n9=u._Min=function(){return(n9=u._Min=u.asm.ua).apply(null,arguments)},s9=u._Minimum=function(){return(s9=u._Minimum=u.asm.va).apply(null,arguments)},i9=u._MirrorPad=function(){return(i9=u._MirrorPad=u.asm.wa).apply(null,arguments)},o9=u._Multiply=function(){return(o9=u._Multiply=u.asm.xa).apply(null,arguments)},l9=u._Neg=function(){return(l9=u._Neg=u.asm.ya).apply(null,arguments)},u9=u._NonMaxSuppressionV3=function(){return(u9=u._NonMaxSuppressionV3=u.asm.za).apply(null,arguments)},d9=u._NonMaxSuppressionV4=function(){return(d9=u._NonMaxSuppressionV4=u.asm.Aa).apply(null,arguments)},p9=u._NonMaxSuppressionV5=function(){return(p9=u._NonMaxSuppressionV5=u.asm.Ba).apply(null,arguments)},h9=u._NotEqual=function(){return(h9=u._NotEqual=u.asm.Ca).apply(null,arguments)},c9=u._OneHot=function(){return(c9=u._OneHot=u.asm.Da).apply(null,arguments)},f9=u._PadV2=function(){return(f9=u._PadV2=u.asm.Ea).apply(null,arguments)},m9=u._Pow=function(){return(m9=u._Pow=u.asm.Fa).apply(null,arguments)},g9=u._Prelu=function(){return(g9=u._Prelu=u.asm.Ga).apply(null,arguments)},y9=u._Prod=function(){return(y9=u._Prod=u.asm.Ha).apply(null,arguments)},A9=u._RealDiv=function(){return(A9=u._RealDiv=u.asm.Ia).apply(null,arguments)},x9=u._Relu=function(){return(x9=u._Relu=u.asm.Ja).apply(null,arguments)},b9=u._Relu6=function(){return(b9=u._Relu6=u.asm.Ka).apply(null,arguments)},v9=u._ResizeBilinear=function(){return(v9=u._ResizeBilinear=u.asm.La).apply(null,arguments)},w9=u._Reverse=function(){return(w9=u._Reverse=u.asm.Ma).apply(null,arguments)},k9=u._RotateWithOffset=function(){return(k9=u._RotateWithOffset=u.asm.Na).apply(null,arguments)},I9=u._Round=function(){return(I9=u._Round=u.asm.Oa).apply(null,arguments)},S9=u._Rsqrt=function(){return(S9=u._Rsqrt=u.asm.Pa).apply(null,arguments)},T9=u._ScatterNd=function(){return(T9=u._ScatterNd=u.asm.Qa).apply(null,arguments)},C9=u._SelectV2=function(){return(C9=u._SelectV2=u.asm.Ra).apply(null,arguments)},N9=u._Sigmoid=function(){return(N9=u._Sigmoid=u.asm.Sa).apply(null,arguments)},E9=u._Sin=function(){return(E9=u._Sin=u.asm.Ta).apply(null,arguments)},R9=u._Softmax=function(){return(R9=u._Softmax=u.asm.Ua).apply(null,arguments)},F9=u._SparseFillEmptyRows=function(){return(F9=u._SparseFillEmptyRows=u.asm.Va).apply(null,arguments)},M9=u._SparseReshape=function(){return(M9=u._SparseReshape=u.asm.Wa).apply(null,arguments)},$9=u._SparseSegmentReduction=function(){return($9=u._SparseSegmentReduction=u.asm.Xa).apply(null,arguments)},P9=u._Sqrt=function(){return(P9=u._Sqrt=u.asm.Ya).apply(null,arguments)},O9=u._Square=function(){return(O9=u._Square=u.asm.Za).apply(null,arguments)},z9=u._SquaredDifference=function(){return(z9=u._SquaredDifference=u.asm._a).apply(null,arguments)},D9=u._Step=function(){return(D9=u._Step=u.asm.$a).apply(null,arguments)},_9=u._StridedSlice=function(){return(_9=u._StridedSlice=u.asm.ab).apply(null,arguments)},L9=u._Sub=function(){return(L9=u._Sub=u.asm.bb).apply(null,arguments)},B9=u._Sum=function(){return(B9=u._Sum=u.asm.cb).apply(null,arguments)},W9=u._Tan=function(){return(W9=u._Tan=u.asm.db).apply(null,arguments)},V9=u._Tanh=function(){return(V9=u._Tanh=u.asm.eb).apply(null,arguments)},U9=u._Tile=function(){return(U9=u._Tile=u.asm.fb).apply(null,arguments)},G9=u._TopK=function(){return(G9=u._TopK=u.asm.gb).apply(null,arguments)},j9=u._Transform=function(){return(j9=u._Transform=u.asm.hb).apply(null,arguments)},H9=u._Transpose=function(){return(H9=u._Transpose=u.asm.ib).apply(null,arguments)},q9=u.__FusedMatMul=function(){return(q9=u.__FusedMatMul=u.asm.jb).apply(null,arguments)},to=u._malloc=function(){return(to=u._malloc=u.asm.kb).apply(null,arguments)},Zd=u._free=function(){return(Zd=u._free=u.asm.lb).apply(null,arguments)},C5=u.___errno_location=function(){return(C5=u.___errno_location=u.asm.mb).apply(null,arguments)},N5=u._emscripten_get_global_libc=function(){return(N5=u._emscripten_get_global_libc=u.asm.ob).apply(null,arguments)},ys=u._pthread_self=function(){return(ys=u._pthread_self=u.asm.pb).apply(null,arguments)},E5=u.___pthread_tsd_run_dtors=function(){return(E5=u.___pthread_tsd_run_dtors=u.asm.qb).apply(null,arguments)},xc=u._emscripten_main_thread_process_queued_calls=function(){return(xc=u._emscripten_main_thread_process_queued_calls=u.asm.rb).apply(null,arguments)},K9=u._emscripten_current_thread_process_queued_calls=function(){return(K9=u._emscripten_current_thread_process_queued_calls=u.asm.sb).apply(null,arguments)},R5=u._emscripten_register_main_browser_thread_id=function(){return(R5=u._emscripten_register_main_browser_thread_id=u.asm.tb).apply(null,arguments)},F5=u._emscripten_main_browser_thread_id=function(){return(F5=u._emscripten_main_browser_thread_id=u.asm.ub).apply(null,arguments)},M5=u.__emscripten_do_dispatch_to_thread=function(){return(M5=u.__emscripten_do_dispatch_to_thread=u.asm.vb).apply(null,arguments)},$5=u._emscripten_sync_run_in_main_thread_4=function(){return($5=u._emscripten_sync_run_in_main_thread_4=u.asm.wb).apply(null,arguments)},P5=u._emscripten_run_in_main_runtime_thread_js=function(){return(P5=u._emscripten_run_in_main_runtime_thread_js=u.asm.xb).apply(null,arguments)},h1=u.__emscripten_call_on_thread=function(){return(h1=u.__emscripten_call_on_thread=u.asm.yb).apply(null,arguments)},X9=u._emscripten_tls_init=function(){return(X9=u._emscripten_tls_init=u.asm.zb).apply(null,arguments)},c1=u.__emscripten_thread_init=function(){return(c1=u.__emscripten_thread_init=u.asm.Ab).apply(null,arguments)},Yd=u.stackSave=function(){return(Yd=u.stackSave=u.asm.Bb).apply(null,arguments)},Gl=u.stackRestore=function(){return(Gl=u.stackRestore=u.asm.Cb).apply(null,arguments)},jl=u.stackAlloc=function(){return(jl=u.stackAlloc=u.asm.Db).apply(null,arguments)},O5=u._emscripten_stack_set_limits=function(){return(O5=u._emscripten_stack_set_limits=u.asm.Eb).apply(null,arguments)},z5=u._memalign=function(){return(z5=u._memalign=u.asm.Fb).apply(null,arguments)},D5=u.__emscripten_allow_main_runtime_queued_calls=10208,Hl=u.__emscripten_main_thread_futex=10412;u.cwrap=qe,u.PThread=Fe,u.PThread=Fe,u.wasmMemory=ie,u.ExitStatus=Jd;var bc;function Jd(S){this.name="ExitStatus",this.message="Program terminated with exit("+S+")",this.status=S}Ji=function S(){bc||f1(),bc||(Ji=S)};function f1(S){if(S=S||g,_a>0)return;if(T){p(u),Jh(),postMessage({cmd:"loaded"});return}if(Yh(),_a>0)return;function F(){bc||(bc=!0,u.calledRun=!0,!be&&(Jh(),Qh(),p(u),u.onRuntimeInitialized&&u.onRuntimeInitialized(),ec()))}u.setStatus?(u.setStatus("Running..."),setTimeout(function(){setTimeout(function(){u.setStatus("")},1),F()},1)):F()}u.run=f1;function Z9(S,F){if(!(F&&ae&&S===0)){if(!F&&T)throw postMessage({cmd:"exitProcess",returnCode:S}),new Jd(S);ae||(Fe.terminateAllThreads(),Te=S,Yr(),u.onExit&&u.onExit(S),be=!0),A(S,new Jd(S))}}if(u.preInit)for(typeof u.preInit=="function"&&(u.preInit=[u.preInit]);u.preInit.length>0;)u.preInit.pop()();T&&(ae=!1,Fe.initWorker()),f1();var vc;c&&(vc={uncaughtException:process.listeners("uncaughtException").filter(function(S){return!c.uncaughtException.indexOf(S)>-1}),unhandledRejection:process.listeners("unhandledRejection").filter(function(S){return!c.unhandledRejection.indexOf(S)>-1})});var wc;if(typeof WasmBackendModule!="undefined")wc=WasmBackendModule;else if(typeof n!="undefined")wc=n;else throw new Error("Could not find wasm module in post.js");if(vc){var Y9=wc._dispose;wc._dispose=function(){Y9(),vc.uncaughtException.forEach(function(S){process.removeListener("uncaughtException",S)}),vc.unhandledRejection.forEach(function(S){process.removeListener("unhandledRejection",S)})}}return n.ready}}();typeof e=="object"&&typeof t=="object"?t.exports=r:typeof define=="function"&&define.amd?define([],function(){return r}):typeof e=="object"&&(e.WasmBackendModuleThreadedSimd=r)}}),TE=sr({"src/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm.js"(e,t){var r=function(){var a=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(a=a||__filename),function(n){n=n||{};var s=typeof n!="undefined"?n:{},i,o;s.ready=new Promise(function(te,le){i=te,o=le});var l;typeof process!="undefined"&&process.listeners&&(l={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var d={},u;for(u in s)s.hasOwnProperty(u)&&(d[u]=s[u]);var p=[],h="./this.program",c=function(te,le){throw le},f=!1,m=!1,g=!1,y=!1;f=typeof window=="object",m=typeof importScripts=="function",g=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",y=!f&&!g&&!m;var A="";function x(te){return s.locateFile?s.locateFile(te,A):A+te}var b,v,C,T,E,R;g?(m?A=yp().dirname(A)+"/":A=__dirname+"/",b=function(te,le){return E||(E=Hc()),R||(R=yp()),te=R.normalize(te),E.readFileSync(te,le?null:"utf8")},C=function(te){var le=b(te,!0);return le.buffer||(le=new Uint8Array(le)),_(le.buffer),le},process.argv.length>1&&(h=process.argv[1].replace(/\\/g,"/")),p=process.argv.slice(2),process.on("uncaughtException",function(te){if(!(te instanceof d1))throw te}),process.on("unhandledRejection",zn),c=function(te){process.exit(te)},s.inspect=function(){return"[Emscripten Module object]"}):y?(typeof read!="undefined"&&(b=function(te){return read(te)}),C=function(te){var le;return typeof readbuffer=="function"?new Uint8Array(readbuffer(te)):(le=read(te,"binary"),_(typeof le=="object"),le)},typeof scriptArgs!="undefined"?p=scriptArgs:typeof arguments!="undefined"&&(p=arguments),typeof quit=="function"&&(c=function(te){quit(te)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(f||m)&&(m?A=self.location.href:typeof document!="undefined"&&document.currentScript&&(A=document.currentScript.src),a&&(A=a),A.indexOf("blob:")!==0?A=A.substr(0,A.lastIndexOf("/")+1):A="",b=function(te){var le=new XMLHttpRequest;return le.open("GET",te,!1),le.send(null),le.responseText},m&&(C=function(te){var le=new XMLHttpRequest;return le.open("GET",te,!1),le.responseType="arraybuffer",le.send(null),new Uint8Array(le.response)}),v=function(te,le,Me){var ot=new XMLHttpRequest;ot.open("GET",te,!0),ot.responseType="arraybuffer",ot.onload=function(){if(ot.status==200||ot.status==0&&ot.response){le(ot.response);return}Me()},ot.onerror=Me,ot.send(null)},T=function(te){document.title=te});var z=s.print||console.log.bind(console),M=s.printErr||console.warn.bind(console);for(u in d)d.hasOwnProperty(u)&&(s[u]=d[u]);d=null,s.arguments&&(p=s.arguments),s.thisProgram&&(h=s.thisProgram),s.quit&&(c=s.quit);var I;s.wasmBinary&&(I=s.wasmBinary);var D=s.noExitRuntime||!0;typeof WebAssembly!="object"&&zn("no native wasm support detected");var O,j=!1,X;function _(te,le){te||zn("Assertion failed: "+le)}function K(te){var le=s["_"+te];return _(le,"Cannot call unknown function "+te+", make sure it is exported"),le}function W(te,le,Me,ot,Lt){var Rt={string:function(wa){var gs=0;if(wa!=null&&wa!==0){var Ac=(wa.length<<2)+1;gs=qd(Ac),ie(wa,gs,Ac)}return gs},array:function(wa){var gs=qd(wa.length);return xe(wa,gs),gs}};function Qe(wa){return le==="string"?Z(wa):le==="boolean"?Boolean(wa):wa}var tt=K(te),yr=[],_n=0;if(ot)for(var Ln=0;Ln<ot.length;Ln++){var yc=Rt[Me[Ln]];yc?(_n===0&&(_n=mc()),yr[Ln]=yc(ot[Ln])):yr[Ln]=ot[Ln]}var Xd=tt.apply(null,yr);return Xd=Qe(Xd),_n!==0&&gc(_n),Xd}function ee(te,le,Me,ot){Me=Me||[];var Lt=Me.every(function(Qe){return Qe==="number"}),Rt=le!=="string";return Rt&&Lt&&!ot?K(te):function(){return W(te,le,Me,arguments,ot)}}var Q=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function ne(te,le,Me){for(var ot=le+Me,Lt=le;te[Lt]&&!(Lt>=ot);)++Lt;if(Lt-le>16&&te.subarray&&Q)return Q.decode(te.subarray(le,Lt));for(var Rt="";le<Lt;){var Qe=te[le++];if(!(Qe&128)){Rt+=String.fromCharCode(Qe);continue}var tt=te[le++]&63;if((Qe&224)==192){Rt+=String.fromCharCode((Qe&31)<<6|tt);continue}var yr=te[le++]&63;if((Qe&240)==224?Qe=(Qe&15)<<12|tt<<6|yr:Qe=(Qe&7)<<18|tt<<12|yr<<6|te[le++]&63,Qe<65536)Rt+=String.fromCharCode(Qe);else{var _n=Qe-65536;Rt+=String.fromCharCode(55296|_n>>10,56320|_n&1023)}}return Rt}function Z(te,le){return te?ne($e,te,le):""}function ae(te,le,Me,ot){if(!(ot>0))return 0;for(var Lt=Me,Rt=Me+ot-1,Qe=0;Qe<te.length;++Qe){var tt=te.charCodeAt(Qe);if(tt>=55296&&tt<=57343){var yr=te.charCodeAt(++Qe);tt=65536+((tt&1023)<<10)|yr&1023}if(tt<=127){if(Me>=Rt)break;le[Me++]=tt}else if(tt<=2047){if(Me+1>=Rt)break;le[Me++]=192|tt>>6,le[Me++]=128|tt&63}else if(tt<=65535){if(Me+2>=Rt)break;le[Me++]=224|tt>>12,le[Me++]=128|tt>>6&63,le[Me++]=128|tt&63}else{if(Me+3>=Rt)break;le[Me++]=240|tt>>18,le[Me++]=128|tt>>12&63,le[Me++]=128|tt>>6&63,le[Me++]=128|tt&63}}return le[Me]=0,Me-Lt}function ie(te,le,Me){return ae(te,$e,le,Me)}function xe(te,le){Re.set(te,le)}function be(te,le){return te%le>0&&(te+=le-te%le),te}var Te,Re,$e,_e,qe,Ze,st,ht,ct;function yt(te){Te=te,s.HEAP8=Re=new Int8Array(te),s.HEAP16=_e=new Int16Array(te),s.HEAP32=Ze=new Int32Array(te),s.HEAPU8=$e=new Uint8Array(te),s.HEAPU16=qe=new Uint16Array(te),s.HEAPU32=st=new Uint32Array(te),s.HEAPF32=ht=new Float32Array(te),s.HEAPF64=ct=new Float64Array(te)}var Et=s.INITIAL_MEMORY||16777216,Hr,ut=[],qr=[],gr=[],Kr=[],za=!1;qr.push({func:function(){ac()}});function Xr(){if(s.preRun)for(typeof s.preRun=="function"&&(s.preRun=[s.preRun]);s.preRun.length;)ia(s.preRun.shift());_a(ut)}function Rr(){za=!0,_a(qr)}function Da(){_a(gr)}function xn(){if(s.postRun)for(typeof s.postRun=="function"&&(s.postRun=[s.postRun]);s.postRun.length;)_l(s.postRun.shift());_a(Kr)}function ia(te){ut.unshift(te)}function _l(te){Kr.unshift(te)}var Zr=0,hs=null,va=null;function Bd(te){Zr++,s.monitorRunDependencies&&s.monitorRunDependencies(Zr)}function Wd(te){if(Zr--,s.monitorRunDependencies&&s.monitorRunDependencies(Zr),Zr==0&&(hs!==null&&(clearInterval(hs),hs=null),va)){var le=va;va=null,le()}}s.preloadedImages={},s.preloadedAudios={};function zn(te){s.onAbort&&s.onAbort(te),te+="",M(te),j=!0,X=1,te="abort("+te+"). Build with -s ASSERTIONS=1 for more info.";var le=new WebAssembly.RuntimeError(te);throw o(le),le}function Zh(te,le){return String.prototype.startsWith?te.startsWith(le):te.indexOf(le)===0}var U0="data:application/octet-stream;base64,";function Yh(te){return Zh(te,U0)}var Jh="file://";function Qh(te){return Zh(te,Jh)}var Yr="tfjs-backend-wasm.wasm";Yh(Yr)||(Yr=x(Yr));function ec(te){try{if(te==Yr&&I)return new Uint8Array(I);if(C)return C(te);throw"both async and sync fetching of the wasm failed"}catch(le){zn(le)}}function G0(){if(!I&&(f||m)){if(typeof fetch=="function"&&!Qh(Yr))return fetch(Yr,{credentials:"same-origin"}).then(function(te){if(!te.ok)throw"failed to load wasm binary file at '"+Yr+"'";return te.arrayBuffer()}).catch(function(){return ec(Yr)});if(v)return new Promise(function(te,le){v(Yr,function(Me){te(new Uint8Array(Me))},le)})}return Promise.resolve().then(function(){return ec(Yr)})}function j0(){var te={a:Jr};function le(Qe,tt){var yr=Qe.exports;s.asm=yr,O=s.asm.h,yt(O.buffer),Hr=s.asm.Va,Wd("wasm-instantiate")}Bd("wasm-instantiate");function Me(Qe){le(Qe.instance)}function ot(Qe){return G0().then(function(tt){return WebAssembly.instantiate(tt,te)}).then(Qe,function(tt){M("failed to asynchronously prepare wasm: "+tt),zn(tt)})}function Lt(){return!I&&typeof WebAssembly.instantiateStreaming=="function"&&!Yh(Yr)&&!Qh(Yr)&&typeof fetch=="function"?fetch(Yr,{credentials:"same-origin"}).then(function(Qe){var tt=WebAssembly.instantiateStreaming(Qe,te);return tt.then(Me,function(yr){return M("wasm streaming compile failed: "+yr),M("falling back to ArrayBuffer instantiation"),ot(Me)})}):ot(Me)}if(s.instantiateWasm)try{var Rt=s.instantiateWasm(te,le);return Rt}catch(Qe){return M("Module.instantiateWasm callback failed with error: "+Qe),!1}return Lt().catch(o),{}}function _a(te){for(;te.length>0;){var le=te.shift();if(typeof le=="function"){le(s);continue}var Me=le.func;typeof Me=="number"?le.arg===void 0?Hr.get(Me)():Hr.get(Me)(le.arg):Me(le.arg===void 0?null:le.arg)}}function Vd(){zn()}function Ji(te,le,Me){$e.copyWithin(te,le,le+Me)}function H0(){return $e.length}function q0(te){try{return O.grow(te-Te.byteLength+65535>>>16),yt(O.buffer),1}catch(le){}}function Dn(te){var le=H0(),Me=2147483648;if(te>Me)return!1;for(var ot=1;ot<=4;ot*=2){var Lt=le*(1+.2/ot);Lt=Math.min(Lt,te+100663296);var Rt=Math.min(Me,be(Math.max(te,Lt),65536)),Qe=q0(Rt);if(Qe)return!0}return!1}var Qi={mappings:{},buffers:[null,[],[]],printChar:function(te,le){var Me=Qi.buffers[te];le===0||le===10?((te===1?z:M)(ne(Me,0)),Me.length=0):Me.push(le)},varargs:void 0,get:function(){Qi.varargs+=4;var te=Ze[Qi.varargs-4>>2];return te},getStr:function(te){var le=Z(te);return le},get64:function(te,le){return te}};function K0(te){return 0}function tc(te,le,Me,ot,Lt){}function X0(te,le,Me,ot){for(var Lt=0,Rt=0;Rt<Me;Rt++){for(var Qe=Ze[le+Rt*8>>2],tt=Ze[le+(Rt*8+4)>>2],yr=0;yr<tt;yr++)Qi.printChar(te,$e[Qe+yr]);Lt+=tt}return Ze[ot>>2]=Lt,0}function rc(){return 28}var Jr={a:Vd,d:Ji,e:Dn,f:K0,c:tc,b:X0,g:rc},Z0=j0(),ac=s.___wasm_call_ctors=function(){return(ac=s.___wasm_call_ctors=s.asm.i).apply(null,arguments)},Y0=s._init=function(){return(Y0=s._init=s.asm.j).apply(null,arguments)},nc=s._init_with_threads_count=function(){return(nc=s._init_with_threads_count=s.asm.k).apply(null,arguments)},J0=s._get_threads_count=function(){return(J0=s._get_threads_count=s.asm.l).apply(null,arguments)},Ll=s._register_tensor=function(){return(Ll=s._register_tensor=s.asm.m).apply(null,arguments)},cs=s._dispose_data=function(){return(cs=s._dispose_data=s.asm.n).apply(null,arguments)},Ud=s._dispose=function(){return(Ud=s._dispose=s.asm.o).apply(null,arguments)},Q0=s._Abs=function(){return(Q0=s._Abs=s.asm.p).apply(null,arguments)},eg=s._Add=function(){return(eg=s._Add=s.asm.q).apply(null,arguments)},sc=s._AddN=function(){return(sc=s._AddN=s.asm.r).apply(null,arguments)},Fe=s._All=function(){return(Fe=s._All=s.asm.s).apply(null,arguments)},tg=s._Any=function(){return(tg=s._Any=s.asm.t).apply(null,arguments)},rg=s._ArgMax=function(){return(rg=s._ArgMax=s.asm.u).apply(null,arguments)},ag=s._AvgPool=function(){return(ag=s._AvgPool=s.asm.v).apply(null,arguments)},ng=s._BatchMatMul=function(){return(ng=s._BatchMatMul=s.asm.w).apply(null,arguments)},sg=s._Ceil=function(){return(sg=s._Ceil=s.asm.x).apply(null,arguments)},eo=s._ClipByValue=function(){return(eo=s._ClipByValue=s.asm.y).apply(null,arguments)},ig=s._Conv2D=function(){return(ig=s._Conv2D=s.asm.z).apply(null,arguments)},og=s._Conv2DBackpropInput=function(){return(og=s._Conv2DBackpropInput=s.asm.A).apply(null,arguments)},lg=s._Cos=function(){return(lg=s._Cos=s.asm.B).apply(null,arguments)},ug=s._Cosh=function(){return(ug=s._Cosh=s.asm.C).apply(null,arguments)},dg=s._CropAndResize=function(){return(dg=s._CropAndResize=s.asm.D).apply(null,arguments)},pg=s._Cumsum=function(){return(pg=s._Cumsum=s.asm.E).apply(null,arguments)},ic=s._DepthToSpace=function(){return(ic=s._DepthToSpace=s.asm.F).apply(null,arguments)},hg=s._DepthwiseConv2dNative=function(){return(hg=s._DepthwiseConv2dNative=s.asm.G).apply(null,arguments)},cg=s._Elu=function(){return(cg=s._Elu=s.asm.H).apply(null,arguments)},fs=s._Equal=function(){return(fs=s._Equal=s.asm.I).apply(null,arguments)},Gd=s._Exp=function(){return(Gd=s._Exp=s.asm.J).apply(null,arguments)},jd=s._FlipLeftRight=function(){return(jd=s._FlipLeftRight=s.asm.K).apply(null,arguments)},fg=s._Floor=function(){return(fg=s._Floor=s.asm.L).apply(null,arguments)},mg=s._FloorDiv=function(){return(mg=s._FloorDiv=s.asm.M).apply(null,arguments)},gg=s._FusedBatchNorm=function(){return(gg=s._FusedBatchNorm=s.asm.N).apply(null,arguments)},yg=s._FusedConv2D=function(){return(yg=s._FusedConv2D=s.asm.O).apply(null,arguments)},Ag=s._FusedDepthwiseConv2D=function(){return(Ag=s._FusedDepthwiseConv2D=s.asm.P).apply(null,arguments)},je=s._Gather=function(){return(je=s._Gather=s.asm.Q).apply(null,arguments)},xg=s._GatherNd=function(){return(xg=s._GatherNd=s.asm.R).apply(null,arguments)},bg=s._Greater=function(){return(bg=s._Greater=s.asm.S).apply(null,arguments)},vg=s._GreaterEqual=function(){return(vg=s._GreaterEqual=s.asm.T).apply(null,arguments)},wg=s._LeakyRelu=function(){return(wg=s._LeakyRelu=s.asm.U).apply(null,arguments)},kg=s._Less=function(){return(kg=s._Less=s.asm.V).apply(null,arguments)},Ig=s._LessEqual=function(){return(Ig=s._LessEqual=s.asm.W).apply(null,arguments)},Hd=s._Log=function(){return(Hd=s._Log=s.asm.X).apply(null,arguments)},oc=s._LogicalAnd=function(){return(oc=s._LogicalAnd=s.asm.Y).apply(null,arguments)},lc=s._Max=function(){return(lc=s._Max=s.asm.Z).apply(null,arguments)},Sg=s._MaxPool=function(){return(Sg=s._MaxPool=s.asm._).apply(null,arguments)},Tg=s._Maximum=function(){return(Tg=s._Maximum=s.asm.$).apply(null,arguments)},Cg=s._Mean=function(){return(Cg=s._Mean=s.asm.aa).apply(null,arguments)},Ng=s._Min=function(){return(Ng=s._Min=s.asm.ba).apply(null,arguments)},Eg=s._Minimum=function(){return(Eg=s._Minimum=s.asm.ca).apply(null,arguments)},Rg=s._MirrorPad=function(){return(Rg=s._MirrorPad=s.asm.da).apply(null,arguments)},Fg=s._Multiply=function(){return(Fg=s._Multiply=s.asm.ea).apply(null,arguments)},dt=s._Neg=function(){return(dt=s._Neg=s.asm.fa).apply(null,arguments)},Mg=s._NonMaxSuppressionV3=function(){return(Mg=s._NonMaxSuppressionV3=s.asm.ga).apply(null,arguments)},$g=s._NonMaxSuppressionV4=function(){return($g=s._NonMaxSuppressionV4=s.asm.ha).apply(null,arguments)},Pg=s._NonMaxSuppressionV5=function(){return(Pg=s._NonMaxSuppressionV5=s.asm.ia).apply(null,arguments)},Bl=s._NotEqual=function(){return(Bl=s._NotEqual=s.asm.ja).apply(null,arguments)},uc=s._OneHot=function(){return(uc=s._OneHot=s.asm.ka).apply(null,arguments)},dc=s._PadV2=function(){return(dc=s._PadV2=s.asm.la).apply(null,arguments)},pc=s._Pow=function(){return(pc=s._Pow=s.asm.ma).apply(null,arguments)},Og=s._Prelu=function(){return(Og=s._Prelu=s.asm.na).apply(null,arguments)},zg=s._Prod=function(){return(zg=s._Prod=s.asm.oa).apply(null,arguments)},hc=s._RealDiv=function(){return(hc=s._RealDiv=s.asm.pa).apply(null,arguments)},Dg=s._Relu=function(){return(Dg=s._Relu=s.asm.qa).apply(null,arguments)},_g=s._Relu6=function(){return(_g=s._Relu6=s.asm.ra).apply(null,arguments)},Lg=s._ResizeBilinear=function(){return(Lg=s._ResizeBilinear=s.asm.sa).apply(null,arguments)},Bg=s._Reverse=function(){return(Bg=s._Reverse=s.asm.ta).apply(null,arguments)},Wg=s._RotateWithOffset=function(){return(Wg=s._RotateWithOffset=s.asm.ua).apply(null,arguments)},cc=s._Round=function(){return(cc=s._Round=s.asm.va).apply(null,arguments)},ms=s._Rsqrt=function(){return(ms=s._Rsqrt=s.asm.wa).apply(null,arguments)},Vg=s._ScatterNd=function(){return(Vg=s._ScatterNd=s.asm.xa).apply(null,arguments)},Ug=s._SelectV2=function(){return(Ug=s._SelectV2=s.asm.ya).apply(null,arguments)},T5=s._Sigmoid=function(){return(T5=s._Sigmoid=s.asm.za).apply(null,arguments)},fc=s._Sin=function(){return(fc=s._Sin=s.asm.Aa).apply(null,arguments)},Gg=s._Softmax=function(){return(Gg=s._Softmax=s.asm.Ba).apply(null,arguments)},jg=s._SparseFillEmptyRows=function(){return(jg=s._SparseFillEmptyRows=s.asm.Ca).apply(null,arguments)},Hg=s._SparseReshape=function(){return(Hg=s._SparseReshape=s.asm.Da).apply(null,arguments)},qg=s._SparseSegmentReduction=function(){return(qg=s._SparseSegmentReduction=s.asm.Ea).apply(null,arguments)},Kg=s._Sqrt=function(){return(Kg=s._Sqrt=s.asm.Fa).apply(null,arguments)},Xg=s._Square=function(){return(Xg=s._Square=s.asm.Ga).apply(null,arguments)},Zg=s._SquaredDifference=function(){return(Zg=s._SquaredDifference=s.asm.Ha).apply(null,arguments)},Yg=s._Step=function(){return(Yg=s._Step=s.asm.Ia).apply(null,arguments)},Jg=s._StridedSlice=function(){return(Jg=s._StridedSlice=s.asm.Ja).apply(null,arguments)},Qg=s._Sub=function(){return(Qg=s._Sub=s.asm.Ka).apply(null,arguments)},e1=s._Sum=function(){return(e1=s._Sum=s.asm.La).apply(null,arguments)},t1=s._Tan=function(){return(t1=s._Tan=s.asm.Ma).apply(null,arguments)},r1=s._Tanh=function(){return(r1=s._Tanh=s.asm.Na).apply(null,arguments)},a1=s._Tile=function(){return(a1=s._Tile=s.asm.Oa).apply(null,arguments)},n1=s._TopK=function(){return(n1=s._TopK=s.asm.Pa).apply(null,arguments)},s1=s._Transform=function(){return(s1=s._Transform=s.asm.Qa).apply(null,arguments)},i1=s._Transpose=function(){return(i1=s._Transpose=s.asm.Ra).apply(null,arguments)},o1=s.__FusedMatMul=function(){return(o1=s.__FusedMatMul=s.asm.Sa).apply(null,arguments)},l1=s._malloc=function(){return(l1=s._malloc=s.asm.Ta).apply(null,arguments)},u1=s._free=function(){return(u1=s._free=s.asm.Ua).apply(null,arguments)},mc=s.stackSave=function(){return(mc=s.stackSave=s.asm.Wa).apply(null,arguments)},gc=s.stackRestore=function(){return(gc=s.stackRestore=s.asm.Xa).apply(null,arguments)},qd=s.stackAlloc=function(){return(qd=s.stackAlloc=s.asm.Ya).apply(null,arguments)};s.cwrap=ee;var Wl;function d1(te){this.name="ExitStatus",this.message="Program terminated with exit("+te+")",this.status=te}va=function te(){Wl||Kd(),Wl||(va=te)};function Kd(te){if(te=te||p,Zr>0||(Xr(),Zr>0))return;function le(){Wl||(Wl=!0,s.calledRun=!0,!j&&(Rr(),Da(),i(s),s.onRuntimeInitialized&&s.onRuntimeInitialized(),xn()))}s.setStatus?(s.setStatus("Running..."),setTimeout(function(){setTimeout(function(){s.setStatus("")},1),le()},1)):le()}if(s.run=Kd,s.preInit)for(typeof s.preInit=="function"&&(s.preInit=[s.preInit]);s.preInit.length>0;)s.preInit.pop()();Kd();var Vl;l&&(Vl={uncaughtException:process.listeners("uncaughtException").filter(function(te){return!l.uncaughtException.indexOf(te)>-1}),unhandledRejection:process.listeners("unhandledRejection").filter(function(te){return!l.unhandledRejection.indexOf(te)>-1})});var Ul;if(typeof n!="undefined")Ul=n;else if(typeof WasmBackendModuleThreadedSimd!="undefined")Ul=WasmBackendModuleThreadedSimd;else throw new Error("Could not find wasm module in post.js");if(Vl){var p1=Ul._dispose;Ul._dispose=function(){p1(),Vl.uncaughtException.forEach(function(te){process.removeListener("uncaughtException",te)}),Vl.unhandledRejection.forEach(function(te){process.removeListener("unhandledRejection",te)})}}return n.ready}}();typeof e=="object"&&typeof t=="object"?t.exports=r:typeof define=="function"&&define.amd?define([],function(){return r}):typeof e=="object"&&(e.WasmBackendModule=r)}}),CE=1e-7,NE=1e-4,Dp=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}},Iu=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,r){return ka("write")}move(e,t,r,a,n){return ka("move")}memory(){return ka("memory")}floatPrecision(){return ka("floatPrecision")}epsilon(){return this.floatPrecision()===32?CE:NE}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 kv(e){let t=e.length,r=0;for(;t>0;)r=Math.random()*t|0,t--,qc(e,t,r)}function EE(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 r=e.length,a=0;for(;r>0;)a=Math.random()*r|0,r--,qc(e,r,a),qc(t,r,a)}function kp(e,t,r){return Math.max(e,Math.min(t,r))}function RE(e){return e%2===0?e:e+1}function qc(e,t,r){let a=e[t];e[t]=e[r],e[r]=a}function FE(e){let t=0;for(let r=0;r<e.length;r++)t+=e[r];return t}function ME(e,t){let r=Math.random();return t*r+(1-r)*e}function $E(e,t){let r=0;for(let a=0;a<e.length;a++){let n=Number(e[a])-Number(t[a]);r+=n*n}return r}function P(e,t){if(!e)throw new Error(typeof t=="string"?t:t())}function _r(e,t,r=""){P(Gs(e,t),()=>r+` Shapes ${e} and ${t} must match`)}function Ro(e){P(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function Ao(e,t=[],r=!1){if(t==null&&(t=[]),Array.isArray(e)||wr(e)&&!r)for(let a=0;a<e.length;++a)Ao(e[a],t,r);else t.push(e);return t}function Tt(e){if(e.length===0)return 1;let t=e[0];for(let r=1;r<e.length;r++)t*=e[r];return t}function PE(e){return e.length===0}function Gs(e,t){if(e===t)return!0;if(e==null||t==null||e.length!==t.length)return!1;for(let r=0;r<e.length;r++)if(e[r]!==t[r])return!1;return!0}function du(e){return e%1===0}function OE(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 zE(e){let t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function DE(e){let t=new Uint32Array(e);for(let r=0;r<e;++r)t[r]=r;return kv(t),t}function Ap(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function _E(e,t=a=>0,r){return new Promise((a,n)=>{let s=0,i=()=>{if(e()){a();return}s++;let o=t(s);if(r!=null&&s>=r){n();return}setTimeout(i,o)};i()})}function LE(e,t){let r=1,a=-1;for(let s=0;s<e.length;++s)if(e[s]>=0)r*=e[s];else if(e[s]===-1){if(a!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${a} and dim ${s}`);a=s}else if(e[s]<0)throw Error(`Shapes can not be < 0. Found ${e[s]} at dim ${s}`);if(a===-1){if(t>0&&t!==r)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(r===0)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%r!==0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${r}`);let n=e.slice();return n[a]=t/r,n}function Ua(e,t){let r=t.length;return e=e==null?t.map((a,n)=>n):[].concat(e),P(e.every(a=>a>=-r&&a<r),()=>`All values in axis param must be in range [-${r}, ${r}) but got axis ${e}`),P(e.every(a=>du(a)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(a=>a<0?r+a:a)}function Iv(e,t){let r=[],a=[],n=t!=null&&Array.isArray(t)&&t.length===0,s=t==null||n?null:Ua(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&&(r.push(e[o]),a.push(o)),s[i]<=o&&i++}e[o]!==1&&(r.push(e[o]),a.push(o))}return{newShape:r,keptDims:a}}function Sv(e,t){let r=null;if(e==null||e==="float32")r=new Float32Array(t);else if(e==="int32")r=new Int32Array(t);else if(e==="bool")r=new Uint8Array(t);else throw new Error(`Unknown data type ${e}`);return r}function Tv(e,t){let r=null;if(e==null||e==="float32")r=new Float32Array(t);else if(e==="int32")r=new Int32Array(t);else if(e==="bool")r=new Uint8Array(t);else if(e==="string")r=new Array(t);else throw new Error(`Unknown data type ${e}`);return r}function Cv(e,t){for(let r=0;r<e.length;r++){let a=e[r];if(isNaN(a)||!isFinite(a))throw Error(`A tensor of type ${t} being uploaded contains ${a}.`)}}function Nv(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function BE(e,t){return!(t==="complex64"||t==="float32"&&e!=="complex64"||t==="int32"&&e!=="float32"&&e!=="complex64"||t==="bool"&&e==="bool")}function wr(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}function F1(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 Ev(e){if(e==null)return 0;let t=0;return e.forEach(r=>t+=r.length),t}function Is(e){return typeof e=="string"||e instanceof String}function Rv(e){return typeof e=="boolean"}function Fv(e){return typeof e=="number"}function If(e){return Array.isArray(e)?If(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":Fv(e)?"float32":Is(e)?"string":Rv(e)?"bool":"float32"}function Es(e){return!!(e&&e.constructor&&e.call&&e.apply)}function Kc(e,t){for(let r=t;r<e;++r)if(e%r===0)return r;return e}function Su(e){let t=e.length;if(t<2)return[];let r=new Array(t-1);r[t-2]=e[t-1];for(let a=t-3;a>=0;--a)r[a]=r[a+1]*e[a+1];return r}function Mv(e,t,r,a=!1){let n=new Array;if(t.length===1){let s=t[0]*(a?2:1);for(let i=0;i<s;i++)n[i]=r[e+i]}else{let s=t[0],i=t.slice(1),o=i.reduce((l,d)=>l*d)*(a?2:1);for(let l=0;l<s;l++)n[l]=Mv(e+l*o,i,r,a)}return n}function su(e,t,r=!1){if(e.length===0)return t[0];let a=e.reduce((n,s)=>n*s)*(r?2:1);if(a===0)return[];if(a!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${r?" for a complex tensor":""}.`);return Mv(0,e,t,r)}function My(e,t){let r=Sf(e,t);for(let a=0;a<r.length;a++)r[a]=1;return r}function Sf(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 WE(e,t){let r=e.reduce((a,n)=>a*n,1);if(t==null||t==="float32")return su(e,new Float32Array(r));if(t==="int32")return su(e,new Int32Array(r));if(t==="bool")return su(e,new Uint8Array(r));throw new Error(`Unknown data type ${t}`)}function $y(e){e.forEach(t=>{P(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function VE(e,t,r){if(t===0)return 0;if(t===1)return e[0];let a=e[e.length-1];for(let n=0;n<e.length-1;++n)a+=r[n]*e[n];return a}function UE(e,t,r){if(t===0)return[];if(t===1)return[e];let a=new Array(t);for(let n=0;n<a.length-1;++n)a[n]=Math.floor(e/r[n]),e-=a[n]*r[n];return a[a.length-1]=e,a}function Py(e){return e&&e.then&&typeof e.then=="function"}var W5="tfjsflags",$v=class{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=GE,this.populateURLFlags()}setPlatform(e,t){this.platform!=null&&(Y().getBool("IS_TEST")||Y().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,r){if(this.flagRegistry[e]={evaluationFn:t,setHook:r},this.urlFlags[e]!=null){let a=this.urlFlags[e];Y().getBool("IS_TEST")||Y().getBool("PROD")||console.warn(`Setting feature override from URL ${e}: ${a}.`),this.set(e,a)}}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(Py(t))throw new Error(`Flag ${e} cannot be synchronously evaluated. Please use getAsync() instead.`);return this.flags[e]=t,this.flags[e]}getNumber(e){return this.get(e)}getBool(e){return this.get(e)}getFlags(){return this.flags}get features(){return this.flags}set(e,t){if(this.flagRegistry[e]==null)throw new Error(`Cannot set flag ${e} as it has not been registered.`);this.flags[e]=t,this.flagRegistry[e].setHook!=null&&this.flagRegistry[e].setHook(t)}evaluateFlag(e){if(this.flagRegistry[e]==null)throw new Error(`Cannot evaluate flag '${e}': no evaluation function found.`);return this.flagRegistry[e].evaluationFn()}setFlags(e){this.flags=Object.assign({},e)}reset(){this.flags={},this.urlFlags={},this.populateURLFlags()}populateURLFlags(){if(typeof this.global=="undefined"||typeof this.global.location=="undefined"||typeof this.global.location.search=="undefined")return;let e=this.getQueryParams(this.global.location.search);W5 in e&&e[W5].split(",").forEach(t=>{let[r,a]=t.split(":");this.urlFlags[r]=HE(r,a)})}};function GE(e){let t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(r,...a)=>(jE(t,a[0],a[1]),a.join("="))),t}function jE(e,t,r){e[decodeURIComponent(t)]=decodeURIComponent(r||"")}function HE(e,t){if(t=t.toLowerCase(),t==="true"||t==="false")return t==="true";if(`${+t}`===t)return+t;throw new Error(`Could not parse value flag value ${t} for flag ${e}.`)}function Y(){return hn}var hn=null;function qE(e){hn=e}var g1;function Pv(){if(g1==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");g1=e}return g1}function KE(){let e=Pv();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function Oy(e,t){let r=KE();if(r.has(e))return r.get(e);{let a=t();return r.set(e,a),r.get(e)}}var Fo="Abs",Tu="Acos",Cu="Acosh",qn="Add",js="AddN",Nu="All",Eu="Any",Hs="ArgMax",Ru="ArgMin",Fu="Asin",Mu="Asinh",$u="Atan",Pu="Atanh",Ou="Atan2",qs="AvgPool",Tf="AvgPoolGrad",_p="AvgPool3D",Cf="AvgPool3DGrad",Ks="BatchMatMul",Mo="BatchToSpaceND",Nf="Bincount",Ov="BroadcastTo",Ef="BroadcastArgs",Xs="Cast",Zs="Ceil",Kn="ClipByValue",Lp="Complex",Bp="ComplexAbs",$o="Concat",Ys="Conv2D",Rf="Conv2DBackpropFilter",Js="Conv2DBackpropInput",Wp="Conv3D",Ff="Conv3DBackpropFilterV2",Mf="Conv3DBackpropInputV2",Qs="Cos",ei="Cosh",Po="Cumsum",Oo="CropAndResize",$f="DenseBincount",zo="DepthToSpace",ti="DepthwiseConv2dNative",Pf="DepthwiseConv2dNativeBackpropFilter",Of="DepthwiseConv2dNativeBackpropInput",zf="Diag",Vp="Dilation2D",Xc="Dilation2DBackpropInput",Zc="Dilation2DBackpropFilter",ri="RealDiv",Up="Einsum",ai="Elu",Df="EluGrad",zu="Erf",Do="Equal",ni="Exp",_o="ExpandDims",Lo="Expm1",_f="FFT",Du="Fill",Bo="FlipLeftRight",si="Floor",ii="FloorDiv",oi="FusedBatchNorm",Wo="GatherV2",Vo="GatherNd",Uo="Greater",li="GreaterEqual",ui="Identity",Lf="IFFT",Gp="Imag",_u="IsFinite",Lu="IsInf",Bu="IsNan",di="LeakyRelu",Go="Less",jo="LessEqual",Bf="LinSpace",pi="Log",Wu="Log1p",Ho="LogicalAnd",Vu="LogicalNot",jp="LogicalOr",zv="LogSoftmax",Hp="LRN",Wf="LRNGrad",hi="Max",ci="Maximum",fi="MaxPool",Vf="MaxPoolGrad",qp="MaxPool3D",Uf="MaxPool3DGrad",Gf="MaxPoolWithArgmax",mi="Mean",gi="Min",yi="Minimum",Ai="MirrorPad",Uu="Mod",jf="Multinomial",xi="Multiply",qo="Neg",Ko="NotEqual",Xo="NonMaxSuppressionV3",Gu="NonMaxSuppressionV4",Zo="NonMaxSuppressionV5",Yo="OnesLike",Jo="OneHot",Qo="Pack",bi="PadV2",XE="Pool",vi="Pow",wi="Prelu",el="Prod",ju="Range",Kp="Real",Hu="Reciprocal",ki="Relu",tl="Reshape",qu="ResizeNearestNeighbor",Hf="ResizeNearestNeighborGrad",Ii="ResizeBilinear",qf="ResizeBilinearGrad",Si="Relu6",rl="Reverse",al="Round",Ti="Rsqrt",nl="ScatterNd",sl="Select",Ku="Selu",il="Slice",Ci="Sin",ol="Sinh",Xu="Sign",Ni="Sigmoid",Zu="Softplus",Ei="Sqrt",Ri="Sum",ll="SpaceToBatchND",ul="SplitV",Fi="Softmax",Xp="SparseFillEmptyRows",Yu="SparseReshape",Zp="SparseSegmentMean",Yp="SparseSegmentSum",Jp="SparseToDense",Mi="SquaredDifference",Ju="Square",dl="StridedSlice",Qp="StringNGrams",Kf="StringSplit",Xf="StringToHashBucketFast",$i="Sub",pl="Tan",Pi="Tanh",Xn="Tile",hl="TopK",cl="Transform",Oi="Transpose",Zf="Unique",fl="Unpack",eh="UnsortedSegmentSum",ml="ZerosLike",zi="Step",Ip="FromPixels",gl="RotateWithOffset",Rs="_FusedMatMul",Fs="FusedConv2D",Ms="FusedDepthwiseConv2D";function ks(...e){Y().getBool("IS_TEST")||Y().getBool("PROD")||console.warn(...e)}function ZE(...e){Y().getBool("IS_TEST")||Y().getBool("PROD")||console.log(...e)}var pu=Oy("kernelRegistry",()=>new Map),Sp=Oy("gradRegistry",()=>new Map);function Yc(e,t){let r=zy(e,t);return pu.get(r)}function M1(e){return Sp.get(e)}function Tn(e){let t=pu.entries(),r=[];for(;;){let{done:a,value:n}=t.next();if(a)break;let[s,i]=n,[o]=s.split("_");o===e&&r.push(i)}return r}function Ga(e){let{kernelName:t,backendName:r}=e,a=zy(t,r);pu.has(a)&&ks(`The kernel '${t}' for backend '${r}' is already registered`),pu.set(a,e)}function Dv(e){let{kernelName:t}=e;Sp.has(t)&&Y().getBool("DEBUG")&&ks(`Overriding the gradient for '${t}'`),Sp.set(t,e)}function YE(e,t){let r=zy(e,t);if(!pu.has(r))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);pu.delete(r)}function JE(e){if(!Sp.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);Sp.delete(e)}function QE(e,t){Tn(e).forEach(r=>{let a=Object.assign({},r,{backendName:t});Ga(a)})}function zy(e,t){return`${t}_${e}`}var w={};De(w,{arraysEqual:()=>Gs,assert:()=>P,assertNonNegativeIntegerDimensions:()=>$y,assertNonNull:()=>Ro,assertShapesMatch:()=>_r,bytesFromStringArray:()=>Ev,bytesPerElement:()=>F1,checkConversionForErrors:()=>Cv,clamp:()=>kp,computeStrides:()=>Su,createScalarValue:()=>sR,createShuffledIndices:()=>DE,decodeString:()=>Jc,distSquared:()=>$E,encodeString:()=>rh,fetch:()=>oR,fingerPrint64:()=>nR,flatten:()=>Ao,getArrayFromDType:()=>Tv,getTypedArrayFromDType:()=>Sv,hasEncodingLoss:()=>BE,hexToLong:()=>th,indexToLoc:()=>UE,inferDtype:()=>If,inferFromImplicitShape:()=>LE,isBoolean:()=>Rv,isFunction:()=>Es,isInt:()=>du,isNumber:()=>Fv,isPromise:()=>Py,isScalarShape:()=>PE,isString:()=>Is,isTypedArray:()=>wr,isValidDtype:()=>Nv,locToIndex:()=>VE,makeOnesTypedArray:()=>My,makeZerosNestedTypedArray:()=>WE,makeZerosTypedArray:()=>Sf,nearestDivisor:()=>Kc,nearestLargerEven:()=>RE,now:()=>Tp,parseAxisParam:()=>Ua,randUniform:()=>ME,repeatedTry:()=>_E,rightPad:()=>Ap,shuffle:()=>kv,shuffleCombo:()=>EE,sizeFromShape:()=>Tt,sizeToSquarishShape:()=>zE,squeezeShape:()=>Iv,sum:()=>FE,swap:()=>qc,tanh:()=>OE,toNestedArray:()=>su,toTypedArray:()=>Yf});var V5=Eo(pE()),io=V5.default||V5;function th(e){return io.fromString(e,!0,16)}var _v=th("c3a5c85c97cb3127"),no=th("b492b66fbe98f273"),Fr=th("9ae16a3b2f90404f");function $1(e){return e.xor(e.shru(47))}function Lv(e,t,r){let a=e.slice(t,t+r);return io.fromBytes(Array.from(a),!0,!0)}function wt(e,t){return Lv(e,t,8)}function U5(e,t){return Lv(e,t,4)}function ur(e,t){return t===0?e:e.shru(t).or(e.shl(64-t))}function Ts(e,t,r=th("9ddfea08eb382d69")){let a=e.xor(t).mul(r);a=a.xor(a.shru(47));let n=t.xor(a).mul(r);return n=n.xor(n.shru(47)),n=n.mul(r),n}function eR(e,t,r,a,n,s){n=n.add(e),s=ur(s.add(n).add(a),21);let i=n;return n=n.add(t),n=n.add(r),s=s.add(ur(n,44)),[n.add(a),s.add(i)]}function Ic(e,t,r,a){return eR(wt(e,t),wt(e,t+8),wt(e,t+16),wt(e,t+24),r,a)}function tR(e,t=e.length){if(t>=8){let r=Fr.add(t*2),a=wt(e,0).add(Fr),n=wt(e,t-8),s=ur(n,37).mul(r).add(a),i=ur(a,25).add(n).mul(r);return Ts(s,i,r)}if(t>=4){let r=Fr.add(t*2),a=U5(e,0);return Ts(a.shl(3).add(t),U5(e,t-4),r)}if(t>0){let r=e[0],a=e[t>>1],n=e[t-1],s=r+(a<<8),i=t+(n<<2);return $1(Fr.mul(s).xor(_v.mul(i))).mul(Fr)}return Fr}function rR(e,t=e.length){let r=Fr.add(t*2),a=wt(e,0).mul(no),n=wt(e,8),s=wt(e,t-8).mul(r),i=wt(e,t-16).mul(Fr);return Ts(ur(a.add(n),43).add(ur(s,30)).add(i),a.add(ur(n.add(Fr),18)).add(s),r)}function aR(e,t=e.length){let r=Fr.add(t*2),a=wt(e,0).mul(Fr),n=wt(e,8),s=wt(e,t-8).mul(r),i=wt(e,t-16).mul(Fr),o=ur(a.add(n),43).add(ur(s,30)).add(i),l=Ts(o,a.add(ur(n.add(Fr),18)).add(s),r),d=wt(e,16).mul(r),u=wt(e,24),p=o.add(wt(e,t-32)).mul(r),h=l.add(wt(e,t-24)).mul(r);return Ts(ur(d.add(u),43).add(ur(p,30)).add(h),d.add(ur(u.add(a),18)).add(p),r)}function nR(e,t=e.length){let r=io.fromNumber(81,!0);if(t<=32)return t<=16?tR(e,t):rR(e,t);if(t<=64)return aR(e,t);let a=r,n=r.mul(no).add(113),s=$1(n.mul(Fr).add(113)).mul(Fr),i=[io.UZERO,io.UZERO],o=[io.UZERO,io.UZERO];a=a.mul(Fr).add(wt(e,0));let l=0,d=(t-1>>6)*64,u=d+(t-1&63)-63;do a=ur(a.add(n).add(i[0]).add(wt(e,l+8)),37).mul(no),n=ur(n.add(i[1]).add(wt(e,l+48)),42).mul(no),a=a.xor(o[1]),n=n.add(i[0]).add(wt(e,l+40)),s=ur(s.add(o[0]),33).mul(no),i=Ic(e,l,i[1].mul(no),a.add(o[0])),o=Ic(e,l+32,s.add(o[1]),n.add(wt(e,l+16))),[s,a]=[a,s],l+=64;while(l!==d);let p=no.add(s.and(255).shl(1));return l=u,o[0]=o[0].add(t-1&63),i[0]=i[0].add(o[0]),o[0]=o[0].add(i[0]),a=ur(a.add(n).add(i[0]).add(wt(e,l+8)),37).mul(p),n=ur(n.add(i[1]).add(wt(e,l+48)),42).mul(p),a=a.xor(o[1].mul(9)),n=n.add(i[0].mul(9).add(wt(e,l+40))),s=ur(s.add(o[0]),33).mul(p),i=Ic(e,l,i[1].mul(p),a.add(o[0])),o=Ic(e,l+32,s.add(o[1]),n.add(wt(e,l+16))),[s,a]=[a,s],Ts(Ts(i[0],o[0],p).add($1(n).mul(_v)).add(s),Ts(i[1],o[1],p).add(a),p)}function sR(e,t){return t==="string"?rh(e):Yf([e],t)}function iR(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function Yf(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=Ao(e)),Y().getBool("DEBUG")&&Cv(e,t),iR(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 r=new Uint8Array(e.length);for(let a=0;a<r.length;++a)Math.round(e[a])!==0&&(r[a]=1);return r}else throw new Error(`Unknown data type ${t}`)}function Tp(){return Y().platform.now()}function oR(e,t){return Y().platform.fetch(e,t)}function rh(e,t="utf-8"){return t=t||"utf-8",Y().platform.encode(e,t)}function Jc(e,t="utf-8"){return t=t||"utf-8",Y().platform.decode(e,t)}var lR=class{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new dR)}profileKernel(e,t,r){let a,n=()=>{a=r()},s,i=Tp();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(n);else{n();for(let o of a)o.dataSync();s=Promise.resolve({kernelMs:Tp()-i})}if(Y().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let o=0;o<a.length;o++){let l=a[o];l.data().then(d=>{uR(d,l.dtype,e)})}return{kernelName:e,outputs:a,inputs:t,timeMs:s.then(o=>o.kernelMs),extraInfo:s.then(o=>o.getExtraProfileInfo!=null?o.getExtraProfileInfo():"")}}logKernelProfile(e){let{kernelName:t,outputs:r,timeMs:a,inputs:n,extraInfo:s}=e;r.forEach(i=>{Promise.all([i.data(),a,s]).then(o=>{this.logger.logKernelProfile(t,i,o[0],o[1],n,o[2])})})}};function uR(e,t,r){if(t!=="float32")return!1;for(let a=0;a<e.length;a++){let n=e[a];if(isNaN(n)||!isFinite(n))return console.warn(`Found ${n} in the result of '${r}'`),!0}return!1}var dR=class{logKernelProfile(e,t,r,a,n,s){let i=typeof a=="number"?Ap(`${a}ms`,9):a.error,o=Ap(e,25),l=t.rank,d=t.size,u=Ap(t.shape.toString(),14),p="";for(let h in n){let c=n[h];if(c!=null){let f=c.shape||t.shape,m=f.length;p+=`${h}: ${m}D ${m>0?f:""} `}}console.log(`%c${o} %c${i} %c${l}D ${u} %c${d} %c${p} %c${s}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function pR(e,t,r){let a={},n={};for(let l=0;l<t.length;l++)a[t[l].id]=!0;for(let l=0;l<e.length;l++){let d=e[l],u=d.inputs;for(let p in u){let h=u[p],c=!1;for(let f=0;f<t.length;f++)if(a[h.id]){d.outputs.forEach(m=>a[m.id]=!0),c=!0,n[d.id]=!0;break}if(c)break}}let s={};s[r.id]=!0;let i={};for(let l=e.length-1;l>=0;l--){let d=e[l],u=d.inputs;for(let p=0;p<d.outputs.length;p++)if(s[d.outputs[p].id]){for(let h in u)s[u[h].id]=!0,i[d.id]=!0;break}}let o=[];for(let l=0;l<e.length;l++){let d=e[l];if(n[d.id]&&i[d.id]){let u={};for(let h in d.inputs){let c=d.inputs[h];a[c.id]&&(u[h]=c)}let p=Object.assign({},d);p.inputs=u,p.outputs=d.outputs,o.push(p)}}return o}function hR(e,t,r,a){for(let n=t.length-1;n>=0;n--){let s=t[n],i=[];if(s.outputs.forEach(l=>{let d=e[l.id];d!=null?i.push(d):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 d=r(()=>o[l]());if(d.dtype!=="float32")throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${d.dtype}'`);let u=s.inputs[l];if(!Gs(d.shape,u.shape))throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${l}' has shape '${d.shape}', which does not match the shape of the input '${u.shape}'`);if(e[u.id]==null)e[u.id]=d;else{let p=e[u.id];e[u.id]=a(p,d),p.dispose()}}}}var G5=20,ap=3,y1=7;function cR(e,t,r,a){let n=Su(t),s=fR(e,t,r,n),i=t.length,o=Oc(e,t,r,n,s),l=["Tensor"];return a&&(l.push(` dtype: ${r}`),l.push(` rank: ${i}`),l.push(` shape: [${t}]`),l.push(" values:")),l.push(o.map(d=>" "+d).join(`
|
|
`)),l.join(`
|
|
`)}function fR(e,t,r,a){let n=Tt(t),s=a[a.length-1],i=new Array(s).fill(0),o=t.length,l=r==="complex64"?lp(e):e;if(o>1)for(let d=0;d<n/s;d++){let u=d*s;for(let p=0;p<s;p++)i[p]=Math.max(i[p],op(l[u+p],0,r).length)}return i}function op(e,t,r){let a;return Array.isArray(e)?a=`${parseFloat(e[0].toFixed(y1))} + ${parseFloat(e[1].toFixed(y1))}j`:Is(e)?a=`'${e}'`:r==="bool"?a=Bv(e):a=parseFloat(e.toFixed(y1)).toString(),Ap(a,t)}function Bv(e){return e===0?"false":"true"}function Oc(e,t,r,a,n,s=!0){let i=r==="complex64"?2:1,o=t[0],l=t.length;if(l===0){if(r==="complex64"){let m=lp(e);return[op(m[0],0,r)]}return r==="bool"?[Bv(e[0])]:[e[0].toString()]}if(l===1){if(o>G5){let g=ap*i,y=Array.from(e.slice(0,g)),A=Array.from(e.slice((o-ap)*i,o*i));return r==="complex64"&&(y=lp(y),A=lp(A)),["["+y.map((x,b)=>op(x,n[b],r)).join(", ")+", ..., "+A.map((x,b)=>op(x,n[o-ap+b],r)).join(", ")+"]"]}let m=r==="complex64"?lp(e):Array.from(e);return["["+m.map((g,y)=>op(g,n[y],r)).join(", ")+"]"]}let d=t.slice(1),u=a.slice(1),p=a[0]*i,h=[];if(o>G5){for(let m=0;m<ap;m++){let g=m*p,y=g+p;h.push(...Oc(e.slice(g,y),d,r,u,n,!1))}h.push("...");for(let m=o-ap;m<o;m++){let g=m*p,y=g+p;h.push(...Oc(e.slice(g,y),d,r,u,n,m===o-1))}}else for(let m=0;m<o;m++){let g=m*p,y=g+p;h.push(...Oc(e.slice(g,y),d,r,u,n,m===o-1))}let c=l===2?",":"";h[0]="["+h[0]+c;for(let m=1;m<h.length-1;m++)h[m]=" "+h[m]+c;let f=`,
|
|
`;for(let m=2;m<l;m++)f+=`
|
|
`;return h[h.length-1]=" "+h[h.length-1]+"]"+(s?"":f),h}function lp(e){let t=[];for(let r=0;r<e.length;r+=2)t.push([e[r],e[r+1]]);return t}var tr=class{constructor(e,t,r){if(this.dtype=t,this.shape=e.slice(),this.size=Tt(e),r!=null){let a=r.length;P(a===this.size,()=>`Length of values '${a}' 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=r||Tv(t,this.size),this.strides=Su(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 r=this.locToIndex(t);this.values[r]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let a of e){if(a<0||a>=this.shape[t]){let n=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(n)}t++}let r=e[e.length-1];for(let a=0;a<e.length-1;++a)r+=this.strides[a]*e[a];return this.values[r]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let r=0;r<e.length-1;++r)t+=this.strides[r]*e[r];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];let t=new Array(this.shape.length);for(let r=0;r<t.length-1;++r)t[r]=Math.floor(e/this.strides[r]),e-=t[r]*this.strides[r];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return Ja().makeTensor(this.values,this.shape,this.dtype)}},Ja=null,tu=null,mR=null;function gR(e){Ja=e}function yR(e){tu=e}function AR(e){mR=e}var et=class{constructor(e,t,r,a){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=Tt(e),this.strides=Su(e),this.dataId=r,this.id=a,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){let e=await this.data();return tu.buffer(this.shape,this.dtype,e)}bufferSync(){return tu.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return su(this.shape,e,this.dtype==="complex64")}arraySync(){return su(this.shape,this.dataSync(),this.dtype==="complex64")}async data(){this.throwIfDisposed();let e=Ja().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(r=>Jc(r))}catch(r){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(),Ja().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();let e=Ja().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Jc(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 Ja().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Ja().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return tu.print(this,e)}clone(){return this.throwIfDisposed(),tu.clone(this)}toString(e=!1){let t=this.dataSync();return cR(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),tu.cast(this,e)}variable(e=!0,t,r){return this.throwIfDisposed(),Ja().makeVariable(this,e,t,r)}};Object.defineProperty(et,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function xR(){return Oy("Tensor",()=>et)}xR();var Cp=class extends et{constructor(e,t,r,a){super(e.shape,e.dtype,e.dataId,a);this.trainable=t,this.name=r}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(!Gs(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Ja().disposeTensor(this),this.dataId=e.dataId,Ja().incRef(this,null)}dispose(){Ja().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(Cp,Symbol.hasInstance,{value:e=>e instanceof et&&e.assign!=null&&e.assign instanceof Function});var rn={};De(rn,{assertTypesMatch:()=>Hv,getTensorsInContainer:()=>Dy,isTensorInList:()=>vR,makeTypesMatch:()=>Dt});var Wv=(e=>(e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6",e))(Wv||{}),Vv=(e=>(e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64",e))(Vv||{}),Uv=(e=>(e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64",e))(Uv||{}),Gv=(e=>(e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64",e))(Gv||{}),jv=(e=>(e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64",e))(jv||{}),bR={float32:Gv,int32:Vv,bool:Uv,complex64:jv};function Or(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return bR[e][t]}function ah(e){return Or(e,"int32")}function Dt(e,t){if(e.dtype===t.dtype)return[e,t];let r=Or(e.dtype,t.dtype);return[e.cast(r),t.cast(r)]}function Hv(e,t){P(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function vR(e,t){return t.some(r=>r.id===e.id)}function Dy(e){let t=[];return qv(e,t,new Set),t}function qv(e,t,r){if(e==null)return;if(e instanceof et){t.push(e);return}if(!wR(e))return;let a=e;for(let n in a){let s=a[n];r.has(s)||(r.add(s),qv(s,t,r))}}function wR(e){return Array.isArray(e)||typeof e=="object"}function A1(e){return e.kernelName!=null}var j5=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()}},P1=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new j5}async ready(){if(this.pendingBackendInit!=null)return this.pendingBackendInit.then(()=>{});if(this.backendInstance!=null)return;let e=this.getSortedBackends();for(let t=0;t<e.length;t++){let r=e[t];if(await this.initializeBackend(r).success){await this.setBackend(r);return}}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(this.pendingBackendInit!=null)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(this.backendInstance==null){let{name:e,asyncInit:t}=this.initializeBackendsAndReturnBest();if(t)throw new Error(`The highest priority backend '${e}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);this.setBackend(e)}return this.backendInstance}backendNames(){return Object.keys(this.registryFactory)}findBackend(e){if(!(e in this.registry))if(e in this.registryFactory){let{asyncInit:t}=this.initializeBackend(e);if(t)return null}else return null;return this.registry[e]}findBackendFactory(e){return e in this.registryFactory?this.registryFactory[e].factory:null}registerBackend(e,t,r=1){return e in this.registryFactory?(ks(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:r},!0)}async setBackend(e){if(this.registryFactory[e]==null)throw new Error(`Backend name '${e}' not found in registry`);if(this.backendName=e,this.registry[e]==null){this.backendInstance=null;let{success:t,asyncInit:r}=this.initializeBackend(e);if(!(r?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new lR(this.backendInstance),!0}setupRegisteredKernels(){Tn(this.backendName).forEach(e=>{e.setupFunc!=null&&e.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){Tn(e).forEach(t=>{t.disposeFunc!=null&&t.disposeFunc(this.registry[e])})}initializeBackend(e){let t=this.registryFactory[e];if(t==null)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{let r=t.factory();if(r&&!(r instanceof Iu)&&typeof r.then=="function"){let a=++this.pendingBackendInitId,n=r.then(s=>a<this.pendingBackendInitId?!1:(this.registry[e]=s,this.pendingBackendInit=null,!0)).catch(s=>(a<this.pendingBackendInitId||(this.pendingBackendInit=null,ks(`Initialization of backend ${e} failed`),ks(s.stack||s.message)),!1));return this.pendingBackendInit=n,{success:n,asyncInit:!0}}else return this.registry[e]=r,{success:!0,asyncInit:!1}}catch(r){return ks(`Initialization of backend ${e} failed`),ks(r.stack||r.message),{success:!1,asyncInit:!1}}}removeBackend(e){if(!(e in this.registryFactory))throw new Error(`${e} backend not found in registry`);this.backendName===e&&this.pendingBackendInit!=null&&this.pendingBackendInitId++,e in this.registry&&(this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e]),delete this.registryFactory[e],this.backendName===e&&(this.pendingBackendInit=null,this.backendName=null,this.backendInstance=null)}getSortedBackends(){if(Object.keys(this.registryFactory).length===0)throw new Error("No backend found in registry.");return Object.keys(this.registryFactory).sort((e,t)=>this.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){let e=this.getSortedBackends();for(let t=0;t<e.length;t++){let r=e[t],{success:a,asyncInit:n}=this.initializeBackend(r);if(n||a)return{name:r,asyncInit:n}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){let r=this.state.tensorInfo.get(t),a=r.backend,n=this.readSync(t),s=a.refCount(t);a.disposeData(t,!0),r.backend=e,e.move(t,n,r.shape,r.dtype,s),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let r=null;if(t==null){if(typeof e!="function")throw new Error("Please provide a function to tidy()");t=e}else{if(typeof e!="string"&&!(e instanceof String))throw new Error("When calling with two arguments, the first argument to tidy() must be a string");if(typeof t!="function")throw new Error("When calling with two arguments, the 2nd argument to tidy() must be a function");r=e}let a;return this.scopedRun(()=>this.startScope(r),()=>this.endScope(a),()=>(a=t(),a instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),a))}scopedRun(e,t,r){e();try{let a=r();return t(),a}catch(a){throw t(),a}}nextTensorId(){return P1.nextTensorId++}nextVariableId(){return P1.nextVariableId++}clone(e){let t=B.runKernel(ui,{x:e}),r={x:e},a=s=>({x:()=>{let i="float32",o={x:s},l={dtype:i};return B.runKernel(Xs,o,l)}}),n=[];return this.addTapeNode(this.state.activeScope.name,r,[t],a,n,{}),t}runKernel(e,t,r){if(this.backendName==null&&this.backend,Yc(e,this.backendName)==null)throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:r})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,r){let a=this.backend.numDataIds(),n=0;r.forEach(o=>{n+=o.dtype==="complex64"?3:1});let s=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=a-t-n-s;if(i>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${i} data ids) after running '${e}'`)}runKernelFunc(e){let t,r=[],a=this.isTapeOn(),n=this.state.numBytes,s=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let i;this.backendName==null&&this.backend;let o,l=A1(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(A1(e)){let{kernelName:c,inputs:f,attrs:m}=e;this.backendName==null&&this.backend;let g=Yc(c,this.backendName);P(g!=null,()=>`Cannot find registered kernel '${c}' for backend '${this.backendName}'`),i=()=>{let y=this.backend.numDataIds();o=g.kernelFunc({inputs:f,attrs:m,backend:this.backend});let A=Array.isArray(o)?o:[o];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(c,y,A);let x=A.map(b=>{if(b.rank!=null)return b;let{dataId:v,shape:C,dtype:T}=b;return this.makeTensorFromDataId(v,C,T)});if(a){let b=this.getTensorsForGradient(c,f,x);r=this.saveTensorsForBackwardMode(b)}return x}}else{let{forwardFunc:c}=e,f=m=>{!a||(r=m.map(g=>this.keep(this.clone(g))))};i=()=>{let m=this.backend.numDataIds();o=this.tidy(()=>c(this.backend,f));let g=Array.isArray(o)?o:[o];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,m,g),g}}let{inputs:d,attrs:u}=e,p=A1(e)?null:e.backwardsFunc,h;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=i():(h=this.profiler.profileKernel(l,d,()=>i()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(h),t=h.outputs)}),a&&this.addTapeNode(l,d,t,p,r,u),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-n,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-s,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(d).map(c=>d[c]!=null?d[c].shape:null),outputShapes:t.map(c=>c.shape),kernelTimeMs:h.timeMs,extraInfo:h.extraInfo}),Array.isArray(o)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(t=>this.keep(this.clone(t)))}getTensorsForGradient(e,t,r){let a=M1(e);if(a!=null){let n=a.inputsToSave||[],s=a.outputsToSave||[],i;a.saveAllInputs?(P(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),i=Object.keys(t).map(l=>t[l])):i=n.map(l=>t[l]);let o=r.filter((l,d)=>s[d]);return i.concat(o)}return[]}makeTensor(e,t,r,a){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");r=r||"float32",a=a||this.backend;let n=e;r==="string"&&Is(e[0])&&(n=e.map(o=>rh(o)));let s=a.write(n,t,r),i=new et(t,r,s,this.nextTensorId());if(this.trackTensor(i,a),r==="string"){let o=this.state.tensorInfo.get(s),l=Ev(n);this.state.numBytes+=l-o.bytes,o.bytes=l}return i}makeTensorFromDataId(e,t,r,a){r=r||"float32";let n=new et(t,r,e,this.nextTensorId());return this.trackTensor(n,a),n}makeVariable(e,t=!0,r,a){r=r||this.nextVariableId().toString(),a!=null&&a!==e.dtype&&(e=e.cast(a));let n=new Cp(e,t,r,this.nextTensorId());if(this.state.registeredVariables[n.name]!=null)throw new Error(`Variable with name ${n.name} was already registered`);return this.state.registeredVariables[n.name]=n,this.incRef(n,this.backend),n}trackTensor(e,t){this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++;let r=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(r=e.size*F1(e.dtype)),this.state.numBytes+=r,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:r})),e instanceof Cp||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;let t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,e.dtype==="string"&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),e.dtype!=="complex64"&&e.dtype!=="string"){let r=e.size*F1(e.dtype);this.state.numBytes-=r}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(let e in this.state.registeredVariables){let t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),this.state.registeredVariables[e.name]!=null&&delete this.state.registeredVariables[e.name]}memory(){let e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,e.reasons==null&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;let t=this.state.numBytes,r=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(a=>a.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-r;for(let a of this.state.activeProfile.kernels)a.kernelTimeMs=await a.kernelTimeMs,a.extraInfo=await a.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,r,a,n,s){let i={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:r,saved:n},o=M1(e);o!=null&&(a=o.gradFunc),a!=null&&(i.gradient=l=>(l=l.map((d,u)=>{if(d==null){let p=r[u],h=Sf(p.size,p.dtype);return this.makeTensor(h,p.shape,p.dtype)}return d}),a(l.length>1?l:l[0],n,s))),this.state.activeTape.push(i)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){let t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){let t=Dy(e),r=new Set(t.map(n=>n.id));for(let n=0;n<this.state.activeScope.track.length;n++){let s=this.state.activeScope.track[n];!s.kept&&!r.has(s.id)&&s.dispose()}let a=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach(n=>{!n.kept&&n.scopeId===a.id&&this.track(n)})}gradients(e,t,r,a=!1){if(P(t.length>0,()=>"gradients() received an empty list of xs."),r!=null&&r.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${r.dtype}'`);let n=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));P(n instanceof et,()=>"The result y returned by f() must be a tensor.");let s=pR(this.state.activeTape,t,n);if(!a&&s.length===0&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",()=>{let i={};i[n.id]=r==null?kR(n.shape):r,hR(i,s,l=>this.tidy(l),IR);let o=t.map(l=>i[l.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(l=>{for(let d of l.saved)d.dispose()}),this.state.activeTape=null),{value:n,grads:o}})}customGrad(e){return P(Es(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{P(t.every(i=>i instanceof et),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let r,a={};t.forEach((i,o)=>{a[o]=i});let n=(i,o)=>(r=e(...t,o),P(r.value instanceof et,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),P(Es(r.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),r.value),s=(i,o)=>{let l=r.gradFunc(i,o),d=Array.isArray(l)?l:[l];P(d.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),P(d.every(p=>p instanceof et),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");let u={};return d.forEach((p,h)=>{u[h]=()=>p}),u};return this.runKernelFunc({forwardFunc:n,backwardsFunc:s,inputs:a})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}readToGPU(e,t){return this.state.tensorInfo.get(e).backend.readToGPU(e,t)}async time(e){let t=Tp(),r=await this.backend.time(e);return r.wallMs=Tp()-t,r}track(e){return this.state.activeScope!=null&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new j5;for(let e in this.registry)this.disposeRegisteredKernels(e),this.registry[e].dispose(),delete this.registry[e];this.backendName=null,this.backendInstance=null,this.pendingBackendInit=null}},_y=P1;_y.nextTensorId=0;_y.nextVariableId=0;function kR(e){let t=My(Tt(e),"float32");return B.makeTensor(t,e,"float32")}function Kv(){let e=Pv();if(e._tfengine==null){let t=new $v(e);e._tfengine=new _y(t)}return qE(e._tfengine.ENV),gR(()=>e._tfengine),e._tfengine}var B=Kv();function IR(e,t){let r={a:e,b:t};return B.runKernel(qn,r)}var nh={};De(nh,{isBrowser:()=>Xv,isMobile:()=>CR,mockIsMobile:()=>TR});function SR(){return typeof navigator!="undefined"&&navigator!=null}var O1;function TR(e){O1=e}function CR(e){if(O1!==void 0)return O1;if(e||SR()){if(e||(e=navigator),e.product==="ReactNative")return!0;let t=e.userAgent||e.vendor||(typeof window!="undefined"?window.opera:"");if(!t){let r=e;return r.userAgentData&&r.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 Xv(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var on=Y();on.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.")});on.registerFlag("IS_BROWSER",()=>Xv());on.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");on.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));on.registerFlag("PROD",()=>!1);on.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>on.getBool("DEBUG"));on.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);on.registerFlag("IS_TEST",()=>!1);on.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);on.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);function Cn(e,t){let r=e;if(wr(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];let a=[];for(;Array.isArray(r)||wr(r)&&t!=="string";)a.push(r.length),r=r[0];return Array.isArray(e)&&Y().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&Zv(e,a,[]),a}function Zv(e,t,r){if(r=r||[],!Array.isArray(e)&&!wr(e)){P(t.length===0,()=>`Element arr[${r.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}P(t.length>0,()=>`Element arr[${r.join("][")}] should be a primitive, but is an array of ${e.length} elements`),P(e.length===t[0],()=>`Element arr[${r.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);let a=t.slice(1);for(let n=0;n<e.length;++n)Zv(e[n],a,r.concat(n))}function H5(e,t,r,a){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 '${r}' passed to '${a}' must be ${e} tensor, but got ${t} tensor`)}}function $(e,t,r,a="numeric"){if(e instanceof et)return H5(a,e.dtype,t,r),e;let n=If(e);if(n!=="string"&&["bool","int32","float32"].indexOf(a)>=0&&(n=a),H5(a,n,t,r),e==null||!wr(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 '${r}' must be a Tensor or TensorLike, but got '${o}'`)}let s=Cn(e,n);!wr(e)&&!Array.isArray(e)&&(e=[e]);let i=n!=="string"?Yf(e,n):Ao(e,[],!0);return B.makeTensor(i,s,n)}function Np(e,t,r,a="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${r} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map((n,s)=>$(n,`${t}[${s}]`,r,a))}var Yv="__op";function V(e){let t=Object.keys(e);if(t.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let r=t[0],a=e[r];r.endsWith("_")&&(r=r.substring(0,r.length-1)),r=r+Yv;let n=(...s)=>{B.startScope(r);try{let i=a(...s);return Py(i)&&console.error("Cannot return a Promise inside of tidy."),B.endScope(i),i}catch(i){throw B.endScope(null),i}};return Object.defineProperty(n,"name",{value:r,configurable:!0}),n}function NR(e,t){let r=$(e,"real","complex"),a=$(t,"imag","complex");_r(r.shape,a.shape,`real and imag shapes, ${r.shape} and ${a.shape}, must match in call to tf.complex().`);let n={real:r,imag:a};return B.runKernel(Lp,n)}var $s=V({complex_:NR});function Di(e,t,r,a){if(a==null&&(a=If(e)),a==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!wr(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){$y(t);let n=Tt(t),s=Tt(r);P(n===s,()=>`Based on the provided shape, [${t}], the tensor should have ${n} values but has ${s}`);for(let i=0;i<r.length;++i){let o=r[i],l=i===r.length-1?o!==Tt(t.slice(i)):!0;P(r[i]===t[i]||!l,()=>`Error creating a new Tensor. Inferred shape (${r}) does not match the provided shape (${t}). `)}}return!wr(e)&&!Array.isArray(e)&&(e=[e]),t=t||r,e=a!=="string"?Yf(e,a):Ao(e,[],!0),B.makeTensor(e,t,a)}function pt(e,t,r){let a=Cn(e,r);return Di(e,t,a,r)}var z1={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},Qc=4;async function ER(e,t){let r=[],a=[],n=Array.isArray(e)?e.map(i=>i.name):Object.keys(e);for(let i=0;i<n.length;++i){let o=n[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 d={name:o,shape:l.shape,dtype:l.dtype};if(l.dtype==="string"){let u=new Promise(async p=>{let h=await l.bytes(),c=h.reduce((g,y)=>g+y.length,0)+Qc*h.length,f=new Uint8Array(c),m=0;for(let g=0;g<h.length;g++){let y=h[g],A=new Uint8Array(new Uint32Array([y.length]).buffer);f.set(A,m),m+=Qc,f.set(y,m),m+=y.length}p(f)});a.push(u)}else a.push(l.data());t!=null&&(d.group=t),r.push(d)}let s=await Promise.all(a);return{data:RR(s),specs:r}}function Jv(e,t){let r={},a,n=0;for(let s of t){let i=s.name,o=s.dtype,l=s.shape,d=Tt(l),u;if("quantization"in s){let p=s.quantization;if(p.dtype==="uint8"||p.dtype==="uint16"){if(!("min"in p&&"scale"in p))throw new Error(`Weight ${s.name} with quantization ${p.dtype} doesn't have corresponding metadata min and scale.`)}else if(p.dtype==="float16"){if(o!=="float32")throw new Error(`Weight ${s.name} is quantized with ${p.dtype} which only supports weights of type float32 not ${o}.`)}else throw new Error(`Weight ${s.name} has unknown quantization dtype ${p.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);let h=z1[p.dtype],c=e.slice(n,n+d*h),f=p.dtype==="uint8"?new Uint8Array(c):new Uint16Array(c);if(o==="float32")if(p.dtype==="uint8"||p.dtype==="uint16"){u=new Float32Array(f.length);for(let m=0;m<f.length;m++){let g=f[m];u[m]=g*p.scale+p.min}}else if(p.dtype==="float16")a===void 0&&(a=zR()),u=a(f);else throw new Error(`Unsupported quantization type ${p.dtype} for weight type float32.`);else if(o==="int32"){if(p.dtype!=="uint8"&&p.dtype!=="uint16")throw new Error(`Unsupported quantization type ${p.dtype} for weight type int32.`);u=new Int32Array(f.length);for(let m=0;m<f.length;m++){let g=f[m];u[m]=Math.round(g*p.scale+p.min)}}else throw new Error(`Unsupported dtype in weight '${i}': ${o}`);n+=d*h}else if(o==="string"){let p=Tt(s.shape);u=[];for(let h=0;h<p;h++){let c=new Uint32Array(e.slice(n,n+Qc))[0];n+=Qc;let f=new Uint8Array(e.slice(n,n+c));u.push(f),n+=c}}else{let p=z1[o],h=e.slice(n,n+d*p);if(o==="float32")u=new Float32Array(h);else if(o==="int32")u=new Int32Array(h);else if(o==="bool")u=new Uint8Array(h);else if(o==="complex64"){u=new Float32Array(h);let c=new Float32Array(u.length/2),f=new Float32Array(u.length/2);for(let y=0;y<c.length;y++)c[y]=u[y*2],f[y]=u[y*2+1];let m=pt(c,l,"float32"),g=pt(f,l,"float32");r[i]=$s(m,g),m.dispose(),g.dispose()}else throw new Error(`Unsupported dtype in weight '${i}': ${o}`);n+=d*p}o!=="complex64"&&(r[i]=pt(u,l,o))}return r}function RR(e){if(e===null)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0,r=[];e.forEach(s=>{if(t+=s.byteLength,r.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 a=new Uint8Array(t),n=0;return r.forEach(s=>{a.set(new Uint8Array(s.buffer),n),n+=s.byteLength}),a.buffer}var Ly=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function q5(e){return Ly?Buffer.byteLength(e):new Blob([e]).size}function FR(e){if(Ly)return Buffer.from(e).toString("base64");let t=new Uint8Array(e),r="";for(let a=0,n=t.length;a<n;a++)r+=String.fromCharCode(t[a]);return btoa(r)}function MR(e){if(Ly){let a=Buffer.from(e,"base64");return a.buffer.slice(a.byteOffset,a.byteOffset+a.byteLength)}let t=atob(e),r=new Uint8Array(t.length);for(let a=0;a<t.length;++a)r.set([t.charCodeAt(a)],a);return r.buffer}function By(e){if(e.length===1)return e[0];let t=0;e.forEach(n=>{t+=n.byteLength});let r=new Uint8Array(t),a=0;return e.forEach(n=>{r.set(new Uint8Array(n),a),a+=n.byteLength}),r.buffer}function K5(e){let t="/";for(e=e.trim();e.endsWith(t);)e=e.slice(0,e.length-1);let r=e.split(t);return r[r.length-1]}function Qv(e,t){let r={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};return e.signature!=null&&(r.signature=e.signature),e.userDefinedMetadata!=null&&(r.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(r.modelInitializer=e.modelInitializer),e.trainingConfig!=null&&(r.trainingConfig=e.trainingConfig),r}async function Wy(e,t){let r={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(e.trainingConfig!=null&&(r.trainingConfig=e.trainingConfig),e.weightsManifest!=null){let[a,n]=await t(e.weightsManifest);r.weightSpecs=a,r.weightData=n}return e.signature!=null&&(r.signature=e.signature),e.userDefinedMetadata!=null&&(r.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(r.modelInitializer=e.modelInitializer),r}function sh(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:q5(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:q5(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function $R(){let e=r=>{let a=r<<13,n=0;for(;(a&8388608)===0;)n-=8388608,a<<=1;return a&=-8388609,n+=947912704,a|n},t=new Uint32Array(2048);t[0]=0;for(let r=1;r<1024;r++)t[r]=e(r);for(let r=1024;r<2048;r++)t[r]=939524096+(r-1024<<13);return t}function PR(){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 OR(){let e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function zR(){let e=$R(),t=PR(),r=OR();return a=>{let n=new ArrayBuffer(4*a.length),s=new Uint32Array(n);for(let i=0;i<a.length;i++){let o=a[i],l=e[r[o>>10]+(o&1023)]+t[o>>10];s[i]=l}return new Float32Array(n)}}var Bt=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Bt.instance==null&&(Bt.instance=new Bt),Bt.instance}static registerSaveRouter(e){Bt.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Bt.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Bt.getHandlers(e,"save")}static getLoadHandlers(e,t){return Bt.getHandlers(e,"load",t)}static getHandlers(e,t,r){let a=[];return(t==="load"?Bt.getInstance().loadRouters:Bt.getInstance().saveRouters).forEach(n=>{let s=n(e,r);s!==null&&a.push(s)}),a}},DR=e=>Bt.registerSaveRouter(e),_R=e=>Bt.registerLoadRouter(e),LR=e=>Bt.getSaveHandlers(e),BR=(e,t)=>Bt.getLoadHandlers(e,t),D1="tensorflowjs",_1=1,po="models_store",Ss="model_info_store";function ew(){if(!Y().getBool("IS_BROWSER"))throw new Error("Failed to obtain IndexedDB factory because the current environmentis not a web browser.");let e=typeof window=="undefined"?self:window,t=e.indexedDB||e.mozIndexedDB||e.webkitIndexedDB||e.msIndexedDB||e.shimIndexedDB;if(t==null)throw new Error("The current browser does not appear to support IndexedDB.");return t}function L1(e){let t=e.result;t.createObjectStore(po,{keyPath:"modelPath"}),t.createObjectStore(Ss,{keyPath:"modelPath"})}var xo=class{constructor(e){if(this.indexedDB=ew(),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((r,a)=>{let n=this.indexedDB.open(D1,_1);n.onupgradeneeded=()=>L1(n),n.onsuccess=()=>{let s=n.result;if(t==null){let i=s.transaction(po,"readonly"),o=i.objectStore(po).get(this.modelPath);o.onsuccess=()=>{if(o.result==null)return s.close(),a(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));r(o.result.modelArtifacts)},o.onerror=l=>(s.close(),a(o.error)),i.oncomplete=()=>s.close()}else{let i=sh(t),o=s.transaction(Ss,"readwrite"),l=o.objectStore(Ss),d=l.put({modelPath:this.modelPath,modelArtifactsInfo:i}),u;d.onsuccess=()=>{u=s.transaction(po,"readwrite");let p=u.objectStore(po).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:i});p.onsuccess=()=>r({modelArtifactsInfo:i}),p.onerror=h=>{l=o.objectStore(Ss);let c=l.delete(this.modelPath);c.onsuccess=()=>(s.close(),a(p.error)),c.onerror=f=>(s.close(),a(p.error))}},d.onerror=p=>(s.close(),a(d.error)),o.oncomplete=()=>{u==null?s.close():u.oncomplete=()=>s.close()}}},n.onerror=s=>a(n.error)})}};xo.URL_SCHEME="indexeddb://";var tw=e=>Y().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(xo.URL_SCHEME)?WR(e.slice(xo.URL_SCHEME.length)):null;Bt.registerSaveRouter(tw);Bt.registerLoadRouter(tw);function WR(e){return new xo(e)}function VR(e){return e.startsWith(xo.URL_SCHEME)?e.slice(xo.URL_SCHEME.length):e}var UR=class{constructor(){this.indexedDB=ew()}async listModels(){return new Promise((e,t)=>{let r=this.indexedDB.open(D1,_1);r.onupgradeneeded=()=>L1(r),r.onsuccess=()=>{let a=r.result,n=a.transaction(Ss,"readonly"),s=n.objectStore(Ss).getAll();s.onsuccess=()=>{let i={};for(let o of s.result)i[o.modelPath]=o.modelArtifactsInfo;e(i)},s.onerror=i=>(a.close(),t(s.error)),n.oncomplete=()=>a.close()},r.onerror=a=>t(r.error)})}async removeModel(e){return e=VR(e),new Promise((t,r)=>{let a=this.indexedDB.open(D1,_1);a.onupgradeneeded=()=>L1(a),a.onsuccess=()=>{let n=a.result,s=n.transaction(Ss,"readwrite"),i=s.objectStore(Ss),o=i.get(e),l;o.onsuccess=()=>{if(o.result==null)return n.close(),r(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{let d=i.delete(e),u=()=>{l=n.transaction(po,"readwrite");let p=l.objectStore(po).delete(e);p.onsuccess=()=>t(o.result.modelArtifactsInfo),p.onerror=h=>r(o.error)};d.onsuccess=u,d.onerror=p=>(u(),n.close(),r(o.error))}},o.onerror=d=>(n.close(),r(o.error)),s.oncomplete=()=>{l==null?n.close():l.oncomplete=()=>n.close()}},a.onerror=n=>r(a.error)})}},Un="/",ru="tensorflowjs_models",rw="info",GR="model_topology",jR="weight_specs",HR="weight_data",qR="model_metadata";function aw(e){return{info:[ru,e,rw].join(Un),topology:[ru,e,GR].join(Un),weightSpecs:[ru,e,jR].join(Un),weightData:[ru,e,HR].join(Un),modelMetadata:[ru,e,qR].join(Un)}}function nw(e){for(let t of Object.values(e))window.localStorage.removeItem(t)}function KR(e){let t=e.split(Un);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Un)}function XR(e){return e.startsWith(bo.URL_SCHEME)?e.slice(bo.URL_SCHEME.length):e}var bo=class{constructor(e){if(!Y().getBool("IS_BROWSER")||typeof window=="undefined"||typeof window.localStorage=="undefined")throw new Error("The current environment does not support local storage.");if(this.LS=window.localStorage,e==null||!e)throw new Error("For local storage, modelPath must not be null, undefined or empty.");this.modelPath=e,this.keys=aw(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),r=JSON.stringify(e.weightSpecs),a=sh(e);try{this.LS.setItem(this.keys.info,JSON.stringify(a)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,r),this.LS.setItem(this.keys.weightData,FR(e.weightData));let n={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,signature:e.signature!=null?e.signature:void 0,userDefinedMetadata:e.userDefinedMetadata!=null?e.userDefinedMetadata:void 0,modelInitializer:e.modelInitializer!=null?e.modelInitializer:void 0,trainingConfig:e.trainingConfig!=null?e.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(n)),{modelArtifactsInfo:a}}catch(n){throw nw(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=${a.modelTopologyBytes}, weightSpecsBytes=${a.weightSpecsBytes}, weightDataBytes=${a.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={},r=JSON.parse(this.LS.getItem(this.keys.topology));if(r==null)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=r;let a=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(a==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=a;let n=this.LS.getItem(this.keys.modelMetadata);if(n!=null){let i=JSON.parse(n);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.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}};bo.URL_SCHEME="localstorage://";var sw=e=>Y().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(bo.URL_SCHEME)?ZR(e.slice(bo.URL_SCHEME.length)):null;Bt.registerSaveRouter(sw);Bt.registerLoadRouter(sw);function ZR(e){return new bo(e)}var YR=class{constructor(){P(Y().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=ru+Un,r=Un+rw;for(let a=0;a<this.LS.length;++a){let n=this.LS.key(a);if(n.startsWith(t)&&n.endsWith(r)){let s=KR(n);e[s]=JSON.parse(this.LS.getItem(n))}}return e}async removeModel(e){e=XR(e);let t=aw(e);if(this.LS.getItem(t.info)==null)throw new Error(`Cannot find model at path '${e}'`);let r=JSON.parse(this.LS.getItem(t.info));return nw(t),r}},iu="://",Ia=class{constructor(){this.managers={}}static getInstance(){return Ia.instance==null&&(Ia.instance=new Ia),Ia.instance}static registerManager(e,t){P(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(iu)&&(e=e.slice(0,e.indexOf(iu))),P(e.length>0,()=>"scheme must not be an empty string.");let r=Ia.getInstance();P(r.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),r.managers[e]=t}static getManager(e){let t=this.getInstance().managers[e];if(t==null)throw new Error(`Cannot find model manager for scheme '${e}'`);return t}static getSchemes(){return Object.keys(this.getInstance().managers)}};function zc(e){if(e.indexOf(iu)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Ia.getSchemes().join(",")}`);return{scheme:e.split(iu)[0],path:e.split(iu)[1]}}async function iw(e,t,r=!1){P(e!==t,()=>`Old path and new path are the same: '${e}'`);let a=Bt.getLoadHandlers(e);P(a.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),P(a.length<2,()=>`Copying failed because more than one (${a.length}) load handlers for source URL ${e}.`);let n=a[0],s=Bt.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 (${a.length}) save handlers for destination URL ${t}.`);let i=s[0],o=zc(e).scheme,l=zc(e).path,d=o===zc(e).scheme,u=await n.load();r&&d&&await Ia.getManager(o).removeModel(l);let p=await i.save(u);return r&&!d&&await Ia.getManager(o).removeModel(l),p.modelArtifactsInfo}async function JR(){let e=Ia.getSchemes(),t={};for(let r of e){let a=await Ia.getManager(r).listModels();for(let n in a){let s=r+iu+n;t[s]=a[n]}}return t}async function QR(e){let t=zc(e);return Ia.getManager(t.scheme).removeModel(t.path)}async function eF(e,t){return iw(e,t,!1)}async function tF(e,t){return iw(e,t,!0)}var rF=class{fetch(e,t){return fetch(e,t)}now(){return performance.now()}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Browser's encoder only supports utf-8, but got ${t}`);return this.textEncoder==null&&(this.textEncoder=new TextEncoder),this.textEncoder.encode(e)}decode(e,t){return new TextDecoder(t).decode(e)}};if(Y().get("IS_BROWSER")){Y().setPlatform("browser",new rF);try{Ia.registerManager(bo.URL_SCHEME,new YR)}catch(e){}try{Ia.registerManager(xo.URL_SCHEME,new UR)}catch(e){}}var aF={importFetch:()=>hE()},x1,nF=class{constructor(){this.util=cE(),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return Y().global.fetch!=null?Y().global.fetch(e,t):(x1==null&&(x1=aF.importFetch()),x1(e,t))}now(){let e=process.hrtime();return e[0]*1e3+e[1]/1e6}encode(e,t){if(t!=="utf-8"&&t!=="utf8")throw new Error(`Node built-in encoder only supports utf-8, but got ${t}`);return this.textEncoder.encode(e)}decode(e,t){return e.length===0?"":new this.util.TextDecoder(t).decode(e)}};Y().get("IS_NODE")&&!Y().get("IS_BROWSER")&&Y().setPlatform("node",new nF);function Le(e,t="float32",r){return t=t||"float32",$y(e),new tr(e,t,r)}function sF(e,t){let r=$(e,"x","cast");if(!Nv(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if(t==="string"&&r.dtype!=="string"||t!=="string"&&r.dtype==="string")throw new Error("Only strings can be casted to strings");let a={x:r},n={dtype:t};return B.runKernel(Xs,a,n)}var me=V({cast_:sF});function iF(e){let t={x:$(e,"x","clone","string_or_numeric")};return B.runKernel(ui,t)}var Pr=V({clone_:iF});function ow(e,t=!1){console.log(e.toString(t))}Kv();var oF={buffer:Le,cast:me,clone:Pr,print:ow};yR(oF);var Ir={};De(Ir,{browserFiles:()=>fF,browserHTTPRequest:()=>xF,concatenateArrayBuffers:()=>By,copyModel:()=>eF,decodeWeights:()=>Jv,encodeWeights:()=>ER,fromMemory:()=>vF,getLoadHandlers:()=>BR,getModelArtifactsForJSON:()=>Wy,getModelArtifactsInfoForJSON:()=>sh,getSaveHandlers:()=>LR,http:()=>Uy,isHTTPScheme:()=>W1,listModels:()=>JR,loadWeights:()=>mF,moveModel:()=>tF,registerLoadRouter:()=>_R,registerSaveRouter:()=>DR,removeModel:()=>QR,weightsLoaderFactory:()=>uw,withSaveHandler:()=>wF});var lF="model",uF=".json",dF=".weights.bin";function X5(e){return new Promise(t=>setTimeout(t)).then(e)}var B1=class{constructor(e){if(!Y().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(B1.URL_SCHEME)&&(e=e.slice(B1.URL_SCHEME.length)),(e==null||e.length===0)&&(e=lF),this.modelJsonFileName=e+uF,this.weightDataFileName=e+dF}async save(e){if(typeof document=="undefined")throw new Error("Browser downloads are not supported in this environment since `document` is not present");let t=window.URL.createObjectURL(new Blob([e.weightData],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{let r=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],a=Qv(e,r),n=window.URL.createObjectURL(new Blob([JSON.stringify(a)],{type:"application/json"})),s=this.modelJsonAnchor==null?document.createElement("a"):this.modelJsonAnchor;if(s.download=this.modelJsonFileName,s.href=n,await X5(()=>s.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){let i=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;i.download=this.weightDataFileName,i.href=t,await X5(()=>i.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:sh(e)}}}},ef=B1;ef.URL_SCHEME="downloads://";var pF=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 r=new FileReader;r.onload=a=>{let n=JSON.parse(a.target.result),s=n.modelTopology;if(s==null){t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));return}if(n.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=Wy(n,o=>this.loadWeights(o));e(i)},r.onerror=a=>t(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),r.readAsText(this.jsonFile)})}loadWeights(e){let t=[],r=[];for(let s of e)t.push(...s.weights),r.push(...s.paths);let a=this.checkManifestAndWeightFiles(e),n=r.map(s=>this.loadWeightsFile(s,a[s]));return Promise.all(n).then(s=>[t,By(s)])}loadWeightsFile(e,t){return new Promise((r,a)=>{let n=new FileReader;n.onload=s=>{let i=s.target.result;r(i)},n.onerror=s=>a(`Failed to weights data from file of path '${e}'.`),n.readAsArrayBuffer(t)})}checkManifestAndWeightFiles(e){let t=[],r=this.weightsFiles.map(n=>K5(n.name)),a={};for(let n of e)n.paths.forEach(s=>{let i=K5(s);if(t.indexOf(i)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${i}'`);if(t.push(i),r.indexOf(i)===-1)throw new Error(`Weight file with basename '${i}' is not provided.`);a[s]=this.weightsFiles[r.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 a}},hF=e=>Y().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(ef.URL_SCHEME)?cF(e.slice(ef.URL_SCHEME.length)):null;Bt.registerSaveRouter(hF);function cF(e="model"){return new ef(e)}function fF(e){return new pF(e)}function Z5(e,t,r,a){i(e),r=r==null?0:r,a=a==null?1:a,o(r,a);let n=0,s=l=>(l.then(d=>{let u=r+ ++n/e.length*(a-r);return t(u),d}),l);function i(l){P(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function o(l,d){P(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),P(d>=0&&d<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${d}`),P(d>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${d}`)}return Promise.all(e.map(s))}async function lw(e,t){t==null&&(t={});let r=t.fetchFunc==null?Y().platform.fetch:t.fetchFunc,a=e.map(d=>r(d,t.requestInit,{isBinary:!0})),n=0,s=.5,i=(t.onProgress==null?await Promise.all(a):await Z5(a,t.onProgress,n,s)).map(d=>d.arrayBuffer()),o=.5,l=1;return t.onProgress==null?await Promise.all(i):await Z5(i,t.onProgress,o,l)}async function mF(e,t="",r,a){return uw(n=>lw(n,{requestInit:a}))(e,t,r)}function uw(e){return async(t,r="",a)=>{let n=t.map(()=>!1),s={},i=a!=null?a.map(()=>!1):[],o=[];if(t.forEach((c,f)=>{let m=0;c.weights.forEach(g=>{let y="quantization"in g?g.quantization.dtype:g.dtype,A=z1[y]*Tt(g.shape),x=()=>{n[f]=!0,s[f]==null&&(s[f]=[]),s[f].push({manifestEntry:g,groupOffset:m,sizeBytes:A})};a!=null?a.forEach((b,v)=>{b===g.name&&(x(),i[v]=!0)}):x(),o.push(g.name),m+=A})}),!i.every(c=>c)){let c=a.filter((f,m)=>!i[m]);throw new Error(`Could not find weights in manifest with names: ${c.join(", ")}.
|
|
Manifest JSON has weights with names: ${o.join(", ")}.`)}let l=n.reduce((c,f,m)=>(f&&c.push(m),c),[]),d=[];l.forEach(c=>{t[c].paths.forEach(f=>{let m=r+(r.endsWith("/")?"":"/")+f;d.push(m)})});let u=await e(d),p={},h=0;return l.forEach(c=>{let f=t[c].paths.length,m=0;for(let x=0;x<f;x++)m+=u[h+x].byteLength;let g=new ArrayBuffer(m),y=new Uint8Array(g),A=0;for(let x=0;x<f;x++){let b=new Uint8Array(u[h+x]);y.set(b,A),A+=b.byteLength}s[c].forEach(x=>{let b=g.slice(x.groupOffset,x.groupOffset+x.sizeBytes),v=Jv(b,[x.manifestEntry]);for(let C in v)p[C]=v[C]}),h+=f}),p}}var gF="application/octet-stream",yF="application/json",Vy=class{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(P(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=Y().platform.fetch,P(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&P(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");let t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;let r=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],a=Qv(e,r);t.body.append("model.json",new Blob([JSON.stringify(a)],{type:yF}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:gF}),"model.weights.bin");let n=await this.fetch(this.path,t);if(n.ok)return{modelArtifactsInfo:sh(e),responses:[n]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${n.status}.`)}async load(){let e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(n){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 r=t.modelTopology,a=t.weightsManifest;if(r==null&&a==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return Wy(t,n=>this.loadWeights(n))}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[r,a]=AF(t),n=this.weightPathPrefix||r,s=[];for(let d of e)s.push(...d.weights);let i=[],o=[];for(let d of e)for(let u of d.paths)this.weightUrlConverter!=null?o.push(this.weightUrlConverter(u)):i.push(n+u+a);this.weightUrlConverter&&i.push(...await Promise.all(o));let l=await lw(i,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[s,By(l)]}};Vy.URL_SCHEME_REGEX=/^https?:\/\//;function AF(e){let t=e.lastIndexOf("/"),r=e.lastIndexOf("?"),a=e.substring(0,t),n=r>t?e.substring(r):"";return[a+"/",n]}function W1(e){return e.match(Vy.URL_SCHEME_REGEX)!=null}var dw=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let r=!0;if(Array.isArray(e)?r=e.every(a=>W1(a)):r=W1(e),r)return Uy(e,t)}return null};Bt.registerSaveRouter(dw);Bt.registerLoadRouter(dw);function Uy(e,t){return new Vy(e,t)}function xF(e,t){return Uy(e,t)}var b1=class{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}},bF=class{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}};function vF(e,t,r,a){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new b1(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 b1({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 b1({modelTopology:e,weightSpecs:t,weightData:r,trainingConfig:a}))}function wF(e){return new bF(e)}var pw={};De(pw,{confusionMatrix:()=>CF});function kF(e,t,r=!1,a=!1){let n=$(e,"a","matMul"),s=$(t,"b","matMul");[n,s]=Dt(n,s);let i={a:n,b:s},o={transposeA:r,transposeB:a};return B.runKernel(Ks,i,o)}var Ke=V({matMul_:kF});function IF(e,t,r=1,a=0){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);let n={indices:$(e,"indices","oneHot","int32")},s={depth:t,onValue:r,offValue:a};return B.runKernel(Jo,n,s)}var Ep=V({oneHot_:IF});function SF(e,t){let r=$(e,"x","transpose");if(t==null&&(t=r.shape.map((s,i)=>i).reverse()),P(r.rank===t.length,()=>`Error in transpose: rank of input ${r.rank} must match length of perm ${t}.`),t.forEach(s=>{P(s>=0&&s<r.rank,()=>`All entries in 'perm' must be between 0 and ${r.rank-1} but got ${t}`)}),r.rank<=1)return r.clone();let a={x:r},n={perm:t};return B.runKernel(Oi,a,n)}var rt=V({transpose_:SF});function TF(e,t,r){let a=$(e,"labels","confusionMatrix"),n=$(t,"predictions","confusionMatrix");P(r==null||r>0&&Number.isInteger(r),()=>`If provided, numClasses must be a positive integer, but got ${r}`),P(a.rank===1,()=>`Expected the rank of labels to be 1, but got ${a.rank}`),P(n.rank===1,()=>`Expected the rank of predictions to be 1, but got ${n.rank}`),P(a.shape[0]===n.shape[0],()=>`Mismatch in the number of examples: ${a.shape[0]} vs. ${n.shape[0]}. Labels and predictions should have the same number of elements.`),P(r>0&&Number.isInteger(r),()=>`numClasses is required to be a positive integer, but got ${r}`);let s=Ep(me(a,"int32"),r),i=Ep(me(n,"int32"),r),o=rt(s),l=Ke(o,i);return me(l,"int32")}var CF=V({confusionMatrix_:TF}),yl={};De(yl,{assertAndGetBroadcastShape:()=>bt,getBroadcastDims:()=>hw,getReductionAxes:()=>Xt});function hw(e,t){let r=e.length,a=[];for(let n=0;n<r;n++){let s=r-1-n,i=e[s]||1;(t[t.length-1-n]||1)>1&&i===1&&a.unshift(s)}return a}function Xt(e,t){let r=[];for(let a=0;a<t.length;a++){let n=e[e.length-a-1],s=t.length-a-1,i=t[s];(n==null||n===1&&i>1)&&r.unshift(s)}return r}function bt(e,t){let r=[],a=Math.max(e.length,t.length);for(let n=0;n<a;n++){let s=e[e.length-n-1];s==null&&(s=1);let i=t[t.length-n-1];if(i==null&&(i=1),s===1)r.unshift(i);else if(i===1)r.unshift(s);else if(s!==i){let o=`Operands could not be broadcast together with shapes ${e} and ${t}.`;throw Error(o)}else r.unshift(s)}return r}var $a={};De($a,{fromPixels:()=>PF,fromPixelsAsync:()=>MF,toPixels:()=>$F});function cw(e,t,r){if(Ro(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let a=Cn(e,r);if(a.length!==3&&a.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Di(e,t,a,r)}var ro;function fw(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 r=!1,a=!1,n=!1,s=!1,i=!1,o=!1;if(e.data instanceof Uint8Array)r=!0;else if(typeof ImageData!="undefined"&&e instanceof ImageData)a=!0;else if(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)n=!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(n&&n&&e.readyState<2)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.");if(Yc(Ip,B.backendName)!=null){let h={pixels:e},c={numChannels:t};return B.runKernel(Ip,h,c)}let[l,d]=n?[e.videoWidth,e.videoHeight]:[e.width,e.height],u;if(i)u=e.getContext("2d").getImageData(0,0,l,d).data;else if(a||r)u=e.data;else if(s||n||o){if(ro==null)if(typeof document=="undefined")if(typeof OffscreenCanvas!="undefined"&&typeof OffscreenCanvasRenderingContext2D!="undefined")ro=new OffscreenCanvas(1,1).getContext("2d");else throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");else ro=document.createElement("canvas").getContext("2d");ro.canvas.width=l,ro.canvas.height=d,ro.drawImage(e,0,0,l,d),u=ro.getImageData(0,0,l,d).data}let p;if(t===4)p=new Int32Array(u);else{let h=l*d;p=new Int32Array(h*t);for(let c=0;c<h;c++)for(let f=0;f<t;++f)p[c*t+f]=u[c*4+f]}return cw(p,[d,l,t],"int32")}function NF(e){return e!=null&&e.data instanceof Uint8Array}function EF(){return typeof window!="undefined"&&typeof ImageBitmap!="undefined"&&window.hasOwnProperty("createImageBitmap")}function RF(e){return e!=null&&e.width!==0&&e.height!==0}function FF(e){return EF()&&!(e instanceof ImageBitmap)&&RF(e)&&!NF(e)}async function MF(e,t=3){let r=null;if(Y().getBool("WRAP_TO_IMAGEBITMAP")&&FF(e)){let a;try{a=await createImageBitmap(e,{premultiplyAlpha:"none"})}catch(n){a=null}a!=null&&a.width===e.width&&a.height===e.height?r=a:r=e}else r=e;return fw(r,t)}async function $F(e,t){let r=$(e,"img","toPixels");if(!(e instanceof et)){let d=r;r=me(d,"int32"),d.dispose()}if(r.rank!==2&&r.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${r.rank}.`);let[a,n]=r.shape.slice(0,2),s=r.rank===2?1:r.shape[2];if(s>4||s===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${s}`);if(r.dtype!=="float32"&&r.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${r.dtype}. Please use float32 or int32 tensors.`);let i=await r.data(),o=r.dtype==="float32"?255:1,l=new Uint8ClampedArray(n*a*4);for(let d=0;d<a*n;++d){let u=[0,0,0,255];for(let h=0;h<s;h++){let c=i[d*s+h];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}.`);s===1?(u[0]=c*o,u[1]=c*o,u[2]=c*o):u[h]=c*o}let p=d*4;l[p+0]=Math.round(u[0]),l[p+1]=Math.round(u[1]),l[p+2]=Math.round(u[2]),l[p+3]=Math.round(u[3])}if(t!=null){t.width=n,t.height=a;let d=t.getContext("2d"),u=new ImageData(l,n,a);d.putImageData(u,0,0)}return r!==e&&r.dispose(),l}var PF=V({fromPixels_:fw}),Gy={};De(Gy,{prepareAndValidate:()=>mw});function mw(e,t){let r=e.shape.length,a=t.shape.length;if(r<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${r}.`);if(a<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${a}.`);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[a-1]>r)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[a-1]} vs. ${r}`);if(Tt(e.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);let n=t.shape,s=n[n.length-1],i=1;for(let p=0;p<n.length-1;++p)i*=n[p];let o=e.shape,l=n.slice();l.pop();let d=1;for(let p=s;p<r;++p)d*=o[p],l.push(o[p]);let u=[...Su(e.shape).map(p=>p/d),1].slice(0,s);return[l,i,d,u]}var jy={};De(jy,{calculateShapes:()=>gw,validateInput:()=>qy,validateUpdateShape:()=>Hy});function Hy(e,t,r){let a=t.rank>1?t.shape[t.rank-1]:1,n=t.rank>1?t.rank-1:1,s=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${r.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${a}, and batchDim: ${n}.`;if(r.rank<n)throw new Error(s+` update.rank < ${n}. `);if(e.length<a+(r.rank-n))throw new Error(s+` Output shape length < ${a+(r.rank-n)}`);if(r.rank!==n+e.length-a)throw new Error(s+` update.rank != ${n+e.length-a}`);for(let i=0;i<n;++i)if(r.shape[i]!==t.shape[i])throw new Error(s+` updates.shape[${i}] (${r.shape[i]}) != indices.shape[${i}] (${t.shape[i]}).`);for(let i=0;i<r.rank-n;++i)if(r.shape[i+n]!==e[i+a])throw new Error(s+` updates.shape[${i+n}] (${r.shape[i+n]}) != shape[${i+n}] (${e[i+n]})`)}function qy(e,t,r){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(r.length<1)throw new Error(`Output rank must be greater or equal to 1, but got shape: ${r}`);if(r.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}`)}Hy(r,t,e)}function gw(e,t,r){let a=t.shape.length,n=a>1?t.shape[a-1]:1,s=r.length,i=1;for(let p=n;p<s;++p)i*=r[p];let o=n<1?1:n,l=Tt(t.shape)/o,d=[...Su(r.slice(0,n)),1],u=Tt(r);return{sliceRank:n,numUpdates:l,sliceSize:i,strides:d,outputSize:u}}var Ot={};De(Ot,{assertParamsValid:()=>zF,computeFlatOffset:()=>WF,computeOutShape:()=>_F,getNormalizedAxes:()=>LF,isSliceContinous:()=>BF,maskToAxes:()=>DF,parseSliceParams:()=>Sw,sliceInfo:()=>VF,startForAxis:()=>kw,startIndicesWithElidedDims:()=>bw,stopForAxis:()=>Iw,stopIndicesWithElidedDims:()=>vw,stridesForAxis:()=>ww,stridesWithElidedDims:()=>yw});var V1=-2,OF=-1;function zF(e,t,r){let a=e.shape.length;P(a===t.length,()=>`Error in slice${a}D: Length of begin ${t} must match the rank of the array (${a}).`),P(a===r.length,()=>`Error in slice${a}D: Length of size ${r} must match the rank of the array (${a}).`);for(let n=0;n<a;++n)P(t[n]+r[n]<=e.shape[n],()=>`Error in slice${a}D: begin[${n}] + size[${n}] (${t[n]+r[n]}) would overflow input.shape[${n}] (${e.shape[n]})`)}function DF(e){let t=[],r=0;for(;e>0;)e&1&&t.push(r),e/=2,r++;return t}function _F(e,t,r){let a=[];for(let n=0;n<e.length;n++)a[n]=Math.ceil((t[n]-e[n])/r[n]);return a}function yw(e,t,r,a){let n=[...e];for(let s=n.length;s<a.length;s++)n.push(1);for(let s=0;s<r;s++)s===0?n[t]=1:(n.splice(t,0,1),n.pop());return n}function Aw(e,t,r){return r<=e?r:r-(t-1)}function xw(e,t){let r=[];for(let a=0;a<e;a++)r.push(t+a);return r}function LF(e,t,r,a,n,s,i,o,l){let d=e.length,u=new Array(d),p=new Array(d),h=new Array(d);if(t.length&&r>0){let c=t[0],f=r+1;u=bw(i,c,f,a,e),p=vw(o,c,f,n,e),h=yw(s,c,f,e)}else for(let c=0;c<d;c++)u[c]=kw(i,a,s,e,c,l),p[c]=Iw(o,n,s,e,c,l),h[c]=ww(s,c,l);return{begin:u,end:p,strides:h}}function bw(e,t,r,a,n){let s=[...n],i=xw(r,t);for(let o=0;o<s.length;o++)if(i.indexOf(o)>-1)s[o]=0;else{let l=Aw(t,r,o),d=a[l];e&1<<l&&(d=0),s[o]=d}return s}function vw(e,t,r,a,n){let s=[...n],i=xw(r,t);for(let o=0;o<s.length;o++)if(i.indexOf(o)>-1)s[o]=Number.MAX_SAFE_INTEGER;else{let l=Aw(t,r,o),d=a[l];e&1<<l&&(d=Number.MAX_SAFE_INTEGER),s[o]=d}for(let o=0;o<s.length;o++){let l=n[o];s[o]<0&&(s[o]+=l),s[o]=kp(0,s[o],n[o])}return s}function ww(e,t,r){let a=e[t];return(r&1<<t||a==null)&&(a=1),a}function kw(e,t,r,a,n,s){let i=t[n],o=r[n]||1;(e&1<<n||s&1<<n||i==null)&&(o>0?i=Number.MIN_SAFE_INTEGER:i=Number.MAX_SAFE_INTEGER);let l=a[n];return i<0&&(i+=l),i=kp(0,i,l-1),i}function Iw(e,t,r,a,n,s){let i=t[n],o=r[n]||1;(e&1<<n||s&1<<n||i==null)&&(o>0?i=Number.MAX_SAFE_INTEGER:i=Number.MIN_SAFE_INTEGER);let l=a[n];return i<0&&(i+=l),o>0?i=kp(0,i,l):i=kp(-1,i,l-1),i}function BF(e,t,r){let a=r.length;for(let n=0;n<r.length;n++)if(r[n]>1){a=n;break}for(let n=a+1;n<r.length;n++)if(t[n]>0||r[n]!==e[n])return!1;return!0}function WF(e,t){let r=e.length>0?e[e.length-1]:1;for(let a=0;a<e.length-1;a++)r+=e[a]*t[a];return r}function Sw(e,t,r){let a,n=e.shape.length;typeof t=="number"?a=[t,...new Array(n-1).fill(0)]:t.length<n?a=t.concat(new Array(n-t.length).fill(0)):a=t.slice(),a.forEach(i=>{P(i!==-1,()=>"slice() does not support negative begin indexing.")});let s;return r==null?s=new Array(n).fill(-1):typeof r=="number"?s=[r,...new Array(n-1).fill(-1)]:r.length<n?s=r.concat(new Array(n-r.length).fill(-1)):s=r,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]-a[o])),[a,s]}function VF(e,t,r,a,n,s,i,o,l){let d;if(a==null?(d=new Array(t.length),d.fill(1)):d=a,i!=null&&(i&i-1)!==0)throw new Error("Multiple ellipses in slice is not allowed.");let u=!1,p={dims:d.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:r.slice(),strides:d.slice(),beginMask:n,endMask:s,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};for(let A=0;A<p.dims;A++)u&&(1<<A&o)!==0&&p.numAddAxisAfterEllipsis++,1<<A&i&&(u=!0);u||(p.ellipsisMask|=1<<p.dims,p.dims++);let h={dims:e.length,beginMask:0,endMask:0,beginValid:!1,endValid:!1};UF(p,h);let c=!0,f=!0,m=!0,g=[],y=[];for(let A=0;A<e.length;++A){if(h.strides[A]===0)throw Error(`strides[${A}] must be non-zero`);let x=!!(h.shrinkAxisMask&1<<A),b=e[A];if(b===-1){g.push(x?1:-1);continue}let v=[h.beginMask&1<<A,h.endMask&1<<A],C=[h.strides[A]>0?0:-1,h.strides[A]>0?b:b-1];if(x&&h.strides[A]<=0)throw Error("only stride 1 allowed on non-range indexing.");m=m&&h.strides[A]===1;let T=!!(h.beginMask&1<<A&&h.endMask&1<<A);if(h.beginValid&&h.endValid){if(x){let M=h.begin[A]<0?b+h.begin[A]:h.begin[A];if(h.begin[A]=M,h.end[A]=h.begin[A]+1,M<0||M>=b)throw Error(`slice index ${h.begin[A]} of dimension ${A} out of bounds.`)}else h.begin[A]=Y5(h.begin[A],0,h.strides[A],b,v,C),h.end[A]=Y5(h.end[A],1,h.strides[A],b,v,C);let z=h.strides[A]===1&&h.begin[A]===0&&h.end[A]===b;c=c&&z,f=f&&(A===0&&h.strides[A]===1||z)}else c=c&&h.strides[A]===1&&T,f=f&&(A===0&&h.strides[A]===1||T);let E,R=!1;if(h.beginValid&&h.endValid?(E=h.end[A]-h.begin[A],R=!0):x?(E=1,R=!0):T&&b>=0&&(h.strides[A]<0?E=-b:E=b,R=!0),R){let z;E===0||E<0!=h.strides[A]<0?z=0:z=Math.trunc(E/h.strides[A])+(E%h.strides[A]!==0?1:0),g.push(z)}else g.push(-1)}for(let A=0;A<h.finalShapeGatherIndices.length;++A){let x=h.finalShapeGatherIndices[A];x>=0?y.push(g[x]):x===V1&&y.push(1)}return{finalShapeSparse:y.filter((A,x)=>h.finalShapeGatherIndices[x]!==V1),finalShape:y,isIdentity:c,sliceDim0:f,isSimpleSlice:m,begin:h.begin,end:h.end,strides:h.strides}}function UF(e,t){t.beginMask=0,t.endMask=0,t.shrinkAxisMask=0;let r=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 a=0;a<e.dims;a++)if(1<<a&e.ellipsisMask){let n=Math.min(t.dims-(e.dims-a)+1+e.numAddAxisAfterEllipsis,t.dims);for(;r<n;r++)t.begin[r]=0,t.end[r]=0,t.strides[r]=1,t.beginMask|=1<<r,t.endMask|=1<<r,t.finalShapeGatherIndices.push(r),t.finalShapeGatherIndicesSparse.push(-1),t.inputShapeGatherIndicesSparse[r]=a}else if(1<<a&e.newAxisMask)t.finalShapeGatherIndices.push(V1),t.finalShapeGatherIndicesSparse.push(-1);else{if(r===t.begin.length)throw Error(`Index out of range using input dim ${r}; input has only ${t.dims} dims, ${t.begin.length}.`);e.begin!=null&&(t.begin[r]=e.begin[a]),e.end!=null&&(t.end[r]=e.end[a]),t.strides[r]=e.strides[a],e.beginMask&1<<a&&(t.beginMask|=1<<r),e.endMask&1<<a&&(t.endMask|=1<<r),e.shrinkAxisMask&1<<a?(t.finalShapeGatherIndices.push(OF),t.finalShapeGatherIndicesSparse.push(-1),t.shrinkAxisMask|=1<<r):(t.finalShapeGatherIndices.push(r),t.finalShapeGatherIndicesSparse.push(a)),t.inputShapeGatherIndicesSparse[r]=a,r++}}function Y5(e,t,r,a,n,s){if(n[t])return r>0?s[t]:s[t+1&1];{let i=e<0?a+e:e;return i<s[0]?s[0]:i>s[1]?s[1]:i}}var de={};De(de,{Serializable:()=>Tw,SerializationMap:()=>oo,registerClass:()=>_i});var Tw=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},oo=class{constructor(){this.classNameMap={}}static getMap(){return oo.instance==null&&(oo.instance=new oo),oo.instance}static register(e){oo.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function _i(e){P(e.className!=null,()=>"Class being registered does not have the static className property defined."),P(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),P(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),oo.register(e)}var Cw={};De(Cw,{TEST_EPSILON_FLOAT16:()=>Nw,encodeStrings:()=>Ew,expectArrayBuffersEqual:()=>ZF,expectArraysClose:()=>jF,expectArraysEqual:()=>qF,expectNumbersClose:()=>KF,expectPromiseToFail:()=>HF,expectValuesInRange:()=>XF,testEpsilon:()=>Ky});var GF=.001,Nw=.1;function jF(e,t,r){return r==null&&(r=Ky()),U1(e,t,(a,n)=>Xy(a,n,r))}function Ky(){return B.backend.floatPrecision()===32?GF:Nw}function U1(e,t,r){let a=!0;if((wr(e)||wr(t))&&(a=!1),wr(e)&&wr(t)&&(a=!0),a){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=Cn(e),o=Cn(t);if(!Gs(i,o))throw new Error(`Arrays have different shapes. Actual: [${i}]. Expected: [${o}]`)}let n=wr(e)?e:Ao(e),s=wr(t)?t:Ao(t);if(n.length!==s.length)throw new Error(`Arrays have different lengths actual: ${n.length} vs expected: ${s.length}.
|
|
Actual: ${n}.
|
|
Expected: ${s}.`);for(let i=0;i<s.length;++i){let o=n[i],l=s[i];if(!r(o,l))throw new Error(`Arrays differ: actual[${i}] = ${o}, expected[${i}] = ${l}.
|
|
Actual: ${n}.
|
|
Expected: ${s}.`)}}function HF(e,t){e().then(()=>t.fail(),()=>t())}function qF(e,t){let r=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Is(e)||Is(e[0])||Is(t)||Is(t[0])?U1(e,r,(a,n)=>a==n):U1(e,t,(a,n)=>Xy(a,n,0))}function KF(e,t,r){if(r==null&&(r=Ky()),!Xy(e,t,r))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function Xy(e,t,r){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>r)}function XF(e,t,r){for(let a=0;a<e.length;a++)if(e[a]<t||e[a]>r)throw new Error(`Value out of range:${e[a]} low: ${t}, high: ${r}`)}function ZF(e,t){let r=new Float32Array(e),a=new Float32Array(t);if(r.length!==a.length)throw new Error(`Expected ArrayBuffer to be of length ${a.length}, but it was ${r.length}`);for(let n=0;n<a.length;n++)if(r[n]!==a[n])throw new Error(`Expected ArrayBuffer value at ${n} to be ${a[n]} but got ${r[n]} instead`)}function Ew(e){for(let t=0;t<e.length;t++){let r=e[t];Array.isArray(r)?Ew(r):e[t]=rh(r)}return e}var Zy="0.0.0";function Yy(){Y().set("PROD",!0)}function YF(){Y().set("DEBUG",!0)}function JF(){Y().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function Jy(e){Y().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}AR(Jy);function QF(){B.disposeVariables()}function kr(){return B}function tf(){return B.memory()}function eM(e){return B.profile(e)}function q(e,t){return B.tidy(e,t)}function re(e){Dy(e).forEach(t=>t.dispose())}function dr(e){return B.keep(e)}function tM(e){return B.time(e)}function Qy(e){return B.setBackend(e)}function Qu(){return B.ready()}function ca(){return B.backendName}function rM(e){B.removeBackend(e)}function e2(e){return B.findBackend(e)}function aM(e){return B.findBackendFactory(e)}function Al(e,t,r=1){return B.registerBackend(e,t,r)}function cn(){return B.backend}function nM(e,t){Y().setPlatform(e,t)}function sM(e,t){let r=$(e,"a","add"),a=$(t,"b","add");[r,a]=Dt(r,a);let n={a:r,b:a};return B.runKernel(qn,n)}var ue=V({add_:sM});function iM(e,t){let r=$(e,"a","floorDiv"),a=$(t,"b","floorDiv");[r,a]=Dt(r,a);let n={a:r,b:a};return B.runKernel(ii,n)}var ih=V({floorDiv_:iM});function oM(e,t){let r=$(e,"a","div"),a=$(t,"b","div");if([r,a]=Dt(r,a),r.dtype==="int32"&&a.dtype==="int32")return ih(r,a);let n={a:r,b:a},s={};return B.runKernel(ri,n,s)}var pe=V({div_:oM});function lM(e,t){let r=$(e,"a","mul"),a=$(t,"b","mul");[r,a]=Dt(r,a);let n={a:r,b:a};return B.runKernel(xi,n)}var L=V({mul_:lM});function uM(e){let t=$(e,"x","abs");if(t.dtype==="complex64"){let r={x:t};return B.runKernel(Bp,r)}else{let r={x:t};return B.runKernel(Fo,r)}}var Qt=V({abs_:uM});function dM(e){let t={x:$(e,"x","acos")};return B.runKernel(Tu,t)}var Rw=V({acos_:dM});function pM(e){let t={x:$(e,"x","acosh")};return B.runKernel(Cu,t)}var Fw=V({acosh_:pM});function hM(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((n,s)=>$(n,`tensors${s}`,"addN")),r=t[0];t.forEach(n=>{if(n.dtype!==r.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(n=>{if(!Gs(n.shape,r.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let a=t;return B.runKernel(js,a)}var Jf=V({addN_:hM});function cM(e,t=null,r=!1){let a={x:$(e,"x","all","bool")},n={axis:t,keepDims:r};return B.runKernel(Nu,a,n)}var t2=V({all_:cM});function fM(e,t=null,r=!1){let a={x:$(e,"x","any","bool")},n={axis:t,keepDims:r};return B.runKernel(Eu,a,n)}var rf=V({any_:fM});function mM(e,t=0){let r={x:$(e,"x","argMax")},a={axis:t};return B.runKernel(Hs,r,a)}var Ta=V({argMax_:mM});function gM(e,t=0){let r={x:$(e,"x","argMin")},a={axis:t};return B.runKernel(Ru,r,a)}var Mw=V({argMin_:gM});function yM(e){let t={x:$(e,"x","asin")};return B.runKernel(Fu,t)}var $w=V({asin_:yM});function AM(e){let t={x:$(e,"x","asinh")};return B.runKernel(Mu,t)}var Pw=V({asinh_:AM});function xM(e){let t={x:$(e,"x","atan")};return B.runKernel($u,t)}var Ow=V({atan_:xM});function bM(e,t){let r=$(e,"a","atan2"),a=$(t,"b","atan2");[r,a]=Dt(r,a);let n={a:r,b:a};return B.runKernel(Ou,n)}var zw=V({atan2_:bM});function vM(e){let t={x:$(e,"x","atanh")};return B.runKernel(Pu,t)}var Dw=V({atanh_:vM});function wM(e,t,r,a,n="NHWC",s){let i=e[3],o=[...t,i],l=Bw(n);return oh(e,o,r,s,a,null,null,l)}function _w(e,t,r,a,n,s,i="channelsLast"){let[o,l]=af(t),d;if(i==="channelsLast")d=[o,l,e[3],e[3]];else if(i==="channelsFirst")d=[o,l,e[1],e[1]];else throw new Error(`Unknown dataFormat ${i}`);return oh(e,d,r,a,n,s,!1,i)}function kM(e,t,r,a,n,s,i="NDHWC"){let[o,l,d]=G1(t),u,p;if(i==="NDHWC")p="channelsLast",u=[o,l,d,e[4],e[4]];else if(i==="NCDHW")p="channelsFirst",u=[o,l,d,e[1],e[1]];else throw new Error(`Unknown dataFormat ${i}`);return Lw(e,u,r,a,n,!1,p,s)}function oh(e,t,r,a,n,s,i=!1,o="channelsLast"){let[l,d,u,p]=[-1,-1,-1,-1];if(o==="channelsLast")[l,d,u,p]=e;else if(o==="channelsFirst")[l,p,d,u]=e;else throw new Error(`Unknown dataFormat ${o}`);let[h,c,,f]=t,[m,g]=af(r),[y,A]=af(a),x=ou(h,y),b=ou(c,A),{padInfo:v,outHeight:C,outWidth:T}=TM(n,d,u,m,g,x,b,s,o),E=i?f*p:f,R;return o==="channelsFirst"?R=[l,E,C,T]:o==="channelsLast"&&(R=[l,C,T,E]),{batchSize:l,dataFormat:o,inHeight:d,inWidth:u,inChannels:p,outHeight:C,outWidth:T,outChannels:E,padInfo:v,strideHeight:m,strideWidth:g,filterHeight:h,filterWidth:c,effectiveFilterHeight:x,effectiveFilterWidth:b,dilationHeight:y,dilationWidth:A,inShape:e,outShape:R,filterShape:t}}function Lw(e,t,r,a,n,s=!1,i="channelsLast",o){let[l,d,u,p,h]=[-1,-1,-1,-1,-1];if(i==="channelsLast")[l,d,u,p,h]=e;else if(i==="channelsFirst")[l,h,d,u,p]=e;else throw new Error(`Unknown dataFormat ${i}`);let[c,f,m,,g]=t,[y,A,x]=G1(r),[b,v,C]=G1(a),T=ou(c,b),E=ou(f,v),R=ou(m,C),{padInfo:z,outDepth:M,outHeight:I,outWidth:D}=CM(n,d,u,p,y,A,x,T,E,R,o),O=s?g*h:g,j;return i==="channelsFirst"?j=[l,O,M,I,D]:i==="channelsLast"&&(j=[l,M,I,D,O]),{batchSize:l,dataFormat:i,inDepth:d,inHeight:u,inWidth:p,inChannels:h,outDepth:M,outHeight:I,outWidth:D,outChannels:O,padInfo:z,strideDepth:y,strideHeight:A,strideWidth:x,filterDepth:c,filterHeight:f,filterWidth:m,effectiveFilterDepth:T,effectiveFilterHeight:E,effectiveFilterWidth:R,dilationDepth:b,dilationHeight:v,dilationWidth:C,inShape:e,outShape:j,filterShape:t}}function IM(e,t,r,a,n){a==null&&(a=r2(e,t,r));let s=e[0],i=e[1],o=fo((s-t+2*a)/r+1,n),l=fo((i-t+2*a)/r+1,n);return[o,l]}function SM(e,t,r,a,n,s){n==null&&(n=r2(e,t,a));let i=e[0],o=e[1],l=e[2],d=fo((i-t+2*n)/a+1,s),u=fo((o-t+2*n)/a+1,s),p=fo((l-t+2*n)/a+1,s);return[d,u,p,r]}function r2(e,t,r,a=1){let n=ou(t,a);return Math.floor((e[0]*(r-1)-r+n)/2)}function af(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function G1(e){return typeof e=="number"?[e,e,e]:e}function ou(e,t){return t<=1?e:e+(e-1)*(t-1)}function TM(e,t,r,a,n,s,i,o,l){let d,u,p;if(typeof e=="number"){d={top:e,bottom:e,left:e,right:e,type:e===0?"VALID":"NUMBER"};let h=IM([t,r],s,a,e,o);u=h[0],p=h[1]}else if(e==="same"){u=Math.ceil(t/a),p=Math.ceil(r/n);let h=Math.max(0,(u-1)*a+s-t),c=Math.max(0,(p-1)*n+i-r),f=Math.floor(h/2),m=h-f,g=Math.floor(c/2),y=c-g;d={top:f,bottom:m,left:g,right:y,type:"SAME"}}else if(e==="valid")d={top:0,bottom:0,left:0,right:0,type:"VALID"},u=Math.ceil((t-s+1)/a),p=Math.ceil((r-i+1)/n);else if(typeof e=="object"){let h=l==="channelsLast"?e[1][0]:e[2][0],c=l==="channelsLast"?e[1][1]:e[2][1],f=l==="channelsLast"?e[2][0]:e[3][0],m=l==="channelsLast"?e[2][1]:e[3][1];d={top:h,bottom:c,left:f,right:m,type:h===0&&c===0&&f===0&&m===0?"VALID":"EXPLICIT"},u=fo((t-s+h+c)/a+1,o),p=fo((r-i+f+m)/n+1,o)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:d,outHeight:u,outWidth:p}}function CM(e,t,r,a,n,s,i,o,l,d,u){let p,h,c,f;if(typeof e=="number"){p={top:e,bottom:e,left:e,right:e,front:e,back:e,type:e===0?"VALID":"NUMBER"};let m=SM([t,r,a,1],o,1,n,e,u);h=m[0],c=m[1],f=m[2]}else if(e==="same"){h=Math.ceil(t/n),c=Math.ceil(r/s),f=Math.ceil(a/i);let m=(h-1)*n+o-t,g=(c-1)*s+l-r,y=(f-1)*i+d-a,A=Math.floor(m/2),x=m-A,b=Math.floor(g/2),v=g-b,C=Math.floor(y/2),T=y-C;p={top:b,bottom:v,left:C,right:T,front:A,back:x,type:"SAME"}}else if(e==="valid")p={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},h=Math.ceil((t-o+1)/n),c=Math.ceil((r-l+1)/s),f=Math.ceil((a-d+1)/i);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outDepth:h,outHeight:c,outWidth:f}}function fo(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 Ps(e){let[t,r,a]=af(e);return t===1&&r===1&&a===1}function Rn(e,t){return Ps(e)||Ps(t)}function Bw(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function Lr(e,t,r){if(r!=null){if(typeof t=="string")throw Error(`Error in ${e}: pad must be an integer when using dimRoundingMode ${r} but got pad ${t}.`);if(typeof t=="number")P(du(t),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${r} but got pad ${t}.`);else if(typeof t=="object")t.forEach(a=>{a.forEach(n=>{P(du(n),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${r} but got pad ${n}.`)})});else throw Error(`Error in ${e}: Unknown padding parameter: ${t}`)}}function NM(e,t){let r={x:$(e,"x","reshape","string_or_numeric")},a={shape:t};return B.runKernel(tl,r,a)}var U=V({reshape_:NM});function EM(e,t,r,a,n){let s=$(e,"x","avgPool","float32"),i=1;P(Rn(r,i),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${r} and dilations '${i}'`);let o=s,l=!1;s.rank===3&&(l=!0,o=U(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}.`),Lr("avgPool",a,n);let d={x:o},u={filterSize:t,strides:r,pad:a,dimRoundingMode:n},p=B.runKernel(qs,d,u);return p=me(p,s.dtype),l?U(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var Qf=V({avgPool_:EM});function RM(e,t,r,a,n,s="NDHWC"){let i=$(e,"x","avgPool3d","float32"),o=i,l=!1;i.rank===4&&(l=!0,o=U(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}`),Lr("avgPool3d",a,n);let d={x:o},u={filterSize:t,strides:r,pad:a,dimRoundingMode:n,dataFormat:s},p=B.runKernel(_p,d,u);return p=me(p,o.dtype),l?U(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var a2=V({avgPool3d_:RM});function FM(e,t=0){P(e.length>=1,()=>"Pass at least one tensor to concat");let r=Np(e,"tensors","concat","string_or_numeric");if(r[0].dtype==="complex64"&&r.forEach(s=>{if(s.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
|
|
with dtype ${s.dtype}. `)}),r.length===1)return Pr(r[0]);let a=r,n={axis:t};return B.runKernel($o,a,n)}var kt=V({concat_:FM});function MM(e){let t={x:$(e,"x","sigmoid","float32")};return B.runKernel(Ni,t)}var Sr=V({sigmoid_:MM});function $M(e,t,r){let a=$(e,"x","slice","string_or_numeric");if(a.rank===0)throw new Error("Slicing scalar is not possible");let n={x:a},s={begin:t,size:r};return B.runKernel(il,n,s)}var Oe=V({slice_:$M});function PM(e){let t={x:$(e,"x","tanh","float32")};return B.runKernel(Pi,t)}var hu=V({tanh_:PM});function OM(e,t,r,a,n,s){let i=$(e,"forgetBias","basicLSTMCell"),o=$(t,"lstmKernel","basicLSTMCell"),l=$(r,"lstmBias","basicLSTMCell"),d=$(a,"data","basicLSTMCell"),u=$(n,"c","basicLSTMCell"),p=$(s,"h","basicLSTMCell"),h=kt([d,p],1),c=Ke(h,o),f=ue(c,l),m=f.shape[0],g=f.shape[1]/4,y=[m,g],A=Oe(f,[0,0],y),x=Oe(f,[0,g],y),b=Oe(f,[0,g*2],y),v=Oe(f,[0,g*3],y),C=ue(L(Sr(A),hu(x)),L(u,Sr(ue(i,b)))),T=L(hu(C),Sr(v));return[C,T]}var zM=V({basicLSTMCell_:OM});function DM(e,t,r){let a=$(e,"x","batchToSpaceND"),n=t.reduce((o,l)=>o*l);P(a.rank>=1+t.length,()=>`input rank is ${a.rank} but should be > than blockShape.length ${t.length}`),P(r.length===t.length,()=>`crops.length is ${r.length} but should be equal to blockShape.length ${t.length}`),P(a.shape[0]%n===0,()=>`input tensor batch is ${a.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${n}`);let s={x:a},i={blockShape:t,crops:r};return B.runKernel(Mo,s,i)}var em=V({batchToSpaceND_:DM});function _M(e){let t;return e.rank===0||e.rank===1?t=U(e,[1,1,1,e.size]):e.rank===2?t=U(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=U(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function LM(e,t,r,a,n,s){s==null&&(s=.001);let i=$(e,"x","batchNorm"),o=$(t,"mean","batchNorm"),l=$(r,"variance","batchNorm"),d;n!=null&&(d=$(n,"scale","batchNorm"));let u;a!=null&&(u=$(a,"offset","batchNorm")),P(o.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),P(u==null||o.rank===u.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),P(d==null||o.rank===d.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let p={x:_M(i),scale:d,offset:u,mean:o,variance:l},h={varianceEpsilon:s},c=B.runKernel(oi,p,h);return U(c,i.shape)}var cu=V({batchNorm_:LM});function BM(e,t,r,a,n,s){let i=$(e,"x","batchNorm"),o=$(t,"mean","batchNorm"),l=$(r,"variance","batchNorm"),d;n!=null&&(d=$(n,"scale","batchNorm"));let u;return a!=null&&(u=$(a,"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}.`),d!=null&&P(d.rank===2||d.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${d.rank}.`),u!=null&&P(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${u.rank}.`),cu(i,o,l,u,d,s)}var Ww=V({batchNorm2d_:BM});function WM(e,t,r,a,n,s){let i=$(e,"x","batchNorm"),o=$(t,"mean","batchNorm"),l=$(r,"variance","batchNorm"),d;n!=null&&(d=$(n,"scale","batchNorm"));let u;return a!=null&&(u=$(a,"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}.`),d!=null&&P(d.rank===3||d.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${d.rank}.`),u!=null&&P(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${u.rank}.`),cu(i,o,l,u,d,s)}var Vw=V({batchNorm3d_:WM});function VM(e,t,r,a,n,s){let i=$(e,"x","batchNorm"),o=$(t,"mean","batchNorm"),l=$(r,"variance","batchNorm"),d;n!=null&&(d=$(n,"scale","batchNorm"));let u;return a!=null&&(u=$(a,"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}.`),d!=null&&P(d.rank===4||d.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${d.rank}.`),u!=null&&P(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${u.rank}.`),cu(i,o,l,u,d,s)}var Uw=V({batchNorm4d_:VM});function UM(e,t,r){let a=$(e,"x","bincount"),n=$(t,"weights","bincount");P(a.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${a.dtype}`),P(r>=0,()=>`size must be non-negative, but got ${r}.`),P(n.size===a.size||n.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${a.shape}, weights shape: ${n.shape}.`);let s={x:a,weights:n},i={size:r};return B.runKernel(Nf,s,i)}var n2=V({bincount_:UM});function GM(e,t){let r=$(e,"s0","broadcastArgs","int32"),a=$(t,"s1","broadcastArgs","int32");if(r.rank!==1)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${r.rank}`);if(a.rank!==1)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${a.rank}`);let n={s0:r,s1:a};return B.runKernel(Ef,n)}var Gw=V({broadcastArgs_:GM});function jM(e,t){let r=$(e,"broadcastTo","x"),a=r.shape;if(t.some(l=>!(l>0)||l%1!==0))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.length<r.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${r.rank}.`);if(t.length>r.rank){let l=r.shape.slice();for(;l.length<t.length;)l.unshift(1);r=U(r,l)}let n=r.shape,s=Array.from(t);for(let l=t.length-1;l>=0;l--)if(n[l]===t[l])s[l]=1;else if(r.shape[l]!==1)throw new Error(`broadcastTo(): [${a}] cannot be broadcast to [${t}].`);if(s.map((l,d)=>l>1?d:-1).filter(l=>l>=0).length===0)return Pr(r);let i={x:r},o={reps:s};return B.runKernel(Xn,i,o)}var xp=V({broadcastTo_:jM});function HM(e){let t={x:$(e,"x","ceil","float32")};return B.runKernel(Zs,t)}var jw=V({ceil_:HM});function qM(e,t,r){let a=$(e,"x","clipByValue");P(t<=r,()=>`Error in clip: min (${t}) must be less than or equal to max (${r}).`);let n={x:a},s={clipValueMin:t,clipValueMax:r};return B.runKernel(Kn,n,s)}var pa=V({clipByValue_:qM});function KM(e){return kt(e,0)}var Hw=V({concat1d_:KM});function XM(e,t){return kt(e,t)}var ed=V({concat2d_:XM});function ZM(e,t){return kt(e,t)}var qw=V({concat3d_:ZM});function YM(e,t){return kt(e,t)}var Kw=V({concat4d_:YM});function JM(e,t,r,a,n="NHWC",s=[1,1],i){let o=$(e,"x","conv2d","float32"),l=$(t,"filter","conv2d","float32"),d=o,u=!1;o.rank===3&&(u=!0,d=U(o,[1,o.shape[0],o.shape[1],o.shape[2]])),P(d.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${d.rank}.`),P(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),Lr("conv2d",a,i);let p=n==="NHWC"?d.shape[3]:d.shape[1];P(p===l.shape[2],()=>`Error in conv2d: depth of input (${p}) must match input depth for filter ${l.shape[2]}.`),P(Rn(r,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${r} and dilations '${s}'`);let h={x:d,filter:l},c={strides:r,pad:a,dataFormat:n,dilations:s,dimRoundingMode:i},f=B.runKernel(Ys,h,c);return u?U(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Os=V({conv2d_:JM});function QM(e,t,r,a,n="NWC",s=1,i){let o=$(e,"x","conv1d"),l=$(t,"filter","conv1d"),d=o,u=!1;o.rank===2&&(u=!0,d=U(o,[1,o.shape[0],o.shape[1]])),P(d.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${d.rank}.`),P(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),Lr("conv1d",a,i),P(d.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${d.shape[2]}) must match input depth for filter ${l.shape[1]}.`),P(Rn(r,s),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${r} and dilation '${s}'`),P(n==="NWC",()=>`Error in conv1d: got dataFormat of ${n} but only NWC is currently supported.`);let p=U(l,[1,l.shape[0],l.shape[1],l.shape[2]]),h=U(d,[d.shape[0],1,d.shape[1],d.shape[2]]),c=Os(h,p,[1,r],a,"NHWC",[1,s],i);return u?U(c,[c.shape[2],c.shape[3]]):U(c,[c.shape[0],c.shape[2],c.shape[3]])}var s2=V({conv1d_:QM});function e$(e,t,r,a,n,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,d=!1;t.rank===3&&(d=!0,l=U(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(r.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${r.rank}`);let u=s==="NHWC"?o[3]:o[1],p=s==="NHWC"?l.shape[3]:l.shape[1];P(u===r.shape[2],()=>`Error in conv2dDerInput: depth of input (${u}) must match input depth for filter ${r.shape[2]}.`),P(p===r.shape[3],()=>`Error in conv2dDerInput: depth of output (${p}) must match output depth for filter ${r.shape[3]}.`),Lr("conv2dDerInput",n,i);let h={dy:l,filter:r},c={strides:a,pad:n,dataFormat:s,dimRoundingMode:i,inputShape:o},f=B.runKernel(Js,h,c);return d?U(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var i2=V({conv2DBackpropInput_:e$});function t$(e,t,r,a,n,s){let i=$(e,"x","conv2dTranspose"),o=$(t,"filter","conv2dTranspose");return i2(r,i,o,a,n,"NHWC",s)}var o2=V({conv2dTranspose_:t$});function r$(e,t,r,a,n="NDHWC",s=[1,1,1]){let i=$(e,"x","conv3d"),o=$(t,"filter","conv3d"),l=i,d=!1;i.rank===4&&(d=!0,l=U(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(Rn(r,s),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${r} and dilations '${s}'`),P(n==="NDHWC",()=>`Error in conv3d: got dataFormat of ${n} but only NDHWC is currently supported.`);let u={x:l,filter:o},p={strides:r,pad:a,dataFormat:n,dilations:s},h=B.runKernel(Wp,u,p);return d?U(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var l2=V({conv3d_:r$});function a$(e,t,r,a,n){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=U(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],d=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(r.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${r.rank}`),P(l===r.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${r.shape[3]}.`),P(d===r.shape[4],()=>`Error in conv3dDerInput: depth of output (${d}) must match output depth for filter ${r.shape[4]}.`);let u={dy:i,filter:r},p={pad:n,strides:a,inputShape:s},h=B.runKernel(Mf,u,p);return o?U(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var Xw=V({conv3DBackpropInput_:a$});function n$(e,t,r,a,n){let s=$(e,"x","conv3dTranspose"),i=$(t,"filter","conv3dTranspose");return Xw(r,s,i,a,n)}var Zw=V({conv3dTranspose_:n$});function s$(e){let t={x:$(e,"x","cos","float32")};return B.runKernel(Qs,t)}var tm=V({cos_:s$});function i$(e){let t={x:$(e,"x","cosh","float32")};return B.runKernel(ei,t)}var u2=V({cosh_:i$});function o$(e,t=0,r=!1,a=!1){let n={x:$(e,"x","cumsum")},s={axis:t,exclusive:r,reverse:a};return B.runKernel(Po,n,s)}var d2=V({cumsum_:o$});function l$(e,t,r,a=!1){let n=$(e,"x","denseBincount"),s=$(t,"weights","denseBincount");P(n.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${n.dtype}`),P(n.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${n.rank}.`),P(r>=0,()=>`size must be non-negative, but got ${r}.`),P(s.size===n.size||s.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${n.shape}, weights shape: ${s.shape}.`);let i={x:n,weights:s},o={size:r,binaryOutput:a};return B.runKernel($f,i,o)}var Yw=V({denseBincount_:l$});function u$(e,t,r="NHWC"){let a=$(e,"x","depthToSpace","float32"),n=r==="NHWC"?a.shape[1]:a.shape[2],s=r==="NHWC"?a.shape[2]:a.shape[3],i=r==="NHWC"?a.shape[3]:a.shape[1];P(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`),P(n*t>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${n} and ${t} for depthToSpace with input shape
|
|
${a.shape}`),P(s*t>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${s} and ${t} for depthToSpace with input shape
|
|
${a.shape}`),P(i%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${i} for depthToSpace with input shape ${a.shape}`);let o={x:a},l={blockSize:t,dataFormat:r};return B.runKernel(zo,o,l)}var Jw=V({depthToSpace_:u$});function d$(e,t,r,a,n="NHWC",s=[1,1],i){let o=$(e,"x","depthwiseConv2d","float32"),l=$(t,"filter","depthwiseConv2d","float32"),d=o,u=!1;o.rank===3&&(u=!0,d=U(o,[1,o.shape[0],o.shape[1],o.shape[2]])),P(d.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${d.rank}.`),P(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),P(d.shape[3]===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${d.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`),Lr("depthwiseConv2d",a,i);let p={x:d,filter:l},h={strides:r,pad:a,dataFormat:n,dilations:s,dimRoundingMode:i},c=B.runKernel(ti,p,h);return u?U(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var lh=V({depthwiseConv2d_:d$});function p$(e){let t={x:$(e,"x","diag")};return B.runKernel(zf,t)}var h$=V({diag_:p$});function c$(e,t,r,a,n=[1,1],s="NHWC"){let i=$(e,"x","dilation2d"),o=$(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,d=!1;i.rank===3&&(l=U(i,[1,i.shape[0],i.shape[1],i.shape[2]]),d=!0);let u={x:l,filter:o},p={strides:r,pad:a,dilations:n},h=B.runKernel(Vp,u,p);return d?U(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var Qw=V({dilation2d_:c$});function f$(e,t){let r=$(e,"a","equal","string_or_numeric"),a=$(t,"b","equal","string_or_numeric");[r,a]=Dt(r,a),bt(r.shape,a.shape);let n={a:r,b:a};return B.runKernel(Do,n)}var Ca=V({equal_:f$});function m$(e,t,r){let a=$(t,"a","where"),n=$(r,"b","where"),s=$(e,"condition","where","bool"),i=bt(bt(s.shape,a.shape),n.shape),o=xp(s,i),l=xp(a,i),d=xp(n,i),u={condition:o,t:l,e:d};return B.runKernel(sl,u)}var zr=V({where_:m$});function g$(e){let t={x:$(e,"x","zerosLike")};return B.runKernel(ml,t)}var at=V({zerosLike_:g$});function y$(e,t){let r=$(e,"a","div"),a=$(t,"b","div");[r,a]=Dt(r,a);let n=pe(r,a),s=at(n),i=Ca(a,s);return zr(i,s,n)}var ek=V({divNoNan_:y$});function A$(e,t){let r=$(e,"t1","dot"),a=$(t,"t2","dot");P((r.rank===1||r.rank===2)&&(a.rank===1||a.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${r.rank} and ${a.rank}.`);let n=r.rank===1?r.size:r.shape[1],s=a.rank===1?a.size:a.shape[0];if(P(n===s,()=>`Error in dot: inner dimensions of inputs must match, but got ${n} and ${s}.`),r.rank===1&&a.rank===1){let i=U(r,[1,-1]),o=U(a,[-1,1]),l=Ke(i,o);return U(l,[])}else if(r.rank===1&&a.rank===2){let i=U(r,[1,-1]),o=U(a,[a.shape[0],a.shape[1]]),l=Ke(i,o);return U(l,[l.size])}else if(r.rank===2&&a.rank===1){let i=U(a,[-1,1]),o=Ke(r,i);return U(o,[o.size])}else{let i=U(a,[a.shape[0],a.shape[1]]);return Ke(r,i)}}var x$=V({dot_:A$});function b$(e,...t){let r=t.map((n,s)=>$(n,`tensors${s}`,"einsum")),a={equation:e};return B.runKernel(Up,r,a)}var tk=V({einsum_:b$});function v$(e){let t={x:$(e,"x","elu","float32")};return B.runKernel(ai,t)}var uh=V({elu_:v$});function w$(e){let t=$(e,"x","erf");P(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=me(t,"float32"));let r={x:t};return B.runKernel(zu,r)}var rk=V({erf_:w$});function k$(e){let t={x:$(e,"x","exp")};return B.runKernel(ni,t)}var Na=V({exp_:k$});function I$(e,t=0){let r=$(e,"x","expandDims","string_or_numeric");P(t<=r.rank,()=>"Axis must be <= rank of the tensor");let a={input:r},n={dim:t};return B.runKernel(_o,a,n)}var Ht=V({expandDims_:I$});function S$(e){let t={x:$(e,"x","expm1")};return B.runKernel(Lo,t)}var ak=V({expm1_:S$});function T$(e,t){let r=$(e,"x","tile","string_or_numeric");P(r.rank===t.length,()=>`Error in transpose: rank of input ${r.rank} must match length of reps ${t}.`);let a={x:r},n={reps:t};return B.runKernel(Xn,a,n)}var Wa=V({tile_:T$});function C$(e,t,r,a="float32"){t==null&&(t=e);let n=Le([e,t],a),s=e<=t?e:t;for(let o=0;o<s;++o)n.set(1,o,o);let i=U(n.toTensor(),[e,t]);if(r==null)return i;if(r.length===1)return Wa(Ht(i,0),[r[0],1,1]);if(r.length===2)return Wa(Ht(Ht(i,0),0),[r[0],r[1],1,1]);if(r.length===3)return Wa(Ht(Ht(Ht(i,0),0),0),[r[0],r[1],r[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${r.length}D.`)}var p2=V({eye_:C$});function td(e,t,r){let a={shape:e,value:t,dtype:r};return B.runKernel(Du,{},a)}function N$(e){let t={x:$(e,"x","floor","float32")};return B.runKernel(si,t)}var dh=V({floor_:N$});function E$(e,t,r=0,a=0){let n=$(e,"x","gather"),s=$(t,"indices","gather","int32"),i={x:n,indices:s},o={axis:r,batchDims:a};return B.runKernel(Wo,i,o)}var fu=V({gather_:E$});function R$(e,t){let r=$(e,"a","greater","string_or_numeric"),a=$(t,"b","greater","string_or_numeric");[r,a]=Dt(r,a),bt(r.shape,a.shape);let n={a:r,b:a};return B.runKernel(Uo,n)}var fa=V({greater_:R$});function F$(e,t){let r=$(e,"a","greaterEqual","string_or_numeric"),a=$(t,"b","greaterEqual","string_or_numeric");[r,a]=Dt(r,a),bt(r.shape,a.shape);let n={a:r,b:a};return B.runKernel(li,n)}var xl=V({greaterEqual_:F$});function M$(e){let t={input:$(e,"input","imag")};return B.runKernel(Gp,t)}var rm=V({imag_:M$});function $$(e){let t={x:$(e,"x","isFinite")};return B.runKernel(_u,t)}var P$=V({isFinite_:$$});function O$(e){let t={x:$(e,"x","isInf")};return B.runKernel(Lu,t)}var z$=V({isInf_:O$});function D$(e){let t={x:$(e,"x","isNaN")};return B.runKernel(Bu,t)}var nk=V({isNaN_:D$});function _$(e,t=.2){let r={x:$(e,"x","leakyRelu")},a={alpha:t};return B.runKernel(di,r,a)}var am=V({leakyRelu_:_$});function L$(e,t){let r=$(e,"a","less","string_or_numeric"),a=$(t,"b","less","string_or_numeric");[r,a]=Dt(r,a),bt(r.shape,a.shape);let n={a:r,b:a};return B.runKernel(Go,n)}var h2=V({less_:L$});function B$(e,t){let r=$(e,"a","lessEqual","string_or_numeric"),a=$(t,"b","lessEqual","string_or_numeric");[r,a]=Dt(r,a),bt(r.shape,a.shape);let n={a:r,b:a};return B.runKernel(jo,n)}var bl=V({lessEqual_:B$});function sk(e,t,r){if(r<=0)throw new Error("The number of values should be positive.");let a={start:e,stop:t,num:r};return B.runKernel(Bf,{},a)}function W$(e,t=5,r=1,a=1,n=.5){let s=$(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(du(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let i=s,o=!1;s.rank===3&&(o=!0,i=U(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let l={x:i},d={depthRadius:t,bias:r,alpha:a,beta:n},u=B.runKernel(Hp,l,d);return o?U(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var ik=V({localResponseNormalization_:W$});function V$(e){let t={x:$(e,"x","log","float32")};return B.runKernel(pi,t)}var Ea=V({log_:V$});function U$(e){let t={x:$(e,"x","log1p")};return B.runKernel(Wu,t)}var nm=V({log1p_:U$});function G$(e){return P(Es(e),()=>"The f passed in grad(f) must be a function"),(t,r)=>{let a=$(t,"x","tf.grad","string_or_numeric"),n=r!=null?$(r,"dy","tf.grad"):null;return B.tidy(()=>{let{value:s,grads:i}=B.gradients(()=>e(a),[a],n);return n!=null&&_r(s.shape,n.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),sm(i),i[0]})}}function j$(e){return P(Es(e),()=>"The f passed in grads(f) must be a function"),(t,r)=>{P(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let a=Np(t,"args","tf.grads","string_or_numeric"),n=r!=null?$(r,"dy","tf.grads"):null;return B.tidy(()=>{let{value:s,grads:i}=B.gradients(()=>e(...a),a,n);return n!=null&&_r(s.shape,n.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),sm(i),i})}}function H$(e){return P(Es(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,r)=>{P(t instanceof et,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),P(r==null||r instanceof et,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:a,value:n}=B.gradients(()=>e(t),[t],r);return sm(a),{grad:a[0],value:n}}}function q$(e){return P(Es(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,r)=>{P(Array.isArray(t)&&t.every(n=>n instanceof et),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),P(r==null||r instanceof et,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let a=B.gradients(()=>e(...t),t,r);return r!=null&&_r(a.value.shape,r.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),sm(a.grads),a}}function ok(e,t){P(Es(e),()=>"The f passed in variableGrads(f) must be a function"),P(t==null||Array.isArray(t)&&t.every(d=>d instanceof Cp),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let r=t!=null;if(!r){t=[];for(let d in B.registeredVariables)t.push(B.registeredVariables[d])}let a=r?t.filter(d=>!d.trainable):null,n=t.length;t=t.filter(d=>d.trainable),P(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${n} variables is trainable.`);let s=!0,{value:i,grads:o}=B.gradients(e,t,null,s);P(o.some(d=>d!=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((d,u)=>{o[u]!=null&&(l[d.name]=o[u])}),a!=null&&a.forEach(d=>l[d.name]=null),{value:i,grads:l}}function Nn(e){return B.customGrad(e)}function sm(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 K$(e){let t={x:$(e,"x","neg")};return B.runKernel(qo,t)}var zt=V({neg_:K$});function X$(e){let t={x:$(e,"x","softplus")};return B.runKernel(Zu,t)}var rd=V({softplus_:X$});function Z$(e){let t=$(e,"x","logSigmoid");return Nn(r=>({value:zt(rd(zt(r))),gradFunc:a=>L(a,Sr(zt(r)))}))(t)}var Y$=V({logSigmoid_:Z$});function J$(e,t=null,r=!1){let a={x:$(e,"x","max")},n={reductionIndices:t,keepDims:r};return B.runKernel(hi,a,n)}var hr=V({max_:J$});function Q$(e,t){let r=$(e,"a","sub"),a=$(t,"b","sub");[r,a]=Dt(r,a);let n={a:r,b:a};return B.runKernel($i,n)}var he=V({sub_:Q$});function eP(e,t=null,r=!1){let a=$(e,"x","sum");a.dtype==="bool"&&(a=me(a,"int32"));let n={x:a},s={axis:t,keepDims:r};return B.runKernel(Ri,n,s)}var ke=V({sum_:eP});function tP(e,t=-1){let r=$(e,"logits","logSoftmax");if(t===-1&&(t=r.rank-1),t!==r.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${r.rank} and axis was ${t}`);return Nn((a,n)=>{let s=hr(a,t,!0),i=he(a,s),o=he(me(i,"float32"),Ea(ke(Na(i),t,!0)));return n([o]),{value:o,gradFunc:(l,d)=>{let[u]=d,p=!0,h=Na(u);return he(l,L(ke(l,t,p),h))}}})(r)}var c2=V({logSoftmax_:tP});function f2(e,t){for(let r=0;r<e.length;++r)if(e[e.length-r-1]!==t-1-r)return!1;return!0}function lk(e,t,r){let a=e.length+t.length,n=[],s=0,i=0;for(let o=0;o<a;o++)r.indexOf(o)===-1?n.push(e[s++]):n.push(t[i++]);return n}function uk(e,t){let r=[],a=e.length;for(let s=0;s<a;s++)t.indexOf(s)===-1&&r.push(e[s]);let n=t.map(s=>e[s]);return[r,n]}function vo(e,t){let r=t.map(a=>1);return lk(e,r,t)}function rP(e,t,r){P(f2(t,r),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${r} input.`)}function dk(e,t){if(f2(e,t))return null;let r=[];for(let a=0;a<t;++a)e.indexOf(a)===-1&&r.push(a);return e.forEach(a=>r.push(a)),r}function m2(e){return e.map((t,r)=>[r,t]).sort((t,r)=>t[1]-r[1]).map(t=>t[0])}function aP(e,t){let r=[];for(let a=t-e;a<t;++a)r.push(a);return r}function nP(e,t=null,r=!1){let a=$(e,"x","logSumExp"),n=Ua(t,a.shape),s=hr(a,n,!0),i=he(a,s),o=Na(i),l=ke(o,n),d=Ea(l),u=ue(U(s,d.shape),d);if(r){let p=vo(u.shape,n);return U(u,p)}return u}var pk=V({logSumExp_:nP});function sP(e,t){let r=$(e,"a","logicalAnd","bool"),a=$(t,"b","logicalAnd","bool");bt(r.shape,a.shape);let n={a:r,b:a};return B.runKernel(Ho,n)}var ln=V({logicalAnd_:sP});function iP(e){let t={x:$(e,"x","logicalNot","bool")};return B.runKernel(Vu,t)}var im=V({logicalNot_:iP});function oP(e,t){let r=$(e,"a","logicalOr","bool"),a=$(t,"b","logicalOr","bool");bt(r.shape,a.shape);let n={a:r,b:a};return B.runKernel(jp,n)}var g2=V({logicalOr_:oP});function lP(e,t){let r=$(e,"a","logicalXor","bool"),a=$(t,"b","logicalXor","bool");return bt(r.shape,a.shape),ln(g2(e,t),im(ln(e,t)))}var uP=V({logicalXor_:lP});function dP(e,t,r,a,n){let s=$(e,"x","maxPool"),i=1,o=s,l=!1;s.rank===3&&(l=!0,o=U(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(Rn(r,i),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${r} and dilations '${i}'`),Lr("maxPool",a,n);let d={x:o},u={filterSize:t,strides:r,pad:a,dimRoundingMode:n},p=B.runKernel(fi,d,u);return l?U(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var om=V({maxPool_:dP});function pP(e,t=[1,1,1],r,a,n,s="NDHWC"){let i=$(e,"x","maxPool3d"),o=i,l=!1;i.rank===4&&(l=!0,o=U(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}`),Lr("maxPool3d",a,n);let d={x:o},u={filterSize:t,strides:r,pad:a,dimRoundingMode:n,dataFormat:s},p=B.runKernel(qp,d,u);return l?U(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var y2=V({maxPool3d_:pP});function hP(e,t,r,a,n=!1){let s={x:$(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:r,pad:a,includeBatchInIndex:n},o=B.runKernel(Gf,s,i);return{result:o[0],indexes:o[1]}}var hk=V({maxPoolWithArgmax_:hP});function cP(e,t){let r=$(e,"a","maximum"),a=$(t,"b","maximum");[r,a]=Dt(r,a),r.dtype==="bool"&&(r=me(r,"int32"),a=me(a,"int32")),bt(r.shape,a.shape);let n={a:r,b:a};return B.runKernel(ci,n)}var Zn=V({maximum_:cP});function fP(e,t=null,r=!1){let a={x:$(e,"x","mean")},n={axis:t,keepDims:r};return B.runKernel(mi,a,n)}var Wt=V({mean_:fP});function Vt(e,t="float32"){if(t==="complex64"){let a=Vt(e,"float32"),n=Vt(e,"float32");return $s(a,n)}let r=Sf(Tt(e),t);return B.makeTensor(r,e,t)}function da(e,t="float32"){if(t==="complex64"){let a=da(e,"float32"),n=Vt(e,"float32");return $s(a,n)}let r=My(Tt(e),t);return B.makeTensor(r,e,t)}function mP(e,t,{indexing:r="xy"}={}){if(r!=="xy"&&r!=="ij")throw new TypeError(`${r} is not a valid third argument to meshgrid`);if(e===void 0)return[];let a=$(e,"x","meshgrid",e instanceof et?e.dtype:"float32");if(t===void 0)return[a];let n=$(t,"y","meshgrid",t instanceof et?t.dtype:"float32"),s=Tt(a.shape),i=Tt(n.shape);return r==="xy"?(a=U(a,[1,-1]),n=U(n,[-1,1]),[Ke(da([i,1],a.dtype),a),Ke(n,da([1,s],n.dtype))]):(a=U(a,[-1,1]),n=U(n,[1,-1]),[Ke(a,da([1,i],a.dtype)),Ke(da([s,1],n.dtype),n)])}function gP(e,t=null,r=!1){let a={x:$(e,"x","min")},n={axis:t,keepDims:r};return B.runKernel(gi,a,n)}var zs=V({min_:gP});function yP(e,t){let r=$(e,"a","minimum"),a=$(t,"b","minimum");[r,a]=Dt(r,a),r.dtype==="bool"&&(r=me(r,"int32"),a=me(a,"int32")),bt(r.shape,a.shape);let n={a:r,b:a};return B.runKernel(yi,n)}var ph=V({minimum_:yP});function AP(e,t,r){P(r==="reflect"||r==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${r}.`);let a=$(e,"x","mirrorPad");if(a.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");P(t.length===a.rank,()=>`Padding doesn't match input. Must be ${a.rank}. Got ${t.length}.`);let n=r==="reflect"?1:0;for(let o=0;o<a.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]<=a.shape[o]-n&&t[o][1]>=0&&t[o][1]<=a.shape[o]-n,()=>`Padding in dimension ${o} cannot be greater than or equal to ${a.shape[o]-n} or less than 0 for input of shape ${a.shape}`);let s={paddings:t,mode:r},i={x:a};return B.runKernel(Ai,i,s)}var ck=V({mirrorPad_:AP});function xP(e,t){let r=$(e,"a","mod"),a=$(t,"b","mod");[r,a]=Dt(r,a);let n={a:r,b:a};return B.runKernel(Uu,n)}var ad=V({mod_:xP});function bP(e){let t=$(e,"x","square"),r={};return B.runKernel("Square",{x:t},r)}var At=V({square_:bP});function vP(e,t=null,r=!1){e=$(e,"x","moments");let a=Ua(t,e.shape),n=Wt(e,a,r),s=n.shape;r||(s=vo(n.shape,a));let i=At(he(me(e,"float32"),U(n,s))),o=Wt(i,a,r);return{mean:n,variance:o}}var lm=V({moments_:vP});function wP(e,t,r,a){let n=$(t,"data","multiRNNCell"),s=Np(r,"c","multiRNNCell"),i=Np(a,"h","multiRNNCell"),o=n,l=[];for(let p=0;p<e.length;p++){let h=e[p](o,s[p],i[p]);l.push(h[0]),l.push(h[1]),o=h[1]}let d=[],u=[];for(let p=0;p<l.length;p+=2)d.push(l[p]),u.push(l[p+1]);return[d,u]}var kP=V({multiRNNCell_:wP});function IP(e,t,r,a=!1){let n=$(e,"logits","multinomial"),s=n.size,i=n.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}`);r=r||Math.random();let o={logits:i===1?U(n,[1,-1]):n},l={numSamples:t,seed:r,normalized:a},d=B.runKernel(jf,o,l);return i===1?U(d,[d.size]):d}var fk=V({multinomial_:IP});function SP(e,t){let r=$(e,"a","notEqual","string_or_numeric"),a=$(t,"b","notEqual","string_or_numeric");[r,a]=Dt(r,a),bt(r.shape,a.shape);let n={a:r,b:a};return B.runKernel(Ko,n)}var mu=V({notEqual_:SP});function TP(e){let t={x:$(e,"x","onesLike")};return B.runKernel(Yo,t)}var Ra=V({onesLike_:TP});function CP(e,t){let r=$(e,"v1","outerProduct"),a=$(t,"v2","outerProduct");P(r.rank===1&&a.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${r.rank} and ${a.rank}.`);let n=U(r,[-1,1]),s=U(a,[1,-1]);return Ke(n,s)}var NP=V({outerProduct_:CP});function EP(e,t,r=0){let a=$(e,"x","pad");if(a.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");let n={paddings:t,constantValue:r},s={x:a};return B.runKernel(bi,s,n)}var ja=V({pad_:EP});function RP(e,t,r=0){return P(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),ja(e,[t],r)}var FP=V({pad1d_:RP});function MP(e,t,r=0){return P(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),ja(e,t,r)}var $P=V({pad2d_:MP});function PP(e,t,r=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."),ja(e,t,r)}var OP=V({pad3d_:PP});function zP(e,t,r=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."),ja(e,t,r)}var DP=V({pad4d_:zP});function _P(e,t,r){let a=$(e,"x","spaceToBatchND");P(a.rank>=1+t.length,()=>`input rank ${a.rank} should be > than [blockShape] ${t.length}`),P(r.length===t.length,()=>`paddings.shape[0] ${r.length} must be equal to [blockShape] ${t.length}`),P(a.shape.reduce((i,o,l)=>l>0&&l<=t.length?i&&(o+r[l-1][0]+r[l-1][1])%t[l-1]===0:i,!0),()=>`input spatial dimensions ${a.shape.slice(1)} with paddings ${r.toString()} must be divisible by blockShapes ${t.toString()}`);let n={x:a},s={blockShape:t,paddings:r};return B.runKernel(ll,n,s)}var um=V({spaceToBatchND_:_P});function LP(e,t,r,a,n,s,i){n==null&&(n=[1,1]),s==null&&(s=1),a===0&&(a="valid");let o=$(e,"x","maxPool"),l=o,d=!1;o.rank===3&&(d=!0,l=U(o,[1,o.shape[0],o.shape[1],o.shape[2]])),P(Rn(s,n),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${n}'`);let u=_w(l.shape,t,s,n,a),p=[u.dilationHeight,u.dilationWidth],h;a==="same"?h=WP([u.filterHeight,u.filterWidth],p):h=[[0,0],[0,0]];let c=p[0]===1&&p[1]===1,[f,m]=BP([u.inHeight,u.inWidth],p,h),g=c?a:"valid",y=c?l:um(l,p,f),A=(r==="avg"?()=>Qf(y,t,s,g,i):()=>om(y,t,s,g,i))(),x=c?A:em(A,p,m);return d?U(x,[x.shape[1],x.shape[2],x.shape[3]]):x}function BP(e,t,r){let a=r.map(u=>u[0]),n=r.map(u=>u[1]),s=e.concat(a,n),i=t.map((u,p)=>(u-s[p]%u)%u),o=n.map((u,p)=>u+i[p]),l=t.map((u,p)=>[a[p],o[p]]),d=t.map((u,p)=>[0,i[p]]);return[l,d]}function WP(e,t){let r=e.map((s,i)=>s+(s-1)*(t[i]-1)).map(s=>s-1),a=r.map(s=>Math.floor(s/2)),n=r.map((s,i)=>s-a[i]);return r.map((s,i)=>[a[i],n[i]])}var VP=V({pool_:LP});function UP(e,t){let r=$(e,"base","pow"),a=$(t,"exp","pow");[r,a]=Dt(r,a);let n={a:r,b:a};return B.runKernel(vi,n)}var Ds=V({pow_:UP});function GP(e,t){let r=$(e,"x","prelu"),a=$(t,"alpha","prelu"),n={x:r,alpha:a};return B.runKernel(wi,n)}var dm=V({prelu_:GP});function jP(e,t=null,r=!1){let a=$(e,"x","prod");a.dtype==="bool"&&(a=me(a,"int32"));let n={x:a},s={axis:t,keepDims:r};return B.runKernel(el,n,s)}var A2=V({prod_:jP});function HP(e,t,r){let a=Tt(e),n=null;if(r==null||r==="float32")n=new Float32Array(a);else if(r==="int32")n=new Int32Array(a);else if(r==="bool")n=new Uint8Array(a);else throw new Error(`Unknown data type ${r}`);for(let s=0;s<a;s++)n[s]=t();return B.makeTensor(n,e,r)}var qP=V({rand_:HP}),x2=Eo(kf()),b2=class{constructor(e,t,r,a,n){this.mean=e,this.stdDev=t,this.dtype=r,this.nextVal=NaN,this.truncated=a,this.truncated&&(this.upper=this.mean+this.stdDev*2,this.lower=this.mean-this.stdDev*2);let s=n||Math.random();this.random=x2.alea(s.toString())}nextValue(){if(!isNaN(this.nextVal)){let a=this.nextVal;return this.nextVal=NaN,a}let e,t,r=!1;for(;!r;){let a,n,s;do a=2*this.random()-1,n=2*this.random()-1,s=a*a+n*n;while(s>=1||s===0);let i=Math.sqrt(-2*Math.log(s)/s);e=this.mean+this.stdDev*a*i,t=this.mean+this.stdDev*n*i,(!this.truncated||this.isValidTruncated(e))&&(r=!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}},KP=class{constructor(e,t,r,a){this.alpha=e,this.beta=1/t,this.dtype=r;let n=a||Math.random();this.randu=x2.alea(n.toString()),this.randn=new b2(0,1,r,!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,r,a,n,s;for(;;){do a=this.randn.nextValue(),s=1+this.c*a;while(s<=0);if(s*=s*s,e=a*a,t=1-.331*e*e,r=.5*e+this.d*(1-s+Math.log(s)),n=this.randu(),n<t||Math.log(n)<r)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)}},XP=class{constructor(e=0,t=1,r,a){if(this.canReturnFloat=()=>this.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=r,a==null&&(a=Math.random()),typeof a=="number"&&(a=a.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=x2.alea(a)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function ZP(e,t,r=1,a="float32",n){if(r==null&&(r=1),a==null&&(a="float32"),a!=="float32"&&a!=="int32")throw new Error(`Unsupported data type ${a}`);let s=new KP(t,r,a,n),i=Le(e,a);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var YP=V({randomGamma_:ZP});function JP(e,t=0,r=1,a,n){if(a!=null&&a==="bool")throw new Error(`Unsupported data type ${a}`);let s=new b2(t,r,a,!1,n),i=Le(e,a);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var mk=V({randomNormal_:JP});function QP(e,t=0,r=1,a="float32",n){let s=Le(e,a),i=new XP(t,r,null,n);for(let o=0;o<s.values.length;o++)s.values[o]=i.nextValue();return s.toTensor()}var nd=V({randomUniform_:QP});function gu(e,t,r=1,a="float32"){if(r===0)throw new Error("Cannot have a step of zero");let n={start:e,stop:t,step:r,dtype:a};return B.runKernel(ju,{},n)}function eO(e){let t={input:$(e,"input","real")};return B.runKernel(Kp,t)}var Rp=V({real_:eO});function tO(e){let t={x:$(e,"x","reciprocal")};return B.runKernel(Hu,t)}var gk=V({reciprocal_:tO});function rO(e){let t={x:$(e,"x","relu")};return B.runKernel(ki,t)}var Fn=V({relu_:rO});function aO(e){let t={x:$(e,"x","relu6")};return B.runKernel(Si,t)}var v2=V({relu6_:aO});function nO(e,t){let r={x:$(e,"x","reverse")},a={dims:t};return B.runKernel(rl,r,a)}var Fa=V({reverse_:nO});function sO(e){let t=$(e,"x","reverse");return P(t.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),Fa(t,0)}var iO=V({reverse1d_:sO});function oO(e,t){let r=$(e,"x","reverse");return P(r.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${r.rank}.`),Fa(r,t)}var lO=V({reverse2d_:oO});function uO(e,t){let r=$(e,"x","reverse");return P(r.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${r.rank}.`),Fa(r,t)}var dO=V({reverse3d_:uO});function pO(e,t){let r=$(e,"x","reverse");return P(r.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${r.rank}.`),Fa(r,t)}var hO=V({reverse4d_:pO});function cO(e){let t={x:$(e,"x","round")};return B.runKernel(al,t)}var w2=V({round_:cO});function fO(e){let t={x:$(e,"x","rsqrt","float32")};return B.runKernel(Ti,t)}var k2=V({rsqrt_:fO});function Se(e,t){if((wr(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"&&wr(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Di(e,[],[],t)}function mO(e){let t={x:$(e,"x","selu")};return B.runKernel(Ku,t)}var I2=V({selu_:mO});function gO(e,t,r,a,n,s=[1,1],i="NHWC"){let o=$(e,"x","separableConv2d"),l=$(t,"depthwiseFilter","separableConv2d"),d=$(r,"pointwiseFilter","separableConv2d"),u=o,p=!1;if(o.rank===3&&(p=!0,u=U(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(u.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${u.rank}.`),P(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),P(d.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),P(d.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${d.shape[0]}.`),P(d.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${d.shape[1]}.`);let h=l.shape[2],c=l.shape[3];P(d.shape[2]===h*c,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${h*c}, but got ${d.shape[2]}.`);let f=lh(u,l,a,n,i,s),m=Os(f,d,1,"valid",i);return p?U(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var yk=V({separableConv2d_:gO});async function yO(e,t){let r=$(e,"x","setdiff1d"),a=$(t,"y","setdiff1d");P(r.dtype===a.dtype,()=>`x and y should have the same dtype, but got x (${r.dtype}) and y (${a.dtype}).`),P(r.rank===1,()=>`x should be 1D tensor, but got x (${r.shape}).`),P(a.rank===1,()=>`y should be 1D tensor, but got y (${a.shape}).`);let n=await r.data(),s=await a.data(),i=new Set(s),o=0;for(let u=0;u<n.length;u++)i.has(n[u])||o++;let l=new tr([o],r.dtype),d=new tr([o],"int32");for(let u=0,p=0;u<n.length;u++)i.has(n[u])||(l.values[p]=n[u],d.values[p]=u,p++);return[l.toTensor(),d.toTensor()]}var Ak=yO;function AO(e){let t={x:$(e,"x","sign")};return B.runKernel(Xu,t)}var xk=V({sign_:AO});function xO(e){let t={x:$(e,"x","sin","float32")};return B.runKernel(Ci,t)}var S2=V({sin_:xO});function bO(e){let t={x:$(e,"x","sinh")};return B.runKernel(ol,t)}var T2=V({sinh_:bO});function vO(e,t,r){let a=$(e,"x","slice1d");return P(a.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${a.rank} tensor`),Oe(a,[t],[r])}var pm=V({slice1d_:vO});function wO(e,t,r){let a=$(e,"x","slice2d");return P(a.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${a.rank} tensor`),Oe(a,t,r)}var C2=V({slice2d_:wO});function kO(e,t,r){let a=$(e,"x","slice3d");return P(a.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${a.rank} tensor`),Oe(a,t,r)}var vl=V({slice3d_:kO});function IO(e,t,r){let a=$(e,"x","slice4d");return P(a.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${a.rank} tensor`),Oe(a,t,r)}var wo=V({slice4d_:IO});function SO(e,t=-1){let r=$(e,"logits","softmax","float32");if(t===-1&&(t=r.rank-1),t!==r.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${r.rank} and dim was ${t}`);let a={logits:r},n={dim:t};return B.runKernel(Fi,a,n)}var sd=V({softmax_:SO});function TO(e){P(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);let t={input:e};return B.runKernel(_f,t)}var hm=V({fft_:TO});function CO(e){P(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);let t={input:e};return B.runKernel(Lf,t)}var Fp=V({ifft_:CO});function NO(e){let t=e.shape[e.shape.length-1],r=e.size/t,a;if(t<=2){let n=U(e,[r,t]);a=Fp(n)}else{let n=[r,2*(t-1)],s=U(Rp(e),[r,t]),i=U(rm(e),[r,t]),o=Fa(Oe(s,[0,1],[r,t-2]),1),l=L(Fa(Oe(i,[0,1],[r,t-2]),1),Se(-1)),d=kt([s,o],1),u=kt([i,l],1),p=U($s(d,u),[n[0],n[1]]);a=Fp(p)}if(a=Rp(a),e.rank===3&&e.shape[0]!==0){let n=a,s=e.shape[0];a=U(a,[s,a.shape[0]/s,a.shape[1]]),n.dispose()}return a}var N2=V({irfft_:NO});function EO(e,t,r=0){let a={x:$(e,"x","split")},n={numOrSizeSplits:t,axis:r};return B.runKernel(ul,a,n)}var Kt=V({split_:EO});function RO(e,t){P(e.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let r=e.shape[e.shape.length-1],a=e.size/r,n;if(t!=null&&t<r){let f=e.shape.map(g=>0),m=e.shape.map(g=>g);m[e.shape.length-1]=t,n=Oe(e,f,m),r=t}else if(t!=null&&t>r){let f=e.shape.map(m=>m);f[e.shape.length-1]=t-r,n=kt([e,Vt(f)],e.shape.length-1),r=t}else n=e;let s=at(n),i=U($s(n,s),[a,r]),o=hm(i),l=Math.floor(r/2)+1,d=Rp(o),u=rm(o),p=Kt(d,[l,r-l],d.shape.length-1),h=Kt(u,[l,r-l],u.shape.length-1),c=n.shape.slice();return c[n.shape.length-1]=l,U($s(p[0],h[0]),c)}var cm=V({rfft_:RO});function FO(e){let t={x:$(e,"x","sqrt","float32")};return B.runKernel(Ei,t)}var Tr=V({sqrt_:FO});function MO(e,t){let r=$(e,"a","squaredDifference"),a=$(t,"b","squaredDifference");[r,a]=Dt(r,a),bt(r.shape,a.shape);let n={a:r,b:a},s={};return B.runKernel(Mi,n,s)}var E2=V({squaredDifference_:MO});function $O(e,t){let r=$(e,"x","squeeze");return U(r,Iv(r.shape,t).newShape)}var Ye=V({squeeze_:$O});function PO(e,t=0){let r=Np(e,"tensors","stack","string_or_numeric");P(r.length>=1,()=>"Pass at least one tensor to tf.stack"),r.length>0&&P(t<=r[0].rank,()=>"Axis must be <= rank of the tensor");let a=r,n={axis:t};return B.runKernel(Qo,a,n)}var nr=V({stack_:PO});function OO(e,t=0){let r={x:$(e,"x","step")},a={alpha:t};return B.runKernel(zi,r,a)}var hh=V({step_:OO});function zO(e,t,r,a,n=0,s=0,i=0,o=0,l=0){let d={x:$(e,"x","stridedSlice","string_or_numeric")},u={begin:t,end:r,strides:a,beginMask:n,endMask:s,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};return B.runKernel(dl,d,u)}var bk=V({stridedSlice_:zO});function DO(e){let t={x:$(e,"x","tan","float32")};return B.runKernel(pl,t)}var vk=V({tan_:DO});function St(e,t){Ro(e);let r=Cn(e,t);if(r.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Di(e,null,r,t)}function an(e,t,r){if(Ro(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let a=Cn(e,r);if(a.length!==2&&a.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Di(e,t,a,r)}function _O(e,t,r){if(Ro(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let a=Cn(e,r);if(a.length!==4&&a.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Di(e,t,a,r)}function LO(e,t,r){if(Ro(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let a=Cn(e,r);if(a.length!==5&&a.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Di(e,t,a,r)}function BO(e,t,r){if(Ro(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let a=Cn(e,r);if(a.length!==6&&a.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||a,Di(e,t,a,r)}function WO(e,t=1,r=!0){let a=$(e,"x","topk");if(a.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let n=a.shape[a.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>n)throw new Error(`'k' passed to topk() must be <= the last dimension (${n}) but got ${t}`);let s={x:a},i={k:t,sorted:r},[o,l]=B.runKernel(hl,s,i);return{values:o,indices:l}}var wk=V({topk_:WO});function VO(e,t=0,r=1,a,n){if(a!=null&&a==="bool")throw new Error("Unsupported data type $ { dtype }");let s=new b2(t,r,a,!0,n),i=Le(e,a);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var fm=V({truncatedNormal_:VO});function UO(e,t=0){let r=$(e,"x","unique","string_or_numeric");P(r.rank>0,()=>"The input tensor must be at least 1D");let a={x:r},n={axis:t},[s,i]=B.runKernel(Zf,a,n);return{values:s,indices:i}}var j1=V({unique_:UO});function GO(e,t,r){let a=$(e,"x","unsortedSegmentSum"),n=$(t,"segmentIds","unsortedSegmentSum","int32");P(du(r),()=>"numSegments must be of dtype int");let s={x:a,segmentIds:n},i={numSegments:r};return B.runKernel(eh,s,i)}var kk=V({unsortedSegmentSum_:GO});function jO(e,t=0){let r=$(e,"x","unstack","string_or_numeric");P(t>=-r.shape.length&&t<r.shape.length,()=>`Axis = ${t} is not in [-${r.shape.length}, ${r.shape.length})`);let a={value:r},n={axis:t};return B.runKernel(fl,a,n)}var ra=V({unstack_:jO});function Ik(e,t=!0,r,a){return B.makeVariable(e,t,r,a)}function Sk(e,t){let r=[];for(let s=0;s<t.length;s++)t[s]&&r.push(s);let a=Le(e,"int32"),n=Le([r.length,e.length],"int32");for(let s=0;s<r.length;s++){let i=a.indexToLoc(r[s]),o=s*e.length;n.values.set(i,o)}return n.toTensor()}async function HO(e){let t=$(e,"condition","whereAsync","bool"),r=await t.data(),a=Sk(t.shape,r);return e!==t&&t.dispose(),a}var R2=HO;async function qO(e,t,r){let a=$(e,"tensor","boolMask"),n=$(t,"mask","boolMask","bool"),s=r==null?0:r,i=n.rank,o=a.shape;P(i>0,()=>"mask cannot be scalar"),_r(o.slice(s,s+i),n.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let m=s;m<s+i;m++)l*=o[m];let d=o.slice(0,s).concat([l],o.slice(s+i)),u=U(a,d),p=U(n,[-1]),h=await R2(p),c=Ye(h,[1]),f=fu(u,c,s);return e!==a&&a.dispose(),t!==n&&n.dispose(),c.dispose(),u.dispose(),p.dispose(),h.dispose(),f}var KO=qO;function XO(e,t="euclidean",r=null,a=!1){e=$(e,"x","norm");let n=Tk(e,t,r),s=n.shape;if(a){let i=Ua(r,e.shape);s=vo(n.shape,i)}return U(n,s)}function Tk(e,t,r=null){if(e.rank===0)return Qt(e);if(e.rank!==1&&r===null)return Tk(U(e,[-1]),t,r);if(e.rank===1||typeof r=="number"||Array.isArray(r)&&r.length===1){if(t===1)return ke(Qt(e),r);if(t===1/0)return hr(Qt(e),r);if(t===-1/0)return zs(Qt(e),r);if(t==="euclidean"||t===2)return Tr(ke(Ds(Qt(e),Se(2,"int32")),r));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(r)&&r.length===2){if(t===1)return hr(ke(Qt(e),r[0]),r[1]-1);if(t===1/0)return hr(ke(Qt(e),r[1]),r[0]);if(t===-1/0)return zs(ke(Qt(e),r[1]),r[0]);if(t==="fro"||t==="euclidean")return Tr(ke(At(e),r));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${r}`)}var F2=V({norm_:XO});function ZO(e,t,r,a,n=!0){let s=$(e,"v","movingAverage"),i=$(t,"x","movingAverage"),o=$(r,"decay","movingAverage");Hv(s,i),P(Gs(s.shape,i.shape),()=>"Shape mismatch in v and x");let l=Se(1),d=he(l,o),u=L(he(i,s),d);if(n){P(a!=null,()=>"When using zeroDebias: true, step is required.");let p=$(a,"step","movingAverage");u=pe(u,he(l,Ds(o,p)))}return ue(s,u)}var YO=V({movingAverage_:ZO});function JO(e,t,r){let a=$(e,"indices","scatterND","int32"),n=$(t,"updates","scatterND");qy(n,a,r);let s={indices:a,updates:n},i={shape:r};return B.runKernel(nl,s,i)}var Ck=V({scatterND_:JO});function QO(e,t,r,a){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 n=e.rank>0?e.shape[0]:1,s=e.rank>1?e.shape[1]:1;if(r.length!==s)throw new Error(`outputShape has incorrect number of elements:, ${r.length}, should be: ${s}.`);let i=t.size;if(!(t.rank===0||t.rank===1&&i===n))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${n}]`);if(t.dtype!==a.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function ez(e,t,r,a=0){let n=$(e,"sparseIndices","sparseToDense","int32"),s=$(t,"sparseValues","sparseToDense"),i=$(a,"defaultValue","sparseToDense",s.dtype);QO(n,s,r,i);let o={sparseIndices:n,sparseValues:s,defaultValue:i},l={outputShape:r};return B.runKernel(Jp,o,l)}var M2=V({sparseToDense_:ez});function tz(e,t){let r=$(t,"indices","gatherND","int32"),a={params:$(e,"x","gatherND","string_or_numeric"),indices:r};return B.runKernel(Vo,a)}var Nk=V({gatherND_:tz});function rz(e,t){if(t==null)return e.shape.slice();if(Gs(e.shape,t))return t;if(e.shape.length===t.length){let r=[];for(let a=0;a<e.shape.length;a++)t[a]==null&&e.shape[a]!=null?r.push(e.shape[a]):r.push(t[a]);return r}return t}function az(e,t,r,a){let n=$(e,"x","dropout");if(P(n.dtype==="float32",()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${n.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 et?n.clone():n;let s=rz(n,r),i=1-t,o=pe(dh(ue(nd(s,0,1,"float32",a),i)),i);return L(n,o)}var Ek=V({dropout_:az});function Rk(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function $2(e,t,r){let a=1-e%2,n=new Float32Array(e);for(let s=0;s<e;++s){let i=2*Math.PI*s/(e+a-1);n[s]=t-r*Math.cos(i)}return St(n,"float32")}async function nz(e,t,r=1){let a=$(e,"predictions","inTopK"),n=$(t,"targets","inTopK");P(a.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${a.rank}`),P(a.rank-1===n.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${a.rank} and targets rank ${n.rank}`),_r(a.shape.slice(0,a.shape.length-1),n.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");let s=a.shape[a.shape.length-1];P(r>0&&r<=s,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${s}), but got ${r}`);let i=await a.data(),o=await n.data(),[l,d]=[i.length/s,s],u=Sv("bool",l);for(let p=0;p<l;p++){let h=p*d,c=i.subarray(h,h+d),f=[];for(let m=0;m<c.length;m++)f.push({value:c[m],index:m});f.sort((m,g)=>g.value-m.value),u[p]=0;for(let m=0;m<r;m++)if(f[m].index===o[p]){u[p]=1;break}}return e!==a&&a.dispose(),t!==n&&n.dispose(),pt(u,n.shape,"bool")}var sz=nz,_s={};De(_s,{conv2d:()=>lz,depthwiseConv2d:()=>hz,matMul:()=>fz});function iz(e,t,r,a,n,s="NHWC",i){let o=e;e.rank===3&&(o=U(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=U(t,[1,t.shape[0],t.shape[1],t.shape[2]])),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(r.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${r}.`);let d=s==="NHWC"?o.shape[3]:o.shape[1],u=s==="NHWC"?l.shape[3]:l.shape[1];P(d===r[2],()=>`Error in conv2dDerFilter: depth of input ${d}) must match input depth in filter (${r[2]}.`),P(u===r[3],()=>`Error in conv2dDerFilter: depth of dy (${u}) must match output depth for filter (${r[3]}).`),Lr("conv2dDerFilter",n,i);let p={x:o,dy:l},h={strides:a,pad:n,dataFormat:s,dimRoundingMode:i,filterShape:r};return B.runKernel(Rf,p,h)}var P2=V({conv2DBackpropFilter_:iz});function mm(e,t,r){if(r==null||r==="linear")return e;if(r==="relu")return L(e,hh(t));throw new Error(`Cannot compute gradient for fused activation ${r}.`)}function gm(e,t){let r=t,a=Xt(e.shape,t.shape);return a.length>0&&(r=ke(r,a)),U(r,e.shape)}function ym(e,t,r,a){if(t==="linear")return e;if(t==="relu")return Fn(e);if(t==="elu")return uh(e);if(t==="relu6")return v2(e);if(t==="prelu")return dm(e,r);if(t==="leakyrelu")return am(e,a);if(t==="sigmoid")return Sr(e);throw new Error(`Unknown fused activation ${t}.`)}var Am=(e,t)=>!(e>0)||t==="linear";function oz({x:e,filter:t,strides:r,pad:a,dataFormat:n="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:d,leakyreluAlpha:u}){if(l=l||"linear",Am(B.state.gradientDepth,l)===!1){let v=Os(e,t,r,a,n,s,i);return o!=null&&(v=ue(v,o)),ym(v,l,d,u)}let p=$(e,"x","conv2d","float32"),h=$(t,"filter","conv2d","float32"),c=p,f=!1;p.rank===3&&(f=!0,c=U(p,[1,p.shape[0],p.shape[1],p.shape[2]])),P(c.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${c.rank}.`),P(h.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${h.rank}.`),Lr("fused conv2d",a,i),P(c.shape[3]===h.shape[2],()=>`Error in conv2d: depth of input (${c.shape[3]}) must match input depth for filter ${h.shape[2]}.`),P(Rn(r,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${r} and dilations '${s}'`),P(n==="NHWC",()=>`Error in conv2d: got dataFormat of ${n} but only NHWC is currently supported.`);let m=oh(c.shape,h.shape,r,s,a,i),g;o!=null&&(g=$(o,"bias","fused conv2d"),[g]=Dt(g,p),bt(m.outShape,g.shape));let y;d!=null&&(y=$(d,"prelu weights","fused conv2d"));let A=(v,C)=>{let[T,E,R,z]=C,M=mm(v,R,l);P(Ps(s),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let I=i2(E.shape,M,T,r,a),D=P2(E,M,T.shape,r,a),O=[I,D];if(z!=null){let j=gm(z,M);O.push(j)}return O},x={x:c,filter:h,bias:g,preluActivationWeights:y},b={strides:r,pad:a,dataFormat:n,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:u};return o==null?Nn((v,C,T)=>{let E=B.runKernel(Fs,x,b);return T([C,v,E]),f&&(E=U(E,[E.shape[1],E.shape[2],E.shape[3]])),{value:E,gradFunc:A}})(c,h):Nn((v,C,T,E)=>{let R=B.runKernel(Fs,x,b);return E([C,v,R,T]),f&&(R=U(R,[R.shape[1],R.shape[2],R.shape[3]])),{value:R,gradFunc:A}})(c,h,g)}var lz=V({fusedConv2d_:oz});function uz(e,t,r,a,n,s=[1,1],i){let o=e;e.rank===3&&(o=U(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=U(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let d={x:o,dy:l},u={strides:a,pad:n,dimRoundingMode:i,dilations:s,filterShape:r};return B.runKernel(Pf,d,u)}var Fk=V({depthwiseConv2dNativeBackpropFilter_:uz});function dz(e,t,r,a,n,s=[1,1],i){let o=t,l=!1;t.rank===3&&(l=!0,o=U(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let d={dy:o,filter:r},u={strides:a,pad:n,dimRoundingMode:i,dilations:s,inputShape:e},p=B.runKernel(Of,d,u);return l?U(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var Mk=V({depthwiseConv2dNativeBackpropInput_:dz});function pz({x:e,filter:t,strides:r,pad:a,dataFormat:n="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:d,leakyreluAlpha:u}){if(Am(B.state.gradientDepth,l)===!1){let v=lh(e,t,r,a,n,s,i);return o!=null&&(v=ue(v,o)),ym(v,l,d,u)}let p=$(e,"x","depthwiseConv2d","float32"),h=$(t,"filter","depthwiseConv2d","float32"),c=p,f=!1;p.rank===3&&(f=!0,c=U(p,[1,p.shape[0],p.shape[1],p.shape[2]])),P(c.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`),P(h.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${h.rank}.`),P(c.shape[3]===h.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${c.shape[3]}) must match the inChannels dimension in filter ${h.shape[2]}.`),s==null&&(s=[1,1]),P(Rn(r,s),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${r} and dilations '${s}'`),Lr("fused depthwiseConv2d",a,i);let m=oh(c.shape,h.shape,r,s,a,i,!0),g;o!=null&&(g=$(o,"bias","fused conv2d"),[g]=Dt(g,p),bt(m.outShape,g.shape));let y;d!=null&&(y=$(d,"prelu weights","fused depthwiseConv2d"));let A=(v,C)=>{P(Ps(s),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);let[T,E,R,z]=C,M=mm(v,R,l),I=Mk(E.shape,M,T,r,a,s,i),D=Fk(E,M,T.shape,r,a,s,i);if(z!=null){let O=gm(g,M);return[I,D,O]}return[I,D]},x={x:c,filter:h,bias:g,preluActivationWeights:y},b={strides:r,pad:a,dataFormat:n,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:u};return o==null?Nn((v,C,T)=>{let E=B.runKernel(Ms,x,b);return T([C,v,E]),f&&(E=U(E,[E.shape[1],E.shape[2],E.shape[3]])),{value:E,gradFunc:A}})(c,h):Nn((v,C,T,E)=>{let R=B.runKernel(Ms,x,b);return E([C,v,R,T]),f&&(R=U(R,[R.shape[1],R.shape[2],R.shape[3]])),{value:R,gradFunc:A}})(c,h,g)}var hz=V({fusedDepthwiseConv2d_:pz});function cz({a:e,b:t,transposeA:r=!1,transposeB:a=!1,bias:n,activation:s="linear",preluActivationWeights:i,leakyreluAlpha:o}){if(Am(B.state.gradientDepth,s)===!1){let z=Ke(e,t,r,a);return n!=null&&(z=ue(z,n)),ym(z,s,i,o)}let l=$(e,"a","fused matMul"),d=$(t,"b","fused matMul");[l,d]=Dt(l,d);let u=r?l.shape[l.rank-2]:l.shape[l.rank-1],p=a?d.shape[d.rank-1]:d.shape[d.rank-2],h=r?l.shape[l.rank-1]:l.shape[l.rank-2],c=a?d.shape[d.rank-2]:d.shape[d.rank-1],f=l.shape.slice(0,-2),m=d.shape.slice(0,-2),g=Tt(f),y=Tt(m);P(u===p,()=>`Error in fused matMul: inner shapes (${u}) and (${p}) of Tensors with shapes ${l.shape} and ${d.shape} and transposeA=${r} and transposeB=${a} must match.`);let A=bt(l.shape.slice(0,-2),d.shape.slice(0,-2)).concat([h,c]),x=r?U(l,[g,u,h]):U(l,[g,h,u]),b=a?U(d,[y,c,p]):U(d,[y,p,c]),v;n!=null&&(v=$(n,"bias","fused matMul"),[v]=Dt(v,l),bt(A,v.shape));let C;i!=null&&(C=$(i,"prelu weights","fused matMul"));let T=(z,M)=>{let[I,D,O,j]=M,X=mm(U(z,O.shape),O,s),_,K;if(!r&&!a?(_=Ke(X,D,!1,!0),K=Ke(I,X,!0,!1)):!r&&a?(_=Ke(X,D,!1,!1),K=Ke(X,I,!0,!1)):r&&!a?(_=Ke(D,X,!1,!0),K=Ke(I,X,!1,!1)):(_=Ke(D,X,!0,!0),K=Ke(X,I,!0,!0)),n!=null){let W=gm(j,X);return[_,K,W]}else return[_,K]},E={a:x,b,bias:v,preluActivationWeights:C},R={transposeA:r,transposeB:a,activation:s,leakyreluAlpha:o};return n==null?Nn((z,M,I)=>{let D=B.runKernel(Rs,E,R);return I([z,M,D]),{value:U(D,A),gradFunc:T}})(x,b):Nn((z,M,I,D)=>{let O=B.runKernel(Rs,E,R);return D([z,M,O,I]),{value:U(O,A),gradFunc:T}})(x,b,v)}var fz=V({fusedMatMul_:cz});function mz(e){return $2(e,.54,.46)}var gz=V({hammingWindow_:mz});function yz(e){return $2(e,.5,.5)}var $k=V({hannWindow_:yz});function Az(e,t,r,a=!1,n=0){let s=0,i=[];for(;s+t<=e.size;)i.push(Oe(e,s,t)),s+=r;if(a)for(;s<e.size;){let o=s+t-e.size,l=kt([Oe(e,s,t-o),td([o],n)]);i.push(l),s+=r}return i.length===0?an([],[0,t]):U(kt(i),[i.length,t])}var Pk=V({frame_:Az});function xz(e,t,r,a,n=$k){a==null&&(a=Rk(t));let s=Pk(e,t,r),i=L(s,n(t));return cm(i,a)}var bz=V({stft_:xz});function vz(e,t,r,a,n="bilinear",s=0){let i=$(e,"image","cropAndResize"),o=$(t,"boxes","cropAndResize","float32"),l=$(r,"boxInd","cropAndResize","int32"),d=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 [${d},4] but had shape ${o.shape}.`),P(l.rank===1&&l.shape[0]===d,()=>`Error in cropAndResize: boxInd must be have size [${d}] but had shape ${o.shape}.`),P(a.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${a.length}.`),P(a[0]>=1&&a[1]>=1,()=>`cropSize must be atleast [1,1], but was ${a}`),P(n==="bilinear"||n==="nearest",()=>`method must be bilinear or nearest, but was ${n}`);let u={image:i,boxes:o,boxInd:l},p={method:n,extrapolationValue:s,cropSize:a};return B.runKernel(Oo,u,p)}var wz=V({cropAndResize_:vz});function kz(e){let t=$(e,"image","flipLeftRight","float32");P(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);let r={image:t};return B.runKernel(Bo,r,{})}var Iz=V({flipLeftRight_:kz});function Sz(e){let t=$(e,"image","grayscaleToRGB"),r=t.rank-1,a=t.shape[r];P(t.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`),P(a===1,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${a}.`);let n=new Array(t.rank);return n.fill(1,0,r),n[r]=3,Wa(t,n)}var Tz=V({grayscaleToRGB_:Sz});function Cz(e,t,r=0,a=.5){let n=$(e,"image","rotateWithOffset","float32");P(n.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${n.rank}.`);let s={image:n},i={radians:t,fillValue:r,center:a};return B.runKernel(gl,s,i)}var Nz=V({rotateWithOffset_:Cz});function id(e,t,r,a,n,s){a==null&&(a=.5),n==null&&(n=Number.NEGATIVE_INFINITY),s==null&&(s=0);let i=e.shape[0];return r=Math.min(r,i),P(0<=a&&a<=1,()=>`iouThreshold must be in [0, 1], but was '${a}'`),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:r,iouThreshold:a,scoreThreshold:n,softNmsSigma:s}}function Ez(e,t,r,a=.5,n=Number.NEGATIVE_INFINITY){let s=$(e,"boxes","nonMaxSuppression","float32"),i=$(t,"scores","nonMaxSuppression","float32"),o=id(s,i,r,a,n);r=o.maxOutputSize,a=o.iouThreshold,n=o.scoreThreshold;let l={maxOutputSize:r,iouThreshold:a,scoreThreshold:n};return B.runKernel(Xo,{boxes:s,scores:i},l)}var Rz=V({nonMaxSuppression_:Ez});function Fz(e,t,r){let a=Mz(e,t,r),n=a<0?-(a+1):a;e.splice(n,0,t)}function Mz(e,t,r){return Pz(e,t,r||$z)}function $z(e,t){return e>t?1:e<t?-1:0}function Pz(e,t,r){let a=0,n=e.length,s=0,i=!1;for(;a<n;){s=a+(n-a>>>1);let o=r(t,e[s]);o>0?a=s+1:(n=s,i=!o)}return i?a:-a-1}function Ok(e,t,r,a,n){return O2(e,t,r,a,n,0)}function zk(e,t,r,a,n,s){return O2(e,t,r,a,n,0,!1,s,!0)}function Dk(e,t,r,a,n,s){return O2(e,t,r,a,n,s,!0)}function O2(e,t,r,a,n,s,i=!1,o=!1,l=!1){let d=[];for(let g=0;g<t.length;g++)t[g]>n&&d.push({score:t[g],boxIndex:g,suppressBeginIndex:0});d.sort(J5);let u=s>0?-.5/s:0,p=[],h=[];for(;p.length<r&&d.length>0;){let g=d.pop(),{score:y,boxIndex:A,suppressBeginIndex:x}=g;if(y<n)break;let b=!1;for(let v=p.length-1;v>=x;--v){let C=Oz(e,A,p[v]);if(C>=a){b=!0;break}if(g.score=g.score*zz(a,u,C),g.score<=n)break}g.suppressBeginIndex=p.length,b||(g.score===y?(p.push(A),h.push(g.score)):g.score>n&&Fz(d,g,J5))}let c=p.length,f=r-c;o&&f>0&&(p.push(...new Array(f).fill(0)),h.push(...new Array(f).fill(0)));let m={selectedIndices:p};return i&&(m.selectedScores=h),l&&(m.validOutputs=c),m}function Oz(e,t,r){let a=e.subarray(t*4,t*4+4),n=e.subarray(r*4,r*4+4),s=Math.min(a[0],a[2]),i=Math.min(a[1],a[3]),o=Math.max(a[0],a[2]),l=Math.max(a[1],a[3]),d=Math.min(n[0],n[2]),u=Math.min(n[1],n[3]),p=Math.max(n[0],n[2]),h=Math.max(n[1],n[3]),c=(o-s)*(l-i),f=(p-d)*(h-u);if(c<=0||f<=0)return 0;let m=Math.max(s,d),g=Math.max(i,u),y=Math.min(o,p),A=Math.min(l,h),x=Math.max(y-m,0)*Math.max(A-g,0);return x/(c+f-x)}function zz(e,t,r){let a=Math.exp(t*r*r);return r<=e?a:0}function J5(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function Dz(e,t,r,a=.5,n=Number.NEGATIVE_INFINITY){let s=$(e,"boxes","nonMaxSuppressionAsync"),i=$(t,"scores","nonMaxSuppressionAsync"),o=id(s,i,r,a,n);r=o.maxOutputSize,a=o.iouThreshold,n=o.scoreThreshold;let l=await Promise.all([s.data(),i.data()]),d=l[0],u=l[1],{selectedIndices:p}=Ok(d,u,r,a,n);return s!==e&&s.dispose(),i!==t&&i.dispose(),St(p,"int32")}var _z=Dz;function Lz(e,t,r,a=.5,n=Number.NEGATIVE_INFINITY,s=0){let i=$(e,"boxes","nonMaxSuppression"),o=$(t,"scores","nonMaxSuppression"),l=id(i,o,r,a,n,s);r=l.maxOutputSize,a=l.iouThreshold,n=l.scoreThreshold,s=l.softNmsSigma;let d={boxes:i,scores:o},u={maxOutputSize:r,iouThreshold:a,scoreThreshold:n,softNmsSigma:s},p=B.runKernel(Zo,d,u);return{selectedIndices:p[0],selectedScores:p[1]}}var Bz=V({nonMaxSuppressionWithScore_:Lz});async function Wz(e,t,r,a=.5,n=Number.NEGATIVE_INFINITY,s=0){let i=$(e,"boxes","nonMaxSuppressionAsync"),o=$(t,"scores","nonMaxSuppressionAsync"),l=id(i,o,r,a,n,s);r=l.maxOutputSize,a=l.iouThreshold,n=l.scoreThreshold,s=l.softNmsSigma;let d=await Promise.all([i.data(),o.data()]),u=d[0],p=d[1],{selectedIndices:h,selectedScores:c}=Dk(u,p,r,a,n,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:St(h,"int32"),selectedScores:St(c)}}var Vz=Wz;function Uz(e,t,r,a=.5,n=Number.NEGATIVE_INFINITY,s=!1){let i=$(e,"boxes","nonMaxSuppression"),o=$(t,"scores","nonMaxSuppression"),l=id(i,o,r,a,n,null),d=l.maxOutputSize,u=l.iouThreshold,p=l.scoreThreshold,h={boxes:i,scores:o},c={maxOutputSize:d,iouThreshold:u,scoreThreshold:p,padToMaxOutputSize:s},f=B.runKernel(Gu,h,c);return{selectedIndices:f[0],validOutputs:f[1]}}var Gz=V({nonMaxSuppressionPadded_:Uz});async function jz(e,t,r,a=.5,n=Number.NEGATIVE_INFINITY,s=!1){let i=$(e,"boxes","nonMaxSuppressionAsync"),o=$(t,"scores","nonMaxSuppressionAsync"),l=id(i,o,r,a,n,null),d=l.maxOutputSize,u=l.iouThreshold,p=l.scoreThreshold,[h,c]=await Promise.all([i.data(),o.data()]),{selectedIndices:f,validOutputs:m}=zk(h,c,d,u,p,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:St(f,"int32"),validOutputs:Se(m,"int32")}}var Hz=jz;function qz(e,t,r=!1,a=!1){let n=$(e,"images","resizeBilinear");P(n.rank===3||n.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${n.rank}.`),P(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),P(a===!1||r===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let s=n,i=!1;n.rank===3&&(i=!0,s=U(n,[1,n.shape[0],n.shape[1],n.shape[2]]));let[]=t,o={images:s},l={alignCorners:r,halfPixelCenters:a,size:t},d=B.runKernel(Ii,o,l);return i?U(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Kz=V({resizeBilinear_:qz});function Xz(e,t,r=!1,a=!1){let n=$(e,"images","resizeNearestNeighbor");P(n.rank===3||n.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${n.rank}.`),P(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),P(n.dtype==="float32"||n.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),P(a===!1||r===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let s=n,i=!1;n.rank===3&&(i=!0,s=U(n,[1,n.shape[0],n.shape[1],n.shape[2]]));let[]=t,o={images:s},l={alignCorners:r,halfPixelCenters:a,size:t},d=B.runKernel(qu,o,l);return i?U(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Zz=V({resizeNearestNeighbor_:Xz});function Yz(e,t="binary",r=!1,a=.5){let n=$(e,"image","threshold"),s=.2989,i=.587,o=.114,l=n.shape[0]*n.shape[1],d=L(St([a]),255),u,p,h,c;if(P(n.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${n.rank}.`),P(n.shape[2]===3||n.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${n.shape[2]}.`),P(n.dtype==="int32"||n.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${n.dtype}.`),P(t==="otsu"||t==="binary",()=>`Method must be binary or otsu, but was ${t}`),n.shape[2]===3){[u,p,h]=Kt(n,[1,1,1],-1);let m=L(u,s),g=L(p,i),y=L(h,o);c=ue(ue(m,g),y)}else c=e;if(t==="otsu"){let m=n2(me(w2(c),"int32"),pt([]),256);d=Jz(m,l)}let f=r?bl(c,d):fa(c,d);return me(L(f,255),"int32")}function Jz(e,t){let r=St([-1]),a=St([0]),n=St([0]),s,i,o,l,d,u;for(let p=0;p<e.size-1;p++){s=Oe(e,0,p+1),i=Oe(e,p+1),d=pe(ke(s),t),u=pe(ke(i),t);let h=ke(L(s,gu(0,s.size)));o=pe(h,ke(s));let c=td(i.shape,s.size),f=ue(gu(0,i.size),c),m=L(i,f);l=pe(ke(m),ke(i));let g=he(o,l),y=he(o,l),A=L(d,u);n=L(L(A,g),y);let x=fa(n,a);a=zr(x,n,a),r=zr(x,St([p]),r)}return r}var Qz=V({threshold_:Yz});function eD(e,t,r="nearest",a="constant",n=0,s){let i=$(e,"image","transform","float32"),o=$(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},d={interpolation:r,fillMode:a,fillValue:n,outputShape:s};return B.runKernel(cl,l,d)}var tD=V({transform_:eD});function rD(e,t,r){P(t%1===0,()=>`bandPart(): numLower must be an integer, got ${t}.`),P(r%1===0,()=>`bandPart(): numUpper must be an integer, got ${r}.`);let a=$(e,"a","bandPart");P(a.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${a.rank}.`);let n=a.shape,[s,i]=a.shape.slice(-2);if(!(t<=s))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${s}).`);if(!(r<=i))throw new Error(`bandPart(): numUpper (${r}) must not be greater than the number of columns (${i}).`);t<0&&(t=s),r<0&&(r=i);let o=U(gu(0,s,1,"int32"),[-1,1]),l=gu(0,i,1,"int32"),d=he(o,l),u=ln(bl(d,Se(+t,"int32")),xl(d,Se(-r,"int32"))),p=Vt([s,i],a.dtype);return U(nr(ra(U(a,[-1,s,i])).map(h=>zr(u,h,p))),n)}var aD=V({bandPart_:rD});function nD(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 n=e[0].shape[0];for(let s=1;s<e.length;++s)P(e[s].shape[0]===n,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[s].shape[0]} vs. ${n})`)}else t=!0,e=Kt(e,e.shape[0],0).map(n=>Ye(n,[0]));P(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);let r=[],a=e;for(let n=0;n<e.length;++n)r.push(B.tidy(()=>{let s=a[n];if(n>0)for(let i=0;i<n;++i){let o=L(ke(L(r[i],s)),r[i]);s=he(s,o)}return pe(s,F2(s,"euclidean"))}));return t?nr(r,0):r}var sD=V({gramSchmidt_:nD});function iD(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 Q5(e,t);{let r=e.shape.slice(0,e.shape.length-2).reduce((l,d)=>l*d),a=ra(U(e,[r,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),n=[],s=[];a.forEach(l=>{let[d,u]=Q5(l,t);n.push(d),s.push(u)});let i=U(nr(n,0),e.shape),o=U(nr(s,0),e.shape);return[i,o]}}function Q5(e,t=!1){return B.tidy(()=>{P(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);let r=e.shape[0],a=e.shape[1],n=p2(r),s=Pr(e),i=an([[1]],[1,1]),o=Pr(i),l=r>=a?a:r;for(let d=0;d<l;++d){let u=s,p=o,h=n;[o,s,n]=B.tidy(()=>{let c=Oe(s,[d,d],[r-d,1]),f=F2(c),m=Oe(s,[d,d],[1,1]),g=zr(fa(m,0),an([[-1]]),an([[1]])),y=he(m,L(g,f)),A=pe(c,y);A.shape[0]===1?o=Pr(i):o=kt([i,Oe(A,[1,0],[A.shape[0]-1,A.shape[1]])],0);let x=zt(pe(Ke(g,y),f)),b=Oe(s,[d,0],[r-d,a]),v=L(x,o),C=rt(o);if(d===0)s=he(b,Ke(v,Ke(C,b)));else{let R=he(b,Ke(v,Ke(C,b)));s=kt([Oe(s,[0,0],[d,a]),R],0)}let T=rt(v),E=Oe(n,[0,d],[r,n.shape[1]-d]);if(d===0)n=he(E,Ke(Ke(E,o),T));else{let R=he(E,Ke(Ke(E,o),T));n=kt([Oe(n,[0,0],[r,d]),R],1)}return[o,s,n]}),re([u,p,h])}return!t&&r>a&&(n=Oe(n,[0,0],[r,a]),s=Oe(s,[0,0],[a,a])),[n,s]})}var oD=V({qr_:iD}),_k=(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",e))(_k||{});function lD(e,t,r=3){let a=$(e,"losses","computeWeightedLoss"),n=null;t!=null&&(n=$(t,"weights","computeWeightedLoss"));let s=n==null?a:L(a,n);if(r===0)return s;if(r===2)return ke(s);if(r===1){if(n==null)return Wt(s);{let i=a.size/n.size,o=pe(ke(s),ke(n));return i>1?pe(o,Se(i)):o}}if(r===3){if(n==null)return pe(ke(s),Se(a.size));{let i=L(n,da(a.shape)),o=me(ke(mu(i,Se(0))),"float32");return pe(ke(s),o)}}throw Error(`Unknown reduction: ${r}`)}var Yn=V({computeWeightedLoss_:lD});function uD(e,t,r,a=3){let n=$(e,"labels","absoluteDifference"),s=$(t,"predictions","absoluteDifference"),i=null;r!=null&&(i=$(r,"weights","absoluteDifference")),_r(n.shape,s.shape,"Error in absoluteDifference: ");let o=Qt(he(n,s));return Yn(o,i,a)}var dD=V({absoluteDifference_:uD});function pD(e,t,r,a,n=3){let s=$(e,"labels","cosineDistance"),i=$(t,"predictions","cosineDistance"),o=null;a!=null&&(o=$(a,"weights","cosineDistance")),_r(s.shape,i.shape,"Error in cosineDistance: ");let l=Se(1),d=he(l,ke(L(s,i),r,!0));return Yn(d,o,n)}var hD=V({cosineDistance_:pD});function cD(e,t,r,a=3){let n=$(e,"labels","hingeLoss"),s=$(t,"predictions","hingeLoss"),i=null;r!=null&&(i=$(r,"weights","hingeLoss")),_r(n.shape,s.shape,"Error in hingeLoss: ");let o=Se(1);n=he(L(Se(2),n),o);let l=Fn(he(o,L(n,s)));return Yn(l,i,a)}var fD=V({hingeLoss_:cD});function mD(e,t,r,a=1,n=3){let s=$(e,"labels","huberLoss"),i=$(t,"predictions","huberLoss"),o=null;r!=null&&(o=$(r,"weights","huberLoss")),_r(s.shape,i.shape,"Error in huberLoss: ");let l=Se(a),d=Qt(he(i,s)),u=ph(d,l),p=he(d,u),h=ue(L(Se(.5),At(u)),L(l,p));return Yn(h,o,n)}var gD=V({huberLoss_:mD});function yD(e,t,r,a=1e-7,n=3){let s=$(e,"labels","logLoss"),i=$(t,"predictions","logLoss"),o=null;r!=null&&(o=$(r,"weights","logLoss")),_r(s.shape,i.shape,"Error in logLoss: ");let l=Se(1),d=Se(a),u=zt(L(s,Ea(ue(i,d)))),p=L(he(l,s),Ea(ue(he(l,i),d))),h=he(u,p);return Yn(h,o,n)}var AD=V({logLoss_:yD});function xD(e,t,r,a=3){let n=$(e,"labels","meanSquaredError"),s=$(t,"predictions","meanSquaredError"),i=null;r!=null&&(i=$(r,"weights","meanSquaredError")),_r(n.shape,s.shape,"Error in meanSquaredError: ");let o=E2(n,s);return Yn(o,i,a)}var bD=V({meanSquaredError_:xD});function vD(e,t){let r=$(e,"labels","sigmoidCrossEntropyWithLogits"),a=$(t,"logits","sigmoidCrossEntropyWithLogits");_r(r.shape,a.shape,"Error in sigmoidCrossEntropyWithLogits: ");let n=Fn(a),s=L(a,r),i=nm(Na(zt(Qt(a))));return ue(he(n,s),i)}function wD(e,t,r,a=0,n=3){let s=$(e,"multiClassLabels","sigmoidCrossEntropy"),i=$(t,"logits","sigmoidCrossEntropy"),o=null;if(r!=null&&(o=$(r,"weights","sigmoidCrossEntropy")),_r(s.shape,i.shape,"Error in sigmoidCrossEntropy: "),a>0){let d=Se(a),u=Se(1),p=Se(.5);s=ue(L(s,he(u,d)),L(p,d))}let l=vD(s,i);return Yn(l,o,n)}var kD=V({sigmoidCrossEntropy_:wD});function ID(e,t,r=-1){if(r===-1&&(r=t.rank-1),r!==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 ${r}`);return Nn((a,n,s)=>{let i=pk(n,[r],!0),o=he(me(n,"float32"),i);s([a,o]);let l=zt(L(o,a));return{value:ke(l,[r]),gradFunc:(d,u)=>{let[p,h]=u,c=vo(d.shape,[r]);return[L(U(d,c),he(me(p,"float32"),Na(h))),L(U(d,c),he(Na(h),me(p,"float32")))]}}})(e,t)}function SD(e,t,r,a=0,n=3){let s=$(e,"onehotLabels","softmaxCrossEntropy"),i=$(t,"logits","softmaxCrossEntropy"),o=null;if(r!=null&&(o=$(r,"weights","softmaxCrossEntropy")),_r(s.shape,i.shape,"Error in softmaxCrossEntropy: "),a>0){let d=Se(a),u=Se(1),p=Se(s.shape[1]);s=ue(L(s,he(u,d)),pe(d,p))}let l=ID(s,i);return Yn(l,o,n)}var TD=V({softmaxCrossEntropy_:SD});function CD(e,t,r,a){let n=$(e,"indices","sparseFillEmptyRows","int32"),s=$(t,"values","sparseFillEmptyRows"),i=$(r,"denseShape","sparseFillEmptyRows","int32"),o=$(a,"defaultValue","sparseFillEmptyRows",s.dtype);if(n.rank!==2)throw new Error(`Indices should be Tensor2D but received shape
|
|
${n.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:n,values:s,denseShape:i,defaultValue:o},d=B.runKernel(Xp,l);return{outputIndices:d[0],outputValues:d[1],emptyRowIndicator:d[2],reverseIndexMap:d[3]}}var ND=V({sparseFillEmptyRows_:CD});function ED(e,t,r){let a=$(e,"inputIndices","sparseReshape","int32"),n=$(t,"inputShape","sparseReshape","int32"),s=$(r,"newShape","sparseReshape","int32");if(a.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape
|
|
${a.shape}`);if(n.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${n.shape}`);if(s.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${s.shape}`);let i={inputIndices:a,inputShape:n,newShape:s},o=B.runKernel(Yu,i);return{outputIndices:o[0],outputShape:o[1]}}var RD=V({sparseReshape_:ED});function FD(e,t,r){let a=$(e,"data","sparseSegmentMean"),n=$(t,"indices","sparseSegmentMean","int32"),s=$(r,"segmentIds","sparseSegmentMean","int32");if(a.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(n.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
|
|
${n.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
|
|
${s.shape}`);let i={data:a,indices:n,segmentIds:s};return B.runKernel(Zp,i)}var MD=V({sparseSegmentMean_:FD});function $D(e,t,r){let a=$(e,"data","sparseSegmentSum"),n=$(t,"indices","sparseSegmentSum","int32"),s=$(r,"segmentIds","sparseSegmentSum","int32");if(a.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(n.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
|
|
${n.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
|
|
${s.shape}`);let i={data:a,indices:n,segmentIds:s};return B.runKernel(Yp,i)}var PD=V({sparseSegmentSum_:$D});function OD(e,t,r,a,n,s,i,o){let l=$(e,"data","stringNGrams","string");if(l.dtype!=="string")throw new Error("Data must be of datatype string");if(l.shape.length!==1)throw new Error(`Data must be a vector, saw: ${l.shape}`);let d=$(t,"dataSplits","stringNGrams");if(d.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let u={separator:r,nGramWidths:a,leftPad:n,rightPad:s,padWidth:i,preserveShortSequences:o},p={data:l,dataSplits:d},h=B.runKernel(Qp,p,u);return{nGrams:h[0],nGramsSplits:h[1]}}var zD=V({stringNGrams_:OD});function DD(e,t,r=!0){let a=$(e,"input","stringSplit","string"),n=$(t,"delimiter","stringSplit","string");if(a.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${a.shape}`);if(n.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${n.shape}`);let s={skipEmpty:r},i={input:a,delimiter:n},o=B.runKernel(Kf,i,s);return{indices:o[0],values:o[1],shape:o[2]}}var _D=V({stringSplit_:DD});function LD(e,t){let r=$(e,"input","stringToHashBucketFast","string"),a={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");let n={input:r};return B.runKernel(Xf,n,a)}var BD=V({stringToHashBucketFast_:LD}),WD={fft:hm,ifft:Fp,rfft:cm,irfft:N2},VD={hammingWindow:gz,hannWindow:$k,frame:Pk,stft:bz},Ie={flipLeftRight:Iz,grayscaleToRGB:Tz,resizeNearestNeighbor:Zz,resizeBilinear:Kz,rotateWithOffset:Nz,cropAndResize:wz,nonMaxSuppression:Rz,nonMaxSuppressionAsync:_z,nonMaxSuppressionWithScore:Bz,nonMaxSuppressionWithScoreAsync:Vz,nonMaxSuppressionPadded:Gz,nonMaxSuppressionPaddedAsync:Hz,threshold:Qz,transform:tD},Lk={bandPart:aD,gramSchmidt:sD,qr:oD},UD={absoluteDifference:dD,computeWeightedLoss:Yn,cosineDistance:hD,hingeLoss:fD,huberLoss:gD,logLoss:AD,meanSquaredError:bD,sigmoidCrossEntropy:kD,softmaxCrossEntropy:TD},up={sparseFillEmptyRows:ND,sparseReshape:RD,sparseSegmentMean:MD,sparseSegmentSum:PD},Dc={stringNGrams:zD,stringSplit:_D,stringToHashBucketFast:BD},Jn=class extends Tw{minimize(e,t=!1,r){let{value:a,grads:n}=this.computeGradients(e,r);if(r!=null){let s=r.map(i=>({name:i.name,tensor:n[i.name]}));this.applyGradients(s)}else this.applyGradients(n);return re(n),t?a:(a.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return ok(e,t)}dispose(){this.iterations_!=null&&re(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:Se(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(Jn,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var xm=class extends Jn{constructor(e,t,r=null){super();this.learningRate=e,this.rho=t,this.epsilon=r,this.accumulatedGrads=[],this.accumulatedUpdates=[],r==null&&(this.epsilon=B.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,r)=>{let a=B.registeredVariables[t],n=!1;this.accumulatedGrads[r]==null&&(this.accumulatedGrads[r]={originalName:`${t}/accum_grad`,variable:q(()=>at(a).variable(n))}),this.accumulatedUpdates[r]==null&&(this.accumulatedUpdates[r]={originalName:`${t}/accum_var`,variable:q(()=>at(a).variable(n))});let s=Array.isArray(e)?e[r].tensor:e[t];if(s==null)return;let i=this.accumulatedGrads[r].variable,o=this.accumulatedUpdates[r].variable;q(()=>{let l=ue(L(i,this.rho),L(At(s),1-this.rho)),d=L(pe(Tr(ue(o,this.epsilon)),Tr(ue(i,this.epsilon))),s),u=ue(L(o,this.rho),L(At(d),1-this.rho));i.assign(l),o.assign(u);let p=ue(L(d,-this.learningRate),a);a.assign(p)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(re(this.accumulatedGrads.map(e=>e.variable)),re(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,r=!1;this.accumulatedGrads=e.slice(0,t).map(a=>({originalName:a.name,variable:a.tensor.variable(r)})),this.accumulatedUpdates=e.slice(t,t*2).map(a=>({originalName:a.name,variable:a.tensor.variable(r)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}};xm.className="Adadelta";_i(xm);var bm=class extends Jn{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,r)=>{let a=B.registeredVariables[t];this.accumulatedGrads[r]==null&&(this.accumulatedGrads[r]={originalName:`${t}/accumulator`,variable:q(()=>td(a.shape,this.initialAccumulatorValue).variable(!1))});let n=Array.isArray(e)?e[r].tensor:e[t];if(n==null)return;let s=this.accumulatedGrads[r].variable;q(()=>{let i=ue(s,At(n));s.assign(i);let o=ue(L(pe(n,Tr(ue(i,B.backend.epsilon()))),-this.learningRate),a);a.assign(o)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&re(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(r=>({originalName:r.name,variable:r.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}};bm.className="Adagrad";_i(bm);var vm=class extends Jn{constructor(e,t,r,a=null){super();this.learningRate=e,this.beta1=t,this.beta2=r,this.epsilon=a,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],q(()=>{this.accBeta1=Se(t).variable(),this.accBeta2=Se(r).variable()}),a==null&&(this.epsilon=B.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(r=>r.name):Object.keys(e);q(()=>{let r=he(1,this.accBeta1),a=he(1,this.accBeta2);t.forEach((n,s)=>{let i=B.registeredVariables[n],o=!1;this.accumulatedFirstMoment[s]==null&&(this.accumulatedFirstMoment[s]={originalName:`${n}/m`,variable:q(()=>at(i).variable(o))}),this.accumulatedSecondMoment[s]==null&&(this.accumulatedSecondMoment[s]={originalName:`${n}/v`,variable:q(()=>at(i).variable(o))});let l=Array.isArray(e)?e[s].tensor:e[n];if(l==null)return;let d=this.accumulatedFirstMoment[s].variable,u=this.accumulatedSecondMoment[s].variable,p=ue(L(d,this.beta1),L(l,1-this.beta1)),h=ue(L(u,this.beta2),L(At(l),1-this.beta2)),c=pe(p,r),f=pe(h,a);d.assign(p),u.assign(h);let m=ue(L(pe(c,ue(Tr(f),this.epsilon)),-this.learningRate),i);i.assign(m)}),this.accBeta1.assign(L(this.accBeta1,this.beta1)),this.accBeta2.assign(L(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&re(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&re(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),q(()=>{this.accBeta1.assign(Ds(this.beta1,this.iterations_+1)),this.accBeta2.assign(Ds(this.beta2,this.iterations_+1))});let t=e.length/2,r=!1;this.accumulatedFirstMoment=e.slice(0,t).map(a=>({originalName:a.name,variable:a.tensor.variable(r)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(a=>({originalName:a.name,variable:a.tensor.variable(r)}))}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)}};vm.className="Adam";_i(vm);var wm=class extends Jn{constructor(e,t,r,a=null,n=0){super();this.learningRate=e,this.beta1=t,this.beta2=r,this.epsilon=a,this.decay=n,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],q(()=>{this.iteration=Se(0).variable(),this.accBeta1=Se(t).variable()}),a==null&&(this.epsilon=B.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(r=>r.name):Object.keys(e);q(()=>{let r=he(1,this.accBeta1),a=pe(-this.learningRate,ue(L(this.iteration,this.decay),1));t.forEach((n,s)=>{let i=B.registeredVariables[n],o=!1;this.accumulatedFirstMoment[s]==null&&(this.accumulatedFirstMoment[s]={originalName:`${n}/m`,variable:at(i).variable(o)}),this.accumulatedWeightedInfNorm[s]==null&&(this.accumulatedWeightedInfNorm[s]={originalName:`${n}/v`,variable:at(i).variable(o)});let l=Array.isArray(e)?e[s].tensor:e[n];if(l==null)return;let d=this.accumulatedFirstMoment[s].variable,u=this.accumulatedWeightedInfNorm[s].variable,p=ue(L(d,this.beta1),L(l,1-this.beta1)),h=L(u,this.beta2),c=Qt(l),f=Zn(h,c);d.assign(p),u.assign(f);let m=ue(L(pe(a,r),pe(p,ue(f,this.epsilon))),i);i.assign(m)}),this.iteration.assign(ue(this.iteration,1)),this.accBeta1.assign(L(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&re(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&re(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)}};wm.className="Adamax";_i(wm);var ch=class extends Jn{constructor(e){super();this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,r)=>{let a=Array.isArray(e)?e[r].tensor:e[t];if(a==null)return;let n=B.registeredVariables[t];q(()=>{let s=ue(L(this.c,a),n);n.assign(s)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=dr(Se(-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)}};ch.className="SGD";_i(ch);var km=class extends ch{constructor(e,t,r=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=r,this.accumulations=[],this.m=Se(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,r)=>{let a=B.registeredVariables[t];this.accumulations[r]==null&&(this.accumulations[r]={originalName:`${t}/momentum`,variable:q(()=>at(a).variable(!1))});let n=this.accumulations[r].variable,s=Array.isArray(e)?e[r].tensor:e[t];s!=null&&q(()=>{let i,o=ue(L(this.m,n),s);this.useNesterov?i=ue(L(this.c,ue(s,L(o,this.m))),a):i=ue(L(this.c,o),a),n.assign(o),a.assign(i)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&re(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(r=>({originalName:r.name,variable:r.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)}};km.className="Momentum";_i(km);var Im=class extends Jn{constructor(e,t=.9,r=0,a=null,n=!1){super();if(this.learningRate=e,this.decay=t,this.momentum=r,this.epsilon=a,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=n,a==null&&(this.epsilon=B.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,r)=>{let a=B.registeredVariables[t],n=!1;this.accumulatedMeanSquares[r]==null&&(this.accumulatedMeanSquares[r]={originalName:`${t}/rms`,variable:q(()=>at(a).variable(n))}),this.accumulatedMoments[r]==null&&(this.accumulatedMoments[r]={originalName:`${t}/momentum`,variable:q(()=>at(a).variable(n))}),this.accumulatedMeanGrads[r]==null&&this.centered&&(this.accumulatedMeanGrads[r]={originalName:`${t}/mg`,variable:q(()=>at(a).variable(n))});let s=Array.isArray(e)?e[r].tensor:e[t];if(s==null)return;let i=this.accumulatedMeanSquares[r].variable,o=this.accumulatedMoments[r].variable;q(()=>{let l=ue(L(i,this.decay),L(At(s),1-this.decay));if(this.centered){let d=this.accumulatedMeanGrads[r].variable,u=ue(L(d,this.decay),L(s,1-this.decay)),p=pe(L(s,this.learningRate),Tr(he(l,ue(At(u),this.epsilon)))),h=ue(L(o,this.momentum),p);i.assign(l),d.assign(u),o.assign(h);let c=he(a,h);a.assign(c)}else{let d=ue(L(i,this.decay),L(At(s),1-this.decay)),u=ue(L(o,this.momentum),pe(L(s,this.learningRate),Tr(ue(d,this.epsilon))));i.assign(d),o.assign(u);let p=he(a,u);a.assign(p)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&re(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&re(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&re(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,r=!1;this.accumulatedMeanSquares=e.slice(0,t).map(a=>({originalName:a.name,variable:a.tensor.variable(r)})),this.accumulatedMoments=e.slice(t,t*2).map(a=>({originalName:a.name,variable:a.tensor.variable(r)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(a=>({originalName:a.name,variable:a.tensor.variable(r)})))}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)}};Im.className="RMSProp";_i(Im);var vs=class{static sgd(e){return new ch(e)}static momentum(e,t,r=!1){return new km(e,t,r)}static rmsprop(e,t=.9,r=0,a=null,n=!1){return new Im(e,t,r,a,n)}static adam(e=.001,t=.9,r=.999,a=null){return new vm(e,t,r,a)}static adadelta(e=.001,t=.95,r=null){return new xm(e,t,r)}static adamax(e=.002,t=.9,r=.999,a=null,n=0){return new wm(e,t,r,a,n)}static adagrad(e,t=.1){return new bm(e,t)}},so={sgd:vs.sgd,momentum:vs.momentum,adadelta:vs.adadelta,adagrad:vs.adagrad,rmsprop:vs.rmsprop,adamax:vs.adamax,adam:vs.adam},GD=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function Bk(){return new Promise(e=>GD(()=>e()))}var N={};De(N,{ERF_A1:()=>t_,ERF_A2:()=>r_,ERF_A3:()=>a_,ERF_A4:()=>n_,ERF_A5:()=>s_,ERF_P:()=>e_,PARALLELIZE_THRESHOLD:()=>z2,SELU_SCALE:()=>Vk,SELU_SCALEALPHA:()=>Wk,applyActivation:()=>ym,assertAndGetBroadcastShape:()=>bt,assertAxesAreInnerMostDims:()=>rP,assertParamsConsistent:()=>jD,assignToTypedArray:()=>p_,axesAreInnerMostDims:()=>f2,calculateShapes:()=>gw,checkEinsumDimSizes:()=>y_,checkPadOnDimRoundingMode:()=>Lr,combineLocations:()=>lk,complexWithEvenIndex:()=>l_,complexWithOddIndex:()=>u_,computeConv2DInfo:()=>oh,computeConv3DInfo:()=>Lw,computeDefaultPad:()=>r2,computeDilation2DInfo:()=>wM,computeOptimalWindowSize:()=>qD,computeOutAndReduceShapes:()=>uk,computeOutShape:()=>HD,computePool2DInfo:()=>_w,computePool3DInfo:()=>kM,convertConv2DDataFormat:()=>Bw,decodeEinsumEquation:()=>m_,eitherStridesOrDilationsAreOne:()=>Rn,expandShapeToKeepDim:()=>vo,exponent:()=>c_,exponents:()=>h_,fromStringArrayToUint8:()=>__,fromUint8ToStringArray:()=>D_,getAxesPermutation:()=>dk,getBroadcastDims:()=>hw,getComplexWithIndex:()=>d_,getEinsumComputePath:()=>A_,getEinsumPermutation:()=>g_,getFusedBiasGradient:()=>gm,getFusedDyActivation:()=>mm,getImageCenter:()=>KD,getInnerMostAxes:()=>aP,getPermuted:()=>ZD,getReductionAxes:()=>Xt,getReshaped:()=>XD,getReshapedPermuted:()=>YD,getSliceBeginCoords:()=>JD,getSliceSize:()=>QD,getSparseFillEmptyRowsIndicesDenseShapeMismatch:()=>w_,getSparseFillEmptyRowsNegativeIndexErrorMessage:()=>k_,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:()=>I_,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:()=>C_,getSparseReshapeInputOutputMismatchErrorMessage:()=>E_,getSparseReshapeInputOutputMultipleErrorMessage:()=>N_,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:()=>S_,getSparseReshapeNegativeOutputDimErrorMessage:()=>T_,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:()=>$_,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:()=>R_,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:()=>F_,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:()=>M_,getUndoAxesPermutation:()=>m2,isIdentityPermutation:()=>x_,log:()=>ZE,mergeRealAndImagArrays:()=>i_,prepareAndValidate:()=>mw,prepareSplitSize:()=>v_,segment_util:()=>Uk,shouldFuse:()=>Am,slice_util:()=>Ot,splitRealAndImagArrays:()=>o_,tupleValuesAreOne:()=>Ps,upcastType:()=>Or,validateInput:()=>qy,validateUpdateShape:()=>Hy,warn:()=>ks});function jD(e,t){let r=e[0].length;e.forEach((n,s)=>{P(n.length===r,()=>`Error in concat${r}D: rank of tensors[${s}] must be the same as the rank of the rest (${r})`)}),P(t>=0&&t<r,()=>`Error in concat${r}D: axis must be between 0 and ${r-1}.`);let a=e[0];e.forEach((n,s)=>{for(let i=0;i<r;i++)P(i===t||n[i]===a[i],()=>`Error in concat${r}D: Shape of tensors[${s}] (${n}) does not match the shape of the rest (${a}) along the non-concatenated axis ${s}.`)})}function HD(e,t){let r=e[0].slice();for(let a=1;a<e.length;a++)r[t]+=e[a][t];return r}var z2=30;function qD(e){return e<=z2?e:Kc(e,Math.floor(Math.sqrt(e)))}function KD(e,t,r){let a=r*(typeof e=="number"?e:e[0]),n=t*(typeof e=="number"?e:e[1]);return[a,n]}function XD(e,t,r,a=!0){let n=[];if(a)n=n.concat(t.slice(0)),n.push(e[0]/r),n=n.concat(e.slice(1));else{n=n.concat(e[0]);let s=t.length;for(let i=0;i<s;++i)n=n.concat([e[i+1]/t[i],t[i]]);n=n.concat(e.slice(s+1))}return n}function ZD(e,t,r=!0){let a=[];if(r){a.push(t);for(let n=t+1;n<e;++n)n<=2*t?(a.push(n),a.push(n-(t+1))):a.push(n)}else{let n=[],s=[];for(let i=1;i<e;++i)i>=t*2+1||i%2===1?s.push(i):n.push(i);a.push(...n),a.push(0),a.push(...s)}return a}function YD(e,t,r,a=!0){let n=[];a?n.push(e[0]/r):n.push(e[0]*r);for(let s=1;s<e.length;++s)s<=t.length?a?n.push(t[s-1]*e[s]):n.push(e[s]/t[s-1]):n.push(e[s]);return n}function JD(e,t){let r=[0];for(let a=0;a<t;++a)r.push(e[a][0]);return r}function QD(e,t,r){let a=e.slice(0,1);for(let n=0;n<r;++n)a.push(e[n+1]-t[n][0]-t[n][1]);return a}var Wk=1.7580993408473768,Vk=1.0507009873554805,e_=.3275911,t_=.254829592,r_=-.284496736,a_=1.421413741,n_=-1.453152027,s_=1.061405429;function i_(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 r=new Float32Array(e.length*2);for(let a=0;a<r.length;a+=2)r[a]=e[a/2],r[a+1]=t[a/2];return r}function o_(e){let t=new Float32Array(e.length/2),r=new Float32Array(e.length/2);for(let a=0;a<e.length;a+=2)t[a/2]=e[a],r[a/2]=e[a+1];return{real:t,imag:r}}function l_(e){let t=Math.ceil(e.length/4),r=new Float32Array(t),a=new Float32Array(t);for(let n=0;n<e.length;n+=4)r[Math.floor(n/4)]=e[n],a[Math.floor(n/4)]=e[n+1];return{real:r,imag:a}}function u_(e){let t=Math.floor(e.length/4),r=new Float32Array(t),a=new Float32Array(t);for(let n=2;n<e.length;n+=4)r[Math.floor(n/4)]=e[n],a[Math.floor(n/4)]=e[n+1];return{real:r,imag:a}}function d_(e,t){let r=e[t*2],a=e[t*2+1];return{real:r,imag:a}}function p_(e,t,r,a){e[a*2]=t,e[a*2+1]=r}function h_(e,t){let r=new Float32Array(e/2),a=new Float32Array(e/2);for(let n=0;n<Math.ceil(e/2);n++){let s=(t?2:-2)*Math.PI*(n/e);r[n]=Math.cos(s),a[n]=Math.sin(s)}return{real:r,imag:a}}function c_(e,t,r){let a=(r?2:-2)*Math.PI*(e/t),n=Math.cos(a),s=Math.sin(a);return{real:n,imag:s}}var v1="->",f_=/->/g,e3=",",t3="...";function m_(e,t){e=e.replace(/\s/g,"");let r=(e.length-e.replace(f_,"").length)/v1.length;if(r<1)throw new Error("Equations without an arrow are not supported.");if(r>1)throw new Error(`Equation must contain exactly one arrow ("${v1}").`);let[a,n]=e.split(v1);P(a.indexOf(t3)===-1,()=>`The ellipsis notation ("${t3}") is not supported yet.`);let s=a.split(e3),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 h=0;h<n.length;++h){let c=n[h];if(!s.some(f=>f.indexOf(c)!==-1))throw new Error(`Output subscripts contain the label ${c} not present in the input subscripts.`);o.indexOf(c)===-1&&o.push(c)}for(let h=0;h<a.length;++h){let c=a[h];o.indexOf(c)===-1&&c!==e3&&o.push(c)}let l=new Array(s.length);for(let h=0;h<i;++h){if(new Set(s[h].split("")).size!==s[h].length)throw new Error(`Found duplicate axes in input component ${s[h]}. Support for duplicate axes in input is not implemented yet.`);l[h]=[];for(let c=0;c<s[h].length;++c)l[h].push(o.indexOf(s[h][c]))}let d=o.length,u=n.length,p=[];for(let h=u;h<d;++h)p.push(h);return{allDims:o,summedDims:p,idDims:l}}function g_(e,t){let r=new Array(e);r.fill(-1);for(let n=0;n<t.length;++n)r[t[n]]=n;let a=[];for(let n=0;n<e;++n)r[n]===-1&&a.push(n);return r=r.filter(n=>n!==-1),{permutationIndices:r,expandDims:a}}function y_(e,t,r){let a=new Array(e);for(let n=0;n<r.length;++n){let s=r[n].shape;for(let i=0;i<t[n].length;++i)a[t[n][i]]===void 0?a[t[n][i]]=s[i]:P(a[t[n][i]]===s[i],()=>`Expected dimension ${a[t[n][i]]} at axis ${i} of input shaped ${JSON.stringify(s)}, but got dimension ${s[i]}`)}}function A_(e,t){let r=e,a=[],n=0;e.length===0&&r.push(-1),n=e.length+1;for(let i=0;i<n;++i)a.push([]);let s=[];for(let i=0;i<r.length;++i){let o=r[i],l=b_(t,o);for(let d of l)s.indexOf(d)===-1&&(a[i].push(d),s.push(d))}return{path:r,steps:a}}function x_(e){return e.every((t,r)=>t===r)}function b_(e,t){let r=[];for(let a=0;a<e.length;++a)(e[a].length===0||e[a].indexOf(t)!==-1||t===-1)&&r.push(a);return r}function v_(e,t,r=0){let a=[];if(typeof t=="number")P(e.shape[r]%t===0,()=>"Number of splits must evenly divide the axis."),a=new Array(t).fill(e.shape[r]/t);else{let n=t.reduce((i,o)=>(o===-1&&(i+=1),i),0);P(n<=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[r]-i}P(e.shape[r]===t.reduce((i,o)=>i+o),()=>"The sum of sizes must match the size of the axis dimension."),a=t}return a}function w_(e){return`Received SparseTensor with denseShape[0] = 0 but
|
|
indices.shape[0] = ${e}`}function k_(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function I_(e,t,r){return`indices(${e}, 0) is invalid: ${t} >= ${r}`}function S_(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function T_(e,t){return`size ${e} must be non-negative, not ${t}`}function C_(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function N_(e,t){let r=Tt(e),a=Tt(t);return`Input to reshape is a SparseTensor with ${r}
|
|
dense values, but the requested shape requires a multiple of ${a}. inputShape=${e} outputShape= ${t}`}function E_(e,t){let r=Tt(e),a=Tt(t);return`Input to reshape is a tensor with ${r} dense values, but the requested shape has ${a}. inputShape=${e} outputShape=${t}`}function R_(){return"segment ids must be >= 0"}function F_(){return"segment ids are not increasing"}function M_(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function $_(e,t,r){return`Bad: indices[${e}] == ${t} out of range [0, ${r})`}var Uk={};De(Uk,{collectGatherOpShapeInfo:()=>z_,computeOutShape:()=>O_,segOpComputeOptimalWindowSize:()=>P_});function P_(e,t){let r=!1,a;for(e<=z2?(a=e,r=!0):a=Kc(e,Math.floor(Math.sqrt(e)));!r;)a>t||a===e?r=!0:a=Kc(e,a+1);return a}function O_(e,t,r){let a=[],n=e.length;for(let s=0;s<n;s++)s!==t?a.push(e[s]):a.push(r);return a}function z_(e,t,r,a){let n=t.shape.length,s=e.shape.length;if(a!==0&&(a<-n||a>n))throw new Error(`Expect batchDims in the range of [-${n}, ${n}], but got ${a}`);if(a<0&&(a+=n),a>s)throw new Error(`batchDims (${a}) must be less than rank(x) (
|
|
${s}).`);if(r<a)throw new Error(`batchDims (${a}) must be less than or equal to axis (${r}).`);for(let p=0;p<a;++p)if(e.shape[p]!==t.shape[p])throw new Error(`x.shape[${p}]: ${e.shape[p]} should be equal to indices.shape[${p}]: ${t.shape[p]}.`);let i=e.shape[r],o=[],l=1,d=1,u=1;for(let p=0;p<a;++p)o.push(e.shape[p]),l*=e.shape[p];for(let p=a;p<r;p++)o.push(e.shape[p]),d*=e.shape[p];for(let p=a;p<n;p++)o.push(t.shape[p]);for(let p=r+1;p<s;p++)o.push(e.shape[p]),u*=e.shape[p];return{batchSize:l,sliceSize:u,outerSize:d,dimSize:i,outputShape:o}}function D_(e){try{return e.map(t=>Jc(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function __(e){return e.map(t=>rh(t))}var Ha={};De(Ha,{nonMaxSuppressionV3Impl:()=>Ok,nonMaxSuppressionV4Impl:()=>zk,nonMaxSuppressionV5Impl:()=>Dk,whereImpl:()=>Sk});var Gk={kernelName:Fo,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(e,hh(me(r,"float32"),-1))}}},L_={kernelName:Tu,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>{let a=At(me(r,"float32")),n=Tr(he(Se(1),a));return zt(pe(e,n))}}}},B_={kernelName:Cu,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>{let a=Tr(he(At(me(r,"float32")),1));return pe(e,a)}}}},W_={kernelName:qn,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,a]=t,n=bt(r.shape,a.shape);return{a:()=>{let s=e,i=Xt(r.shape,n);return i.length>0&&(s=ke(s,i)),U(s,r.shape)},b:()=>{let s=e,i=Xt(a.shape,n);return i.length>0&&(s=ke(s,i)),U(s,a.shape)}}}},V_={kernelName:js,saveAllInputs:!0,gradFunc:(e,t)=>{let r={};return t.forEach((a,n)=>{r[n]=()=>e.clone()}),r}},U_={kernelName:Hs,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>at(r)}}},G_={kernelName:Ru,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>at(r)}}},j_={kernelName:Fu,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>pe(e,Tr(he(Se(1),At(me(r,"float32")))))}}},H_={kernelName:Mu,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>{let a=Tr(ue(Se(1),At(me(r,"float32"))));return pe(e,a)}}}},q_={kernelName:Ou,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,a]=t,n=bt(r.shape,a.shape);return{a:()=>{let s=ue(At(r),At(a)),i=L(e,pe(a,s)),o=Xt(r.shape,n);return o.length>0&&(i=ke(i,o)),U(i,r.shape)},b:()=>{let s=ue(At(r),At(a)),i=zt(L(e,pe(r,s))),o=Xt(a.shape,n);return o.length>0&&(i=ke(i,o)),U(i,a.shape)}}}},K_={kernelName:$u,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>pe(e,ue(At(me(r,"float32")),1))}}},X_={kernelName:Pu,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>pe(e,he(Se(1),At(me(r,"float32"))))}}};function Z_(e,t,r,a,n,s){let i=$(e,"dy","avgPool3dGrad"),o=$(t,"input","avgPool3dGrad"),l=i,d=o,u=!1;o.rank===4&&(u=!0,l=U(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),d=U(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),P(l.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`),P(d.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${d.rank}.`),Lr("avgPool3dGrad",n,s);let p={dy:l,input:d},h={filterSize:r,strides:a,pad:n,dimRoundingMode:s},c=B.runKernel(Cf,p,h);return u?U(c,[c.shape[1],c.shape[2],c.shape[3],c.shape[4]]):c}var Y_=V({avgPool3dGrad_:Z_}),J_={kernelName:_p,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[a]=t,{filterSize:n,strides:s,pad:i,dimRoundingMode:o}=r;return{x:()=>Y_(e,a,n,s,i,o)}}};function Q_(e,t,r,a,n){let s=$(e,"dy","avgPoolGrad"),i=$(t,"input","avgPoolGrad");P(i.rank===s.rank,()=>`Rank of input (${i.rank}) does not match rank of dy (${s.rank})`);let o=i,l=s,d=!1;i.rank===3&&(d=!0,o=U(i,[1,i.shape[0],i.shape[1],i.shape[2]]),l=U(s,[1,s.shape[0],s.shape[1],s.shape[2]])),P(l.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`),P(o.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${o.rank}.`);let u={dy:l,input:o},p={filterSize:r,strides:a,pad:n},h=B.runKernel(Tf,u,p);return d?U(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var eL=V({avgPoolGrad_:Q_}),tL={kernelName:qs,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[a]=t,{filterSize:n,strides:s,pad:i}=r;return{x:()=>eL(e,a,n,s,i)}}},rL={kernelName:Ks,inputsToSave:["a","b"],gradFunc:(e,t,r)=>{let[a,n]=t,{transposeA:s,transposeB:i}=r;return!s&&!i?{a:()=>Ke(e,n,!1,!0),b:()=>Ke(a,e,!0,!1)}:!s&&i?{a:()=>Ke(e,n,!1,!1),b:()=>Ke(e,a,!0,!1)}:s&&!i?{a:()=>Ke(n,e,!1,!0),b:()=>Ke(a,e,!1,!1)}:{a:()=>Ke(n,e,!0,!0),b:()=>Ke(e,a,!0,!0)}}},aL={kernelName:Mo,gradFunc:(e,t,r)=>{let{blockShape:a,crops:n}=r;return{x:()=>um(e,a,n)}}},nL={kernelName:Ov,gradFunc:(e,t,r)=>{let a=r,n=a.inputShape,s=a.shape,i=Array.from(s);for(let l=n.length-1;l>=0;l--)if(n[l]===s[l])i[l]=1;else if(n[l]!==1)throw new Error(`broadcastTo(): [${n}] cannot be broadcast to [${s}].`);let o=[];for(let l=0;l<i.length;l++)i[l]>1&&o.push(l);return{x:()=>ke(e,o,!0)}}},sL={kernelName:Xs,gradFunc:e=>({x:()=>e.clone()})},iL={kernelName:Zs,gradFunc:e=>({x:()=>at(e)})},oL={kernelName:Kn,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[a]=t,{clipValueMin:n,clipValueMax:s}=r;return{x:()=>zr(ln(xl(a,n),bl(a,s)),e,at(e))}}},lL={kernelName:Bp,inputsToSave:["x"],gradFunc:Gk.gradFunc},uL={kernelName:$o,saveAllInputs:!0,gradFunc:(e,t,r)=>{let a=t.map(o=>o.shape),{axis:n}=r,s=Ua(n,t[0].shape)[0],i=a.map(o=>o[s]);return Kt(e,i,s).map(o=>()=>o)}},dL={kernelName:Ys,inputsToSave:["x","filter"],gradFunc:(e,t,r)=>{let[a,n]=t,{dilations:s,strides:i,pad:o,dataFormat:l}=r;return P(Ps(s),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`),{x:()=>i2(a.shape,e,n,i,o,l),filter:()=>P2(a,e,n.shape,i,o,l)}}},pL={kernelName:Js,inputsToSave:["dy","filter"],gradFunc:(e,t,r)=>{let[a,n]=t,{strides:s,pad:i,dataFormat:o,dimRoundingMode:l}=r;return{dy:()=>Os(e,n,s,i,o,1,l),filter:()=>P2(e,a,n.shape,s,i,o,l)}}};function hL(e,t,r,a,n){let s=e;e.rank===4&&(s=U(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let i=t;i.rank===4&&(i=U(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),P(s.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${s.shape}.`),P(i.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${i.shape}.`),P(r.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${r}.`),P(s.shape[4]===r[3],()=>`Error in conv3dDerFilter: depth of input ${s.shape[4]}) must match input depth in filter (${r[3]}.`),P(i.shape[4]===r[4],()=>`Error in conv3dDerFilter: depth of dy (${i.shape[4]}) must match output depth for filter (${r[4]}).`);let o={x:s,dy:i},l={strides:a,pad:n,filterShape:r};return B.runKernel(Ff,o,l)}var cL=V({conv3DBackpropFilter_:hL}),fL={kernelName:Wp,inputsToSave:["x","filter"],gradFunc:(e,t,r)=>{let{dilations:a,strides:n,pad:s}=r;P(Ps(a),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`);let[i,o]=t;return{x:()=>Xw(i.shape,e,o,n,s),filter:()=>cL(i,e,o.shape,n,s)}}},mL={kernelName:Qs,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(zt(S2(me(r,"float32"))),e)}}},gL={kernelName:ei,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(T2(me(r,"float32")),e)}}},yL={kernelName:Po,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[a]=t,{axis:n,exclusive:s,reverse:i}=r;return{x:()=>{let o=dk([n],a.rank),l=d2(e,n,s,!i);return o!=null&&(l=rt(l,o)),l}}}},AL={kernelName:ti,inputsToSave:["x","filter"],gradFunc:(e,t,r)=>{let{dilations:a,strides:n,pad:s,dimRoundingMode:i}=r,o=a==null?[1,1]:a;P(Ps(o),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`);let[l,d]=t;return P(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),P(d.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${d.rank}.`),P(l.shape[3]===d.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${d.shape[2]}.`),P(Rn(n,o),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'.`),Lr("depthwiseConv2d",s,i),{x:()=>Mk(l.shape,e,d,n,s,o,i),filter:()=>Fk(l,e,d.shape,n,s,o,i)}}},xL={kernelName:Vp,inputsToSave:["x","filter"],gradFunc:(e,t,r)=>{let[a,n]=t,s={x:a,filter:n,dy:e},i={x:a,filter:n,dy:e};return{x:()=>B.runKernel(Xc,s,r),filter:()=>B.runKernel(Zc,i,r)}}},bL={kernelName:ai,outputsToSave:[!0],gradFunc:(e,t)=>{let[r]=t,a={dy:e,y:r};return{x:()=>B.runKernel(Df,a)}}},vL={kernelName:zu,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t,a=L(Na(zt(At(r))),2/Math.sqrt(Math.PI));return{x:()=>L(e,a)}}},wL={kernelName:ni,outputsToSave:[!0],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(e,r)}}},kL={kernelName:_o,inputsToSave:["input"],gradFunc:(e,t)=>{let[r]=t;return{input:()=>U(e,r.shape)}}},IL={kernelName:Lo,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(e,Na(r))}}},SL={kernelName:si,gradFunc:e=>({x:()=>at(e)})},TL={kernelName:ii,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,a]=t,n=bt(r.shape,a.shape);return{a:()=>{let s=pe(e,me(a,"float32")),i=Xt(r.shape,n);return i.length>0?U(ke(s,i),r.shape):s},b:()=>{let s=L(e,me(r,"float32")),i=Xt(a.shape,n);i.length>0&&(s=U(ke(s,i),a.shape));let o=At(a);return zt(pe(s,me(o,"float32")))}}}},CL={kernelName:oi,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,r)=>{let{varianceEpsilon:a}=r,[n,s,i,o]=t,l=o==null?Se(1):o,d=Xt(s.shape,n.shape),u=[];if(s.rank===1){for(let m=0;m<n.shape.length-1;++m)u.push(n.shape[m]);u.push(1)}let p=he(n,s),h=L(e,l),c=k2(ue(i,Se(a))),f=L(L(L(c,c),c),Se(-.5));return{x:()=>s.rank===1?U(L(L(e,Wa(U(c,[1,1,1,s.shape[0]]),u)),l),n.shape):U(L(L(e,c),l),n.shape),mean:()=>{let m=L(L(c,Se(-1)),h);return s.rank===1&&(m=ke(m,d)),U(m,s.shape)},variance:()=>{let m=L(L(f,p),h);return s.rank===1&&(m=ke(m,d)),U(m,s.shape)},scale:()=>{let m=L(p,c),g=L(e,m);return s.rank===1&&(g=ke(g,d)),U(g,s.shape)},offset:()=>{let m=e;return s.rank===1&&(m=ke(m,d)),U(m,s.shape)}}}},NL={kernelName:Wo,inputsToSave:["x","indices"],gradFunc:(e,t,r)=>{let[a,n]=t,{axis:s}=r,i=Ua(s,a.shape)[0];return{x:()=>{let o=a.shape,l=n.size,d=o.slice(0,i),u=d.length,p=o.slice(s,o.length).slice(1),h=p.length,c=r3(0,u),f=r3(u+1,u+1+h),m=a3([d,[l],p]),g=U(e,m),y=U(n,[l]),A=a3([[u],c,f]),x=rt(g,A),b=kk(x,y,a.shape[i]),v=m2(A);return b=rt(b,v),b},indices:()=>n}}};function r3(e,t){let r=[];for(let a=e;a<t;++a)r.push(a);return r}function a3(e){let t=[];for(let r=0;r<e.length;++r)for(let a=0;a<e[r].length;++a)t.push(e[r][a]);return t}var EL={kernelName:li,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,a]=t;return{a:()=>at(r),b:()=>at(a)}}},RL={kernelName:ui,gradFunc:e=>({x:()=>me(e,"float32")})},FL={kernelName:_u,gradFunc:e=>({x:()=>at(e)})},ML={kernelName:Lu,gradFunc:e=>({x:()=>at(e)})},$L={kernelName:Bu,gradFunc:e=>({x:()=>at(e)})},PL={kernelName:di,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[a]=t,{alpha:n}=r,s=fa(a,0);return{x:()=>zr(s,e,L(e,n))}}},OL={kernelName:Wu,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>pe(e,ue(r,1))}}},zL={kernelName:pi,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>pe(e,me(r,"float32"))}}},DL={kernelName:zv,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,r)=>{let[a]=t,{axis:n}=r;return{logits:()=>{let s=Na(a);return he(e,L(ke(e,n,!0),s))}}}};function _L(e,t,r,a=5,n=1,s=1,i=.5){let o={x:e,y:t,dy:r},l={depthRadius:a,bias:n,alpha:s,beta:i};return B.runKernel(Wf,o,l)}var LL=V({localResponseNormalizationBackprop_:_L}),BL={kernelName:Hp,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,r)=>{let[a,n]=t,{depthRadius:s,bias:i,alpha:o,beta:l}=r;return{x:()=>LL(a,n,e,s,i,o,l)}}};function jk(e,t,r,a){return t.rank<r.rank&&(t=U(t,vo(t.shape,a))),e.rank<r.rank&&(e=U(e,vo(e.shape,a))),{x:()=>L(e,me(Ca(r,t),e.dtype))}}var n3={kernelName:hi,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,r)=>{let a=r,{reductionIndices:n}=a,s=t[0],i=t[1],o=Ua(n,s.shape),l=jk(e,i,s,o);return{x:()=>l.x()}}},WL={kernelName:ci,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,a]=t;return{a:()=>L(e,me(xl(r,a),"float32")),b:()=>L(e,me(h2(r,a),"float32"))}}};function VL(e,t,r,a,n,s,i){let o=$(e,"dy","maxPool3dGrad"),l=$(t,"input","maxPool3dGrad"),d=$(r,"output","maxPool3dGrad"),u=o,p=l,h=d,c=!1;l.rank===4&&(c=!0,u=U(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),p=U(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),h=U(d,[1,d.shape[0],d.shape[1],d.shape[2],d.shape[3]])),P(u.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${u.rank}.`),P(p.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${p.rank}.`),P(h.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${h.rank}.`),Lr("maxPool3dGrad",s,i);let f={dy:u,input:p,output:h},m={filterSize:a,strides:n,pad:s,dimRoundingMode:i},g=B.runKernel(Uf,f,m);return c?U(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}var UL=V({maxPool3dGrad_:VL}),GL={kernelName:qp,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,r)=>{let[a,n]=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=r;return{x:()=>UL(e,a,n,s,i,o,l)}}};function jL(e,t,r,a,n,s,i){let o=$(e,"dy","maxPoolGrad"),l=$(t,"input","maxPoolGrad"),d=$(r,"output","maxPoolGrad");P(l.rank===o.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${o.rank})`),P(o.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${o.rank}.`),P(l.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`),Lr("maxPoolGrad",s,i);let u={dy:o,input:l,output:d},p={filterSize:a,strides:n,pad:s,dimRoundingMode:i};return B.runKernel(Vf,u,p)}var HL=V({maxPoolGrad_:jL}),qL={kernelName:fi,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,r)=>{let[a,n]=t,{filterSize:s,strides:i,pad:o}=r;return{x:()=>HL(e,a,n,s,i,o)}}},KL={kernelName:mi,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[a]=t,{axis:n}=r,s=Ua(n,a.shape),i=uk(a.shape,s)[1],o=Tt(i);return{x:()=>{let l=a.shape.slice();s.forEach(u=>{l[u]=1});let d=U(e,l);return pe(L(d,da(a.shape,"float32")),o)}}}},XL={kernelName:gi,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,r)=>{let a=r,{axis:n}=a,[s,i]=t,o=Ua(n,s.shape),l=jk(e,i,s,o);return{x:()=>l.x()}}},ZL={kernelName:yi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,a]=t;return{a:()=>L(e,me(bl(r,a),"float32")),b:()=>L(e,me(fa(r,a),"float32"))}}},YL={kernelName:Ai,inputsToSave:["x"],gradFunc:(e,t,r)=>{let a=t[0],{paddings:n}=r,s=n.map(i=>i[0]);return{x:()=>Oe(e,s,a.shape)}}},JL={kernelName:Uu,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,a]=t,n=bt(r.shape,a.shape);return{a:()=>{let s=Xt(r.shape,n);return s.length>0?U(ke(e,s),r.shape):e},b:()=>{let s=L(e,zt(dh(pe(r,a)))),i=Xt(a.shape,n);return i.length>0?U(ke(s,i),a.shape):s}}}},QL={kernelName:xi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,a]=t,n=bt(r.shape,a.shape);return{a:()=>{let s=L(e,me(a,"float32")),i=Xt(r.shape,n);return i.length>0?U(ke(s,i),r.shape):s},b:()=>{let s=L(e,me(r,"float32")),i=Xt(a.shape,n);return i.length>0?U(ke(s,i),a.shape):s}}}},eB={kernelName:qo,gradFunc:e=>({x:()=>zt(e)})},tB={kernelName:Jo,inputsToSave:["indices"],gradFunc:(e,t)=>{let r=t[0];return{indices:()=>Vt(r.shape,"float32")}}},rB={kernelName:Yo,gradFunc:e=>({x:()=>at(e)})},aB={kernelName:Qo,saveAllInputs:!0,gradFunc:(e,t,r)=>{let{axis:a}=r;return ra(e,a).map(n=>()=>n)}},s3={kernelName:bi,inputsToSave:["x"],gradFunc:(e,t,r)=>{let a=t[0],{paddings:n}=r,s=n.map(i=>i[0]);return{x:()=>Oe(e,s,a.shape)}}},nB={kernelName:vi,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{let[r,a,n]=t,s=r,i=a,o=bt(s.shape,i.shape);return{a:()=>{let l=me(i,"float32"),d=L(e,L(l,Ds(s,he(l,Se(1))))),u=Xt(s.shape,o);return u.length>0&&(d=ke(d,u)),U(d,s.shape)},b:()=>{let l=fa(s,0),d=zr(l,Ea(s),at(s)),u=L(e,L(n,d)),p=Xt(i.shape,o);return p.length>0&&(u=ke(u,p)),U(u,i.shape)}}}},sB={kernelName:wi,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{let[r,a]=t,n=fa(r,0);return{x:()=>zr(n,e,L(e,a)),alpha:()=>{let s=zr(n,at(e),L(e,r)),i=Xt(a.shape,e.shape);return i.length>0&&(s=ke(s,i)),U(s,a.shape)}}}},iB={kernelName:ri,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,a]=t,n=bt(r.shape,a.shape);return{a:()=>{let s=pe(e,me(a,"float32")),i=Xt(r.shape,n);return i.length>0?U(ke(s,i),r.shape):s},b:()=>{let s=L(e,me(r,"float32")),i=Xt(a.shape,n);i.length>0&&(s=U(ke(s,i),a.shape));let o=At(a);return zt(pe(s,me(o,"float32")))}}}},oB={kernelName:Hu,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>pe(e,zt(At(r)))}}},lB={kernelName:Si,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t,a=L(bl(r,6),hh(r));return{x:()=>L(e,me(a,"float32"))}}},uB={kernelName:ki,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(e,me(hh(r),"float32"))}}},dB={kernelName:tl,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>U(e,r.shape)}}},pB={kernelName:Ii,inputsToSave:["images"],gradFunc:(e,t,r)=>{let[a]=t,n={dy:e,images:a};return{images:()=>B.runKernel(qf,n,r)}}},hB={kernelName:qu,inputsToSave:["images"],gradFunc:(e,t,r)=>{let[a]=t,n={dy:e,images:a};return{images:()=>B.runKernel(Hf,n,r)}}},cB={kernelName:rl,gradFunc:(e,t,r)=>{let{dims:a}=r,n=Ua(a,e.shape);return{x:()=>Fa(e,n)}}},fB={kernelName:al,gradFunc:e=>({x:()=>at(e)})},mB={kernelName:Ti,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>zt(pe(e,L(Ds(r,1.5),2)))}}},gB={kernelName:sl,inputsToSave:["condition"],gradFunc:(e,t)=>{let[r]=t;return{condition:()=>me(at(r),"float32"),t:()=>L(e,me(r,e.dtype)),e:()=>L(e,me(im(r),e.dtype))}}},yB={kernelName:Ku,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>{let a=fa(r,Se(0)),n=Se(Wk),s=Se(Vk),i=L(e,s),o=L(L(e,n),Na(me(r,"float32")));return zr(a,i,o)}}}},AB={kernelName:Ni,outputsToSave:[!0],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(e,L(r,he(Se(1),r)))}}},xB={kernelName:Xu,gradFunc:e=>({x:()=>at(e)})},bB={kernelName:Ci,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(tm(me(r,"float32")),e)}}},vB={kernelName:ol,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(u2(me(r,"float32")),e)}}},wB={kernelName:il,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[a]=t,{begin:n,size:s}=r,i=a.shape,[o,l]=Sw(a,n,s),d=[];for(let u=0;u<e.rank;u++)d.push([o[u],i[u]-o[u]-l[u]]);return{x:()=>ja(e,d)}}},kB={kernelName:Fi,outputsToSave:[!0],gradFunc:(e,t,r)=>{let[a]=t,{dim:n}=r,s=!0,i=L(e,a);return{logits:()=>he(i,L(ke(i,[n],s),a))}}},IB={kernelName:Zu,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(e,Sr(r))}}},i3={kernelName:ll,gradFunc:(e,t,r)=>{let{blockShape:a,paddings:n}=r;return{x:()=>em(e,a,n)}}},o3={kernelName:ul,gradFunc:(e,t,r)=>{let{axis:a}=r;return{x:()=>kt(e,a)}}},SB={kernelName:Ei,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>pe(e,L(Tr(me(r,"float32")),2))}}},TB={kernelName:Ju,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(e,L(me(r,"float32"),2))}}},CB={kernelName:Mi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,a]=t,n=Se(2);return{a:()=>L(e,L(n,he(r,a))),b:()=>L(e,L(n,he(a,r)))}}},NB={kernelName:zi,gradFunc:e=>({x:()=>at(e)})},EB={kernelName:$i,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,a]=t,n=bt(r.shape,a.shape);return{a:()=>{let s=e,i=Xt(r.shape,n);return i.length>0&&(s=ke(s,i)),U(s,r.shape)},b:()=>{let s=e,i=Xt(a.shape,n);return i.length>0&&(s=ke(s,i)),U(zt(s),a.shape)}}}},RB={kernelName:Ri,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[a]=t,n=a.shape.slice(),{axis:s}=r;Ua(s,a.shape).forEach(l=>{n[l]=1});let i=U(e,n),o=L(i,da(a.shape,"float32"));return{x:()=>o}}},FB={kernelName:pl,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>pe(e,At(tm(r)))}}},MB={kernelName:Pi,outputsToSave:[!0],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(he(Se(1),At(r)),e)}}},$B={kernelName:Xn,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[a]=t,{reps:n}=r;return{x:()=>{let s=at(a);if(a.rank===1)for(let i=0;i<n[0];++i)s=ue(s,Oe(e,[i*a.shape[0]],[a.shape[0]]));else if(a.rank===2)for(let i=0;i<n[0];++i)for(let o=0;o<n[1];++o)s=ue(s,Oe(e,[i*a.shape[0],o*a.shape[1]],[a.shape[0],a.shape[1]]));else if(a.rank===3)for(let i=0;i<n[0];++i)for(let o=0;o<n[1];++o)for(let l=0;l<n[2];++l)s=ue(s,Oe(e,[i*a.shape[0],o*a.shape[1],l*a.shape[2]],[a.shape[0],a.shape[1],a.shape[2]]));else if(a.rank===4)for(let i=0;i<n[0];++i)for(let o=0;o<n[1];++o)for(let l=0;l<n[2];++l)for(let d=0;d<n[3];++d)s=ue(s,Oe(e,[i*a.shape[0],o*a.shape[1],l*a.shape[2],d*a.shape[3]],[a.shape[0],a.shape[1],a.shape[2],a.shape[3]]));else throw new Error(`Gradient for tile operation is not implemented for rank-${a.rank} tensors yet.`);return s}}}},PB={kernelName:Oi,gradFunc:(e,t,r)=>{let a=r,{perm:n}=a,s=m2(n);return{x:()=>rt(e,s)}}},OB={kernelName:fl,gradFunc:(e,t,r)=>{let a=r,{axis:n}=a;return{value:()=>nr(e,n)}}},zB={kernelName:eh,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>DB(e,r)}}};function DB(e,t){let r=Zn(t,at(t)),a=fu(e,r),n=xl(t,Se(0,"int32")),s=a.rank-n.rank;for(let o=0;o<s;++o)n=Ht(n,o+1);n=ln(n,da(a.shape,"bool"));let i=at(a);return zr(n,a,i)}var _B={kernelName:ml,gradFunc:e=>({x:()=>at(e)})},LB=[Gk,L_,B_,W_,V_,U_,G_,j_,H_,q_,K_,X_,J_,tL,rL,aL,nL,sL,iL,oL,lL,uL,pL,dL,fL,mL,gL,yL,AL,xL,iB,bL,vL,wL,kL,IL,TL,SL,CL,NL,EL,RL,FL,ML,$L,PL,OL,zL,DL,BL,n3,n3,WL,GL,qL,KL,XL,ZL,YL,JL,QL,eB,tB,rB,aB,s3,s3,nB,sB,oB,lB,uB,dB,pB,hB,cB,fB,mB,gB,yB,AB,xB,bB,vB,wB,kB,IB,i3,i3,o3,o3,SB,CB,TB,NB,EB,RB,FB,MB,$B,PB,OB,zB,_B];for(let e of LB)Dv(e);var Hk={};De(Hk,{maxNorm:()=>UB,minMaxNorm:()=>HB,nonNeg:()=>jB,unitNorm:()=>GB});var w1;function er(){return w1==null&&(w1=cn().epsilon()),w1}function un(){return"channelsLast"}var Bn=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Bn.prototype)}},en=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,en.prototype)}},H=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,H.prototype)}},Be=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,Be.prototype)}},qk=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,qk.prototype)}};function ko(e,t){if(Array.isArray(e)){let r=[];for(let a=0;a<t;a++)r=r.concat(e);return r}else{let r=new Array(t);return r.fill(e),r}}function wn(e,t){if(!e)throw new qk(t)}function l3(e,t){let r=0;for(let a of e)a===t&&r++;return r}function ea(e){return e.length===1?e[0]:e}function It(e){return Array.isArray(e)?e:[e]}function Wn(e){let t=e.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return t[0]!=="_"?t:"private"+t}function lo(e){return e.length<=1||e.indexOf("_")===-1?e:e.replace(/[_]+(\w|$)/g,(t,r)=>r.toUpperCase())}var La={};function D2(e){if(e==null)return null;let t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function H1(e){if(!(e==null||typeof e!="object"))if(Array.isArray(e))e.forEach(t=>H1(t));else{let t=Object.keys(e);for(let r of t){let a=e[r];a!=null&&typeof a=="object"&&(!Array.isArray(a)&&a.type==="ndarray"&&typeof a.value=="number"?e[r]=a.value:H1(a))}}}function fh(e,t={},r={},a="object",n=!1){if(typeof e=="string"){let s=e,i;if(s in r)i=r[s];else if(s in La)i=La[s];else if(i=t[s],i==null)throw new H(`Unknown ${a}: ${e}. This may be due to one of the following reasons:
|
|
1. The ${a} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
|
|
2. The custom ${a} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return i}else{let s=e;if(s.className==null||s.config==null)throw new H(`${a}: Improper config format: ${JSON.stringify(s)}.
|
|
'className' and 'config' must set.`);let i=s.className,o,l;if(i in r?[o,l]=r[i]:i in La?[o,l]=La.className:i in t&&([o,l]=t[i]),o==null)throw new H(`Unknown ${a}: ${i}. This may be due to one of the following reasons:
|
|
1. The ${a} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
|
|
2. The custom ${a} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(l!=null){let d={};for(let c of Object.keys(La))d[c]=La[c];for(let c of Object.keys(r))d[c]=r[c];let u=s.config;u.customObjects=d;let p={...La};for(let c of Object.keys(r))La[c]=r[c];H1(s.config);let h=l(o,s.config,r,n);return La={...p},h}else{let d={...La};for(let p of Object.keys(r))La[p]=r[p];let u=new o(s.config);return La={...d},u}}}function BB(e,t){return e<t?-1:e>t?1:0}function Sc(e,t){return-1*BB(e,t)}function Cs(e){if(e==null)return e;let t=[];for(let r of e)t.indexOf(r)===-1&&t.push(r);return t}function WB(e){if(e==null)throw new H(`Invalid value in obj: ${JSON.stringify(e)}`);for(let t in e)if(e.hasOwnProperty(t))return!1;return!0}function wl(e,t,r){if(r!=null&&e.indexOf(r)<0)throw new H(`${r} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function _2(e,t,r=0,a=1/0){return wn(r>=0),wn(a>=r),Array.isArray(e)&&e.length>=r&&e.length<=a&&e.every(n=>typeof n===t)}function pr(e,t){Array.isArray(e)?(w.assert(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((r,a)=>pr(r,`element ${a+1} of ${t}`))):w.assert(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${Kk(e)}.`)}function Kk(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>Kk(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function VB(e,t,r){let a=r!=null?r():w.now(),n;return(...s)=>{let i=r!=null?r():w.now();return i-a<t||(a=i,n=e(...s)),n}}function Xk(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}function L2(e,t){return q(()=>Tr(ke(L(e,e),t,!0)))}var mh=class extends de.Serializable{getConfig(){return{}}},B2=class extends mh{constructor(e){super();this.defaultMaxValue=2,this.defaultAxis=0,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return q(()=>{let t=L2(e,this.axis),r=pa(t,0,this.maxValue);return L(e,pe(r,ue(er(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};B2.className="MaxNorm";de.registerClass(B2);var W2=class extends mh{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return q(()=>pe(e,ue(er(),L2(e,this.axis))))}getConfig(){return{axis:this.axis}}};W2.className="UnitNorm";de.registerClass(W2);var V2=class extends mh{apply(e){return Fn(e)}};V2.className="NonNeg";de.registerClass(V2);var U2=class extends mh{constructor(e){super();this.defaultMinValue=0,this.defaultMaxValue=1,this.defaultRate=1,this.defaultAxis=0,this.minValue=e.minValue!=null?e.minValue:this.defaultMinValue,this.maxValue=e.maxValue!=null?e.maxValue:this.defaultMaxValue,this.rate=e.rate!=null?e.rate:this.defaultRate,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return q(()=>{let t=L2(e,this.axis),r=ue(L(this.rate,pa(t,this.minValue,this.maxValue)),L(1-this.rate,t));return L(e,pe(r,ue(er(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};U2.className="MinMaxNorm";de.registerClass(U2);var u3={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function rr(e){return D2(e)}function d3(e,t={}){return fh(e,de.SerializationMap.getMap().classNameMap,t,"constraint")}function ar(e){if(e==null)return null;if(typeof e=="string"){let t={className:e in u3?u3[e]:e,config:{}};return d3(t)}else return e instanceof mh?e:d3(e)}function UB(e){return new B2(e)}function GB(e){return new W2(e)}function jB(){return new V2}function HB(e){return new U2(e)}var Zk={};De(Zk,{constant:()=>mW,glorotNormal:()=>wW,glorotUniform:()=>vW,heNormal:()=>kW,heUniform:()=>IW,identity:()=>xW,leCunNormal:()=>SW,leCunUniform:()=>TW,ones:()=>fW,orthogonal:()=>CW,randomNormal:()=>yW,randomUniform:()=>gW,truncatedNormal:()=>AW,varianceScaling:()=>bW,zeros:()=>cW});var qB=["channelsFirst","channelsLast"],KB=["nearest","bilinear"],XB=["valid","same","causal"],ZB=["max","avg"],YB=["sum","mul","concat","ave"],Xl=new Map;function Ut(e){wl(qB,"DataFormat",e)}function JB(e){wl(KB,"InterpolationFormat",e)}function Pa(e){wl(XB,"PaddingMode",e)}function Yk(e){wl(ZB,"PoolMode",e)}var bp=[],p3="/";function mo(e,t){bp.push(e);try{let r=t();return bp.pop(),r}catch(r){throw bp.pop(),r}}function QB(){return bp.length===0?"":bp.join(p3)+p3}function Jk(e){if(!e7(e))throw new Error("Not a valid tensor name: '"+e+"'");return QB()+e}function Qk(e){if(!e7(e))throw new Error("Not a valid tensor name: '"+e+"'");Xl.has(e)||Xl.set(e,0);let t=Xl.get(e);if(Xl.set(e,Xl.get(e)+1),t>0){let r=`${e}_${t}`;return Xl.set(r,1),r}else return e}var eW=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function e7(e){return!!e.match(eW)}function tW(e){return e===parseInt(e.toString(),10)}function Ns(e,t,r){t==null&&(t=0),r==null&&(r=e.length);let a=1;for(let n=t;n<r;++n)a*=e[n];return a}function yu(e){if(e.length===0)return Number.NaN;let t=Number.POSITIVE_INFINITY;for(let r=0;r<e.length;r++){let a=e[r];a<t&&(t=a)}return t}function Ls(e){if(e.length===0)return Number.NaN;let t=Number.NEGATIVE_INFINITY;for(let r=0;r<e.length;r++){let a=e[r];a>t&&(t=a)}return t}function dn(e,t){if(t<e)throw new H(`end (${t}) < begin (${e}) is forbidden.`);let r=[];for(let a=e;a<t;++a)r.push(a);return r}function Sm(e,t){return me(e,t)}function gh(e,t=-1){let r=e.shape.slice();return t<0&&(t=r.length+t+1),r.splice(t,0,1),U(e,r)}function rW(e,t){return q(()=>{if(e.shape.length!==2)throw new H(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);let r=gh(e,1);return q1(r,[1,t,1])})}function aW(e){let t=[Ns(e.shape)];return U(e,t)}function nW(e){if(e.rank<=1)throw new H(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);let t=[e.shape[0],Ns(e.shape,1)];return U(e,t)}function go(e,t,r){return q(()=>{switch(e.rank){case 1:return pm(e,t,r);case 2:return C2(e,[t,0],[r,e.shape[1]]);case 3:return vl(e,[t,0,0],[r,e.shape[1],e.shape[2]]);case 4:return wo(e,[t,0,0,0],[r,e.shape[1],e.shape[2],e.shape[3]]);case 5:return Oe(e,[t,0,0,0,0],[r,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return Oe(e,[t,0,0,0,0,0],[r,e.shape[1],e.shape[2],e.shape[3],e.shape[4],e.shape[5]]);default:throw new H(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}})}function k1(e,t,r){return q(()=>{switch(e.rank){case 1:return pm(e,t,r);case 2:return C2(e,[0,t],[e.shape[0],r]);case 3:return vl(e,[0,0,t],[e.shape[0],e.shape[1],r]);case 4:return wo(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],r]);default:throw new H(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Tc(e,t,r,a){return q(()=>{switch(e.rank){case 1:return pm(e,t,r);case 2:switch(a){case 1:return go(e,t,r);case 2:return k1(e,t,r);default:throw new H(`The axis is not within the rank of the tensor ${a}`)}case 3:switch(a){case 1:return go(e,t,r);case 2:return vl(e,[0,t,0],[e.shape[0],r,e.shape[2]]);case 3:return k1(e,t,r);default:throw new H(`The axis is not within the rank of the tensor ${a}`)}case 4:switch(a){case 1:return go(e,t,r);case 2:return wo(e,[0,t,0,0],[e.shape[0],r,e.shape[2],e.shape[3]]);case 3:return wo(e,[0,0,t,0],[e.shape[0],e.shape[1],r,e.shape[3]]);case 4:return k1(e,t,r);default:throw new H(`The axis is not within the rank of the tensor ${a}`)}default:throw new H(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function G2(e,t=-1){let r;return t<0&&(r=e[0].rank,r!==0?t=r:t=0),t===e[0].rank&&(t=-1),kt(e,t)}function h3(e,t){switch(e.rank){case 1:return Hw([e,t]);case 2:return ed([e,t],0);case 3:return qw([e,t],0);case 4:return Kw([e,t],0);default:throw new H(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function q1(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new H(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return Wa(e,t)}function Tm(e,t=0,r=1,a,n){return mk(e,t,r,a,n)}function Sn(e,t,r,a){if(e.rank<2||t.rank<2)throw new Be(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);if(t.rank>=3){let n=e.shape.slice(-1)[0],s=t.shape.slice(-2)[0];if(n!==s)throw new Be(`If rank y >= 3, then the second last dim of y must equal the last dim of x but got x shape = ${e.shape} and y shape = ${t.shape}`)}if(e.rank===2&&t.rank===2)return _s.matMul({a:e,b:t,transposeA:!1,transposeB:!1,bias:a?K1(e.rank,a,un()):null,activation:r});{let n=e.shape.slice(),s=n.pop();e=U(e,[-1,s]);let i=t.shape.slice(),o=i.pop(),l=i.pop(),d=[...i,o],u=Array.from({length:t.rank},(f,m)=>m===0?t.rank-2:m<=t.rank-2?m-1:m);t=U(rt(t,u),[l,-1]);let p=[...n,...d],h=!1,c=!1;return U(_s.matMul({a:e,b:t,transposeA:h,transposeB:c,bias:a?K1(e.rank,a,un()):null,activation:r}),p)}}function t7(e,t,r){return q(()=>(Array.isArray(t)?t=St(t,"int32"):t=me(t,"int32"),fu(e,t,r)))}function yh(e){return L(e,e)}function K1(e,t,r){let a=t.shape;if(t.rank!==1&&t.rank!==e)throw new H(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(e===5){if(r==="channelsFirst")return a.length===1?U(t,[1,a[0],1,1,1]):U(t,[1,a[3],a[0],a[1],a[2]]);if(r==="channelsLast")return a.length===1?U(t,[1,1,1,1,a[0]]):U(t,[1].concat(a))}else if(e===4){if(r==="channelsFirst")return a.length===1?U(t,[1,a[0],1,1]):U(t,[1,a[2],a[0],a[1]]);if(r==="channelsLast")return a.length===1?U(t,[1,1,1,a[0]]):U(t,[1].concat(a))}else if(e===3){if(r==="channelsFirst")return a.length===1?U(t,[1,a[0],1]):U(t,[1,a[1],a[0]]);if(r==="channelsLast")return a.length===1?U(t,[1,1,a[0]]):U(t,[1].concat(a))}else if(e<3)return t;throw new H(`Unsupported input rank by biasAdd: ${t.rank}`)}function fn(e,t,r){return q(()=>(r==null&&(r=un()),Ut(r),ue(e,K1(e.rank,t,r))))}function sW(e,t=1){if(t!==1)throw new Be(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return uh(e)}function iW(e){return q(()=>pe(e,ue(Qt(e),1)))}function r7(e,t,r,a){return q(()=>Ek(e,t,r,a))}function oW(e){return q(()=>{let t=ue(.5,L(.2,e));return pa(t,0,1)})}function Ah(e,t,r=!1){return r?e():t()}var lW=["fanIn","fanOut","fanAvg"],uW=["normal","uniform","truncatedNormal"];function dW(e){wl(lW,"FanMode",e)}function pW(e){wl(uW,"Distribution",e)}var qa=class extends de.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}},j2=class extends qa{apply(e,t){return Vt(e,t)}};j2.className="Zeros";de.registerClass(j2);var Cm=class extends qa{apply(e,t){return da(e,t)}};Cm.className="Ones";de.registerClass(Cm);var H2=class extends qa{constructor(e){super();if(typeof e!="object")throw new H(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new H(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return q(()=>L(Se(this.value),da(e,t)))}getConfig(){return{value:this.value}}};H2.className="Constant";de.registerClass(H2);var q2=class extends qa{constructor(e){super();this.DEFAULT_MINVAL=-.05,this.DEFAULT_MAXVAL=.05,this.minval=e.minval||this.DEFAULT_MINVAL,this.maxval=e.maxval||this.DEFAULT_MAXVAL,this.seed=e.seed}apply(e,t){return nd(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}};q2.className="RandomUniform";de.registerClass(q2);var K2=class extends qa{constructor(e){super();this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Be(`randomNormal does not support dType ${t}.`);return Tm(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};K2.className="RandomNormal";de.registerClass(K2);var X2=class extends qa{constructor(e){super();this.DEFAULT_MEAN=0,this.DEFAULT_STDDEV=.05,this.mean=e.mean||this.DEFAULT_MEAN,this.stddev=e.stddev||this.DEFAULT_STDDEV,this.seed=e.seed}apply(e,t){if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Be(`truncatedNormal does not support dType ${t}.`);return fm(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};X2.className="TruncatedNormal";de.registerClass(X2);var Z2=class extends qa{constructor(e){super();this.gain=e.gain!=null?e.gain:1}apply(e,t){return q(()=>{if(e.length!==2||e[0]!==e[1])throw new H("Identity matrix initializer can only be used for 2D square matrices.");return L(this.gain,p2(e[0]))})}getConfig(){return{gain:this.gain}}};Z2.className="Identity";de.registerClass(Z2);function hW(e,t="channelsLast"){let r,a;if(Ut(t),e.length===2)r=e[0],a=e[1];else if([3,4,5].indexOf(e.length)!==-1){if(t==="channelsFirst"){let n=Ns(e,2);r=e[1]*n,a=e[0]*n}else if(t==="channelsLast"){let n=Ns(e,0,e.length-2);r=e[e.length-2]*n,a=e[e.length-1]*n}}else{let n=Ns(e);r=Math.sqrt(n),a=Math.sqrt(n)}return[r,a]}var aa=class extends qa{constructor(e){super();if(e.scale<0)throw new H(`scale must be a positive float. Got: ${e.scale}`);this.scale=e.scale==null?1:e.scale,this.mode=e.mode==null?"fanIn":e.mode,dW(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,pW(this.distribution),this.seed=e.seed}apply(e,t){let r=hW(e),a=r[0],n=r[1],s=this.scale;if(this.mode==="fanIn"?s/=Math.max(1,a):this.mode==="fanOut"?s/=Math.max(1,n):s/=Math.max(1,(a+n)/2),this.distribution==="normal"){let i=Math.sqrt(s);if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Be(`${this.getClassName()} does not support dType ${t}.`);return fm(e,0,i,t,this.seed)}else{let i=Math.sqrt(3*s);return nd(e,-i,i,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}};aa.className="VarianceScaling";de.registerClass(aa);var Nm=class extends aa{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return aa.className}};Nm.className="GlorotUniform";de.registerClass(Nm);var Em=class extends aa{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return aa.className}};Em.className="GlorotNormal";de.registerClass(Em);var Rm=class extends aa{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return aa.className}};Rm.className="HeNormal";de.registerClass(Rm);var Fm=class extends aa{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return aa.className}};Fm.className="HeUniform";de.registerClass(Fm);var Mm=class extends aa{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return aa.className}};Mm.className="LeCunNormal";de.registerClass(Mm);var $m=class extends aa{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return aa.className}};$m.className="LeCunNormal";de.registerClass($m);var Y2=class extends qa{constructor(e){super();if(this.DEFAULT_GAIN=1,this.gain=e.gain==null?this.DEFAULT_GAIN:e.gain,this.seed=e.seed,this.seed!=null)throw new Be("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return q(()=>{if(e.length<2)throw new Be("Shape must be at least 2D.");e[0]*e[1]>2e3&&console.warn(`Orthogonal initializer is being called on a matrix with more than 2000 (${e[0]*e[1]}) elements: Slowness may result.`);let r=e[0]>e[1]?[e[1],e[0]]:e,a=Tm(r,0,1,"float32"),n=Lk.gramSchmidt(a);return e[0]>e[1]&&(n=rt(n)),L(this.gain,n)})}getConfig(){return{gain:this.gain,seed:this.seed}}};Y2.className="Orthogonal";de.registerClass(Y2);var c3={constant:"Constant",glorotNormal:"GlorotNormal",glorotUniform:"GlorotUniform",heNormal:"HeNormal",heUniform:"HeUniform",identity:"Identity",leCunNormal:"LeCunNormal",leCunUniform:"LeCunUniform",ones:"Ones",orthogonal:"Orthogonal",randomNormal:"RandomNormal",randomUniform:"RandomUniform",truncatedNormal:"TruncatedNormal",varianceScaling:"VarianceScaling",zeros:"Zeros"};function f3(e,t={}){return fh(e,de.SerializationMap.getMap().classNameMap,t,"initializer")}function Pt(e){return D2(e)}function Ft(e){if(typeof e=="string"){let t=e in c3?c3[e]:e;if(t==="GlorotNormal")return new Em;if(t==="GlorotUniform")return new Nm;if(t==="HeNormal")return new Rm;if(t==="HeUniform")return new Fm;if(t==="LeCunNormal")return new Mm;if(t==="LeCunUniform")return new $m;{let r={};return r.className=t,r.config={},f3(r)}}else return e instanceof qa?e:f3(e)}function cW(){return new j2}function fW(){return new Cm}function mW(e){return new H2(e)}function gW(e){return new q2(e)}function yW(e){return new K2(e)}function AW(e){return new X2(e)}function xW(e){return new Z2(e)}function bW(e){return new aa(e)}function vW(e){return new Nm(e)}function wW(e){return new Em(e)}function kW(e){return new Rm(e)}function IW(e){return new Fm(e)}function SW(e){return new Mm(e)}function TW(e){return new $m(e)}function CW(e){return new Y2(e)}var a7={};De(a7,{Layer:()=>nt,RNN:()=>Qn,RNNCell:()=>vh,activation:()=>lU,add:()=>yU,alphaDropout:()=>eG,average:()=>AU,averagePooling1d:()=>ox,averagePooling2d:()=>lx,averagePooling3d:()=>ux,avgPool1d:()=>CU,avgPool2d:()=>EU,avgPool3d:()=>FU,avgPooling1d:()=>NU,avgPooling2d:()=>RU,avgPooling3d:()=>MU,batchNormalization:()=>IU,bidirectional:()=>HU,concatenate:()=>xU,conv1d:()=>QV,conv2d:()=>eU,conv2dTranspose:()=>tU,conv3d:()=>rU,conv3dTranspose:()=>aU,convLstm2d:()=>VU,convLstm2dCell:()=>UU,cropping2D:()=>sU,dense:()=>uU,depthwiseConv2d:()=>oU,dot:()=>kU,dropout:()=>dU,elu:()=>qV,embedding:()=>gU,flatten:()=>hU,gaussianDropout:()=>QU,gaussianNoise:()=>JU,globalAveragePooling1d:()=>$U,globalAveragePooling2d:()=>PU,globalMaxPool1d:()=>KU,globalMaxPool2d:()=>XU,globalMaxPooling1d:()=>r4,globalMaxPooling2d:()=>a4,gru:()=>zU,gruCell:()=>DU,input:()=>S7,inputLayer:()=>HV,layerNormalization:()=>SU,leakyReLU:()=>XV,lstm:()=>_U,lstmCell:()=>LU,masking:()=>tG,maxPool1d:()=>ZU,maxPool2d:()=>YU,maxPooling1d:()=>n4,maxPooling2d:()=>s4,maxPooling3d:()=>OU,maximum:()=>bU,minimum:()=>vU,multiply:()=>wU,permute:()=>mU,prelu:()=>ZV,reLU:()=>KV,repeatVector:()=>cU,reshape:()=>fU,rnn:()=>GU,separableConv2d:()=>nU,simpleRNN:()=>BU,simpleRNNCell:()=>WU,softmax:()=>YV,spatialDropout1d:()=>pU,stackedRNNCells:()=>jU,thresholdedReLU:()=>JV,timeDistributed:()=>qU,upSampling2d:()=>iU,zeroPadding2d:()=>TU});var NW=0;function n7(){return NW++}var Cc={};function Pm(e=""){return e in Cc||(Cc[e]=0),Cc[e]+=1,e+Cc[e].toString()}function X1(e){return Array.isArray(e)&&Array.isArray(e[0])}function nf(e){return e.length===0?[]:Array.isArray(e[0])?e:[e]}function Ve(e){let t;if(Array.isArray(e)){if(e.length!==1)throw new H(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function mt(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(e.length===1)return e=e,e[0];throw new H(`Expected exactly 1 Shape; got ${e.length}`)}else return e}function sf(e){let t=0;for(let r of e)r.shape.length===0?t+=1:t+=r.shape.reduce((a,n)=>a*n);return t}var m3="Variable",s7=class{constructor(e,t="float32",r=m3,a=!0,n=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=n7(),r=r==null?m3:r,this.originalName=Jk(r),this.name=Qk(this.originalName),this.trainable_=a,this.constraint=n,this.val=Ik(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),EW(this.val,e),this.val.id!==e.id&&(this.val.assign(e),this.constraint!=null&&this.val.assign(this.constraint.apply(this.val))),this}dispose(){this.assertNotDisposed(),this.val.dispose()}assertNotDisposed(){if(this.val.isDisposed)throw new Error(`LayersVariable ${this.name} is already disposed.`)}get trainable(){return this.trainable_}set trainable(e){this.trainable_=e,this.val.trainable=e}};function EW(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}function Z1(e){return e.map(t=>t.read())}function J2(e){e.forEach(t=>{t[0].write(t[1])})}var qt=class{constructor(e){this.dtype=e.dtype,this.shape=e.shape,e.shape!=null?this.ndim=e.shape.length:this.ndim=e.ndim,this.maxNDim=e.maxNDim,this.minNDim=e.minNDim,this.axes=e.axes||{}}},tn=class{constructor(e,t,r,a,n,s,i){this.dtype=e,this.shape=t,this.sourceLayer=r,this.inputs=a,this.callArgs=n,this.outputTensorIndex=i,this.id=n7(),s!=null&&(this.originalName=Jk(s),this.name=Qk(this.originalName)),this.rank=t.length}},RW=0,Om=class{constructor(e,t){this.callArgs=t,this.id=RW++,this.outboundLayer=e.outboundLayer,this.inboundLayers=e.inboundLayers,this.nodeIndices=e.nodeIndices,this.tensorIndices=e.tensorIndices,this.inputTensors=e.inputTensors,this.outputTensors=e.outputTensors,this.inputMasks=e.inputMasks,this.outputMasks=e.outputMasks,this.inputShapes=e.inputShapes,this.outputShapes=e.outputShapes;for(let r of e.inboundLayers)r!=null&&r.outboundNodes.push(this);e.outboundLayer.inboundNodes.push(this)}getConfig(){let e=[];for(let t of this.inboundLayers)t!=null?e.push(t.name):e.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:e,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}},FW=0,nt=class extends de.Serializable{constructor(e={}){super();this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=FW++,this.activityRegularizer=null,this.inputSpec=null,this.supportsMasking=!1,this._trainableWeights=[],this._nonTrainableWeights=[],this._losses=[],this._updates=[],this._built=!1,this.inboundNodes=[],this.outboundNodes=[];let t=e.name;if(!t){let r=this.getClassName();t=Wn(r)+"_"+Pm(r)}if(this.name=t,this.trainable_=e.trainable==null?!0:e.trainable,e.inputShape!=null||e.batchInputShape!=null){let r;if(e.batchInputShape!=null)r=e.batchInputShape;else if(e.inputShape!=null){let n=null;e.batchSize!=null&&(n=e.batchSize),r=[n].concat(e.inputShape)}this.batchInputShape=r;let a=e.dtype;a==null&&(a=e.inputDType),a==null&&(a="float32"),this.dtype=a}e.weights!=null?this.initialWeights=e.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(e,t){return e.name+"_ib-"+t.toString()}getNodeAtIndex(e,t){if(this.inboundNodes.length===0)throw new en(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new H(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return ea(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return ea(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new Bn(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer input" is ill-defined. Use \`getInputAt(nodeIndex)\` instead.`);if(this.inboundNodes.length===0)throw new Bn(`Layer ${this.name} is not connected, no input to return.`);return ea(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new Bn(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new Bn(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return ea(this.getNodeAtIndex(0,"output").outputTensors)}get losses(){return this._losses}calculateLosses(){return this.losses.map(e=>e())}get updates(){return this._updates}get built(){return this._built}set built(e){this._built=e}get trainable(){return this.trainable_}set trainable(e){this._trainableWeights.forEach(t=>t.trainable=e),this.trainable_=e}get trainableWeights(){return this.trainable_?this._trainableWeights.filter(e=>e.trainable):[]}set trainableWeights(e){this._trainableWeights=e}get nonTrainableWeights(){return this.trainable?this._trainableWeights.filter(e=>!e.trainable).concat(this._nonTrainableWeights):this._trainableWeights.concat(this._nonTrainableWeights)}set nonTrainableWeights(e){this._nonTrainableWeights=e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}get stateful(){return this._stateful}resetStates(){if(!this.stateful)throw new Error("Cannot call the resetStates() method of a non-stateful Layer object.")}assertInputCompatibility(e){if(e=It(e),this.inputSpec==null||this.inputSpec.length===0)return;let t=It(this.inputSpec);if(e.length!==t.length)throw new H(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let r=0;r<e.length;r++){let a=e[r],n=t[r];if(n==null)continue;let s=a.rank;if(n.ndim!=null&&s!==n.ndim)throw new H(`Input ${r} is incompatible with layer ${this.name}: expected ndim=${n.ndim}, found ndim=${s}`);if(n.maxNDim!=null&&s>n.maxNDim)throw new H(`Input ${r} is incompatible with layer ${this.name}: expected max_ndim=${n.maxNDim}, found ndim=${s}`);if(n.minNDim!=null&&s<n.minNDim)throw new H(`Input ${r} is incompatible with layer ${this.name}: expected min_ndim=${n.minNDim}, found ndim=${s}.`);if(n.dtype!=null&&a.dtype!==n.dtype)throw new H(`Input ${r} is incompatible with layer ${this.name} : expected dtype=${n.dtype}, found dtype=${a.dtype}.`);if(n.axes){let i=a.shape;for(let o in n.axes){let l=Number(o),d=n.axes[o],u=l>=0?i[l]:i[i.length+l];if(d!=null&&[d,null].indexOf(u)===-1)throw new H(`Input ${r} is incompatible with layer ${this.name}: expected axis ${l} of input shape to have value ${d} but got shape ${i}.`)}}if(n.shape!=null)for(let i=0;i<n.shape.length;++i){let o=n.shape[i],l=a.shape[i];if(o!=null&&l!=null&&o!==l)throw new H(`Input ${r} is incompatible with layer ${this.name}: expected shape=${n.shape}, found shape=${a.shape}.`)}}}call(e,t){return e}invokeCallHook(e,t){this._callHook!=null&&this._callHook(e,t)}setCallHook(e){this._callHook=e}clearCallHook(){this._callHook=null}apply(e,t){t=t||{},this.assertNotDisposed();let r=It(e),a=!0;for(let s of r)if(!(s instanceof tn)){a=!1;break}let n=!0;for(let s of r)if(s instanceof tn){n=!1;break}if(a===n)throw new H("Arguments to apply() must be all SymbolicTensors or all Tensors");return mo(this.name,()=>{if(!this.built){this.assertInputCompatibility(e);let s=[];for(let i of It(e))s.push(i.shape);this.build(ea(s)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&n&&(this._refCount=1)}if(this.assertInputCompatibility(e),n){let s=this.call(e,t),i=It(s),o=[];for(let l of i)r.indexOf(l)!==-1&&(l=l.clone()),o.push(l);if(s=ea(o),this.activityRegularizer!=null)throw new Be("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return s}else{let s=MW(e),i=this.computeOutputShape(s),o,l=$W(e);if(this.warnOnIncompatibleInputShape(Array.isArray(e)?s[0]:s),i!=null&&i.length>0&&Array.isArray(i[0])?o=i.map((d,u)=>new tn(l,d,this,It(e),t,this.name,u)):o=new tn(l,i,this,It(e),t,this.name),this.addInboundNode(e,o,null,null,s,i,t),this._refCount++,this.activityRegularizer!=null)throw new Be("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return o}})}warnOnIncompatibleInputShape(e){if(this.batchInputShape!=null)if(e.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(e)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let t=!1;this.batchInputShape.forEach((r,a)=>{r!=null&&e[a]!=null&&e[a]!==r&&(t=!0)}),t&&console.warn(`The shape of the input tensor (${JSON.stringify(e)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(this.inboundNodes==null||this.inboundNodes.length===0)throw new Bn(`The layer ${this.name} has never been called and thus has no defined output shape.`);let e=[];for(let t of this.inboundNodes){let r=JSON.stringify(t.outputShapes);e.indexOf(r)===-1&&e.push(r)}if(e.length===1){let t=this.inboundNodes[0].outputShapes;return Array.isArray(t)&&Array.isArray(t[0])&&t.length===1?t[0]:t}else throw new Bn(`The layer ${this.name} has multiple inbound nodes with different output shapes. Hence the notion of "output shape" is ill-defined for the layer.`)}countParams(){if(!this.built)throw new en(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return sf(this.weights)}build(e){this.built=!0}getWeights(e=!1){return Z1(e?this.trainableWeights:this.weights)}setWeights(e){q(()=>{let t=this.weights;if(t.length!==e.length)throw new H(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);if(t.length===0)return;let r=[],a=Z1(t);for(let n=0;n<a.length;++n){let s=a[n],i=t[n],o=e[n];if(!w.arraysEqual(s.shape,o.shape))throw new H(`Layer weight shape ${s.shape} not compatible with provided weight shape ${o.shape}`);r.push([i,o])}J2(r)})}addWeight(e,t,r,a,n,s,i,o){if(this._addedWeightNames.indexOf(e)!==-1)throw new H(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),r==null&&(r="float32"),this.fastWeightInitDuringBuild&&(a=o!=null?o():Ft("zeros"));let l=a.apply(t,r),d=new s7(l,r,e,s,i);return l.dispose(),n!=null&&this.addLoss(()=>n.apply(d.read())),s==null&&(s=!0),s?this._trainableWeights.push(d):this._nonTrainableWeights.push(d),d}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){e==null||Array.isArray(e)&&e.length===0||(e=It(e),this._losses!==void 0&&this._losses!==null&&this.losses.push(...e))}computeOutputShape(e){return e}computeMask(e,t){if(!this.supportsMasking){if(t!=null)if(Array.isArray(t))t.forEach(r=>{if(r!=null)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)});else throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);return null}return t}addInboundNode(e,t,r,a,n,s,i=null){let o=It(e);t=It(t),r=It(r),a=It(a),n=nf(n),s=nf(s);let l=[],d=[],u=[];for(let p of o)l.push(p.sourceLayer),d.push(p.nodeIndex),u.push(p.tensorIndex);new Om({outboundLayer:this,inboundLayers:l,nodeIndices:d,tensorIndices:u,inputTensors:o,outputTensors:t,inputMasks:r,outputMasks:a,inputShapes:n,outputShapes:s},i);for(let p=0;p<t.length;p++)t[p].sourceLayer=this,t[p].nodeIndex=this.inboundNodes.length-1,t[p].tensorIndex=p}getConfig(){let e={name:this.name,trainable:this.trainable};return this.batchInputShape!=null&&(e.batchInputShape=this.batchInputShape),this.dtype!=null&&(e.dtype=this.dtype),e}disposeWeights(){return this.weights.forEach(e=>e.dispose()),this.weights.length}assertNotDisposed(){if(this._refCount===0)throw new Error(`Layer '${this.name}' is already disposed.`)}dispose(){if(!this.built)throw new Error(`Cannot dispose Layer ${this.name} because it has not been built yet.`);if(this._refCount===null)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let e=0;return--this._refCount===0&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}}};function MW(e){e=It(e);let t=[];for(let r of e)t.push(r.shape);return ea(t)}function $W(e){return"float32"}function i7(e,t,r){if((t==null||r!=null&&r>0)&&(t=e.sourceLayer,r=e.nodeIndex),t.inboundNodes.length===0)return[e];{let a=t.inboundNodes[r];if(a.inboundLayers.length===0)return a.inputTensors;{let n=[];for(let s=0;s<a.inboundLayers.length;s++){let i=a.inputTensors[s],o=a.inboundLayers[s],l=a.nodeIndices[s],d=i7(i,o,l);for(let u of d)n.indexOf(u)===-1&&n.push(u)}return n}}}var od=class extends nt{constructor(e){super({dtype:e.dtype,name:e.name!=null?e.name:Pm("input").toString()});if(e.batchSize==null&&(e.batchSize=null),e.sparse==null&&(e.sparse=!1),this.trainable=!1,this.built=!0,this.sparse=e.sparse,e.inputShape!=null&&e.batchInputShape!=null)throw new H("Only provide the inputShape OR batchInputShape argument to inputLayer, not both at the same time.");let t=e.batchInputShape;if(t==null){if(e.inputShape==null)throw new H("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(e.batchSize!=null)throw new H("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");let r=e.dtype||"float32";this.batchInputShape=t,this.dtype=r,this.inputSpec=[{shape:t}];let a=new tn(this.dtype,this.batchInputShape,this,[],{},this.name);a.nodeIndex=0,a.tensorIndex=0,new Om({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[a],outputTensors:[a],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new H(`Cannot pass any input to an InputLayer's apply() method. InputLayer name: ${this.name}`)}dispose(){return{refCountAfterDispose:this._refCount,numDisposedVariables:0}}getConfig(){return{batchInputShape:this.batchInputShape,dtype:this.dtype,sparse:this.sparse,name:this.name}}};od.className="InputLayer";de.registerClass(od);function o7(e){if(e.batchShape==null&&e.shape==null)throw new Error("Please provide to Input either a `shape` or a `batchShape` argument. Note that `shape` does not include the batch dimension.");if(e.batchShape!=null&&e.shape!=null)throw new H("Please provide either a `shape` or `batchShape` argument to Input, but not both.");let t=e.batchShape;e.shape!=null&&t==null&&(t=[null].concat(e.shape));let r=e.dtype;return r==null&&(r="float32"),new od({batchInputShape:t,name:e.name,dtype:r,sparse:e.sparse}).inboundNodes[0].outputTensors[0]}async function ws(e){if(e==null)return;let t=[],r=[],a=[];for(let n in e){let s=e[n];if(typeof s!="number"){let i=s;t.push(i.data()),r.push(n),a.push(i)}}if(t.length>0){let n=await Promise.all(t);for(let s=0;s<n.length;++s)e[r[s]]=n[s][0];re(a)}}function l7(e){if(e!=null)for(let t in e){let r=e[t];typeof r!="number"&&r.dispose()}}var PW=125,Au=class{constructor(){this.validationData=null}setParams(e){this.params=e}async onEpochBegin(e,t){}async onEpochEnd(e,t){}async onBatchBegin(e,t){}async onBatchEnd(e,t){}async onTrainBegin(e){}async onTrainEnd(e){}setModel(e){}},u7=class{constructor(e,t=10){e==null&&(e=[]),this.callbacks=e,this.queueLength=t}append(e){this.callbacks.push(e)}setParams(e){for(let t of this.callbacks)t.setParams(e)}setModel(e){for(let t of this.callbacks)t.setModel(e)}async onEpochBegin(e,t){t==null&&(t={});for(let r of this.callbacks)await r.onEpochBegin(e,t)}async onEpochEnd(e,t){t==null&&(t={});for(let r of this.callbacks)await r.onEpochEnd(e,t)}async onBatchBegin(e,t){t==null&&(t={});for(let r of this.callbacks)await r.onBatchBegin(e,t)}async onBatchEnd(e,t){t==null&&(t={});for(let r of this.callbacks)await r.onBatchEnd(e,t)}async onTrainBegin(e){e==null&&(e={});for(let t of this.callbacks)await t.onTrainBegin(e)}async onTrainEnd(e){e==null&&(e={});for(let t of this.callbacks)await t.onTrainEnd(e)}},OW=class extends Au{constructor(){super()}async onEpochBegin(e){this.seen=0,this.totals={}}async onBatchEnd(e,t){t==null&&(t={});let r=t.size==null?0:t.size;this.seen+=r;for(let a in t){let n=t[a];if(typeof n=="number")this.totals.hasOwnProperty(a)||(this.totals[a]=0),this.totals[a]=this.totals[a]+n*r;else{let s;a in this.totals?s=this.totals[a]:this.totals[a]=0;let i=q(()=>ue(this.totals[a],L(n,r)));this.totals[a]=i,s!=null&&s.dispose()}}}async onEpochEnd(e,t){if(t!=null)for(let r of this.params.metrics)this.totals[r]!=null&&(typeof this.totals[r]=="number"?t[r]=this.totals[r]/this.seen:q(()=>{let a=L(pe(1,this.seen),this.totals[r]);t[r]=a,this.totals[r].dispose(),dr(t[r])}))}},d7=class extends Au{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){t==null&&(t={}),this.epoch.push(e);for(let r in t)this.history[r]==null&&(this.history[r]=[]),this.history[r].push(t[r])}async syncData(){let e=[],t=[],r=[];for(let n in this.history){let s=this.history[n];for(let i=0;i<s.length;++i)if(typeof s[i]!="number"){let o=s[i];e.push(o.data()),t.push(n),r.push(i)}}let a=await Promise.all(e);for(let n=0;n<a.length;++n)this.history[t[n]][r[n]].dispose(),this.history[t[n]][r[n]]=a[n][0]}},p7=class extends Au{constructor(e,t){super();if(this.currentEpoch=0,this.nowFunc=e.nowFunc,this.nextFrameFunc=e.nextFrameFunc||Bk,this.yieldEvery=t||"auto",this.yieldEvery==="auto"&&(this.yieldEvery=PW),this.yieldEvery==="never"&&e.onYield!=null)throw new Error("yieldEvery is `never` but you provided an `onYield` callback. Either change `yieldEvery` or remove the callback");w.isNumber(this.yieldEvery)&&(this.maybeWait=VB(this.maybeWait.bind(this),this.yieldEvery,this.nowFunc)),this.trainBegin=e.onTrainBegin,this.trainEnd=e.onTrainEnd,this.epochBegin=e.onEpochBegin,this.epochEnd=e.onEpochEnd,this.batchBegin=e.onBatchBegin,this.batchEnd=e.onBatchEnd,this.yield=e.onYield}async maybeWait(e,t,r){let a=[];this.yield!=null&&(await ws(r),a.push(this.yield(e,t,r))),a.push(this.nextFrameFunc()),await Promise.all(a)}async onEpochBegin(e,t){this.currentEpoch=e,this.epochBegin!=null&&(await ws(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){let r=[];this.epochEnd!=null&&(await ws(t),r.push(this.epochEnd(e,t))),this.yieldEvery==="epoch"&&r.push(this.nextFrameFunc()),await Promise.all(r)}async onBatchBegin(e,t){this.batchBegin!=null&&(await ws(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){let r=[];this.batchEnd!=null&&(await ws(t),r.push(this.batchEnd(e,t))),this.yieldEvery==="batch"?r.push(this.nextFrameFunc()):w.isNumber(this.yieldEvery)&&r.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(r)}async onTrainBegin(e){this.trainBegin!=null&&(await ws(e),await this.trainBegin(e))}async onTrainEnd(e){this.trainEnd!=null&&(await ws(e),await this.trainEnd(e))}};function h7(e,t){return e==null&&(e={}),e instanceof Au?[e]:Array.isArray(e)&&e[0]instanceof Au?e:It(e).map(r=>new p7(r,t))}var bn=class{constructor(){}static registerCallbackConstructor(e,t){w.assert(e>=0&&Number.isInteger(e),()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`),bn.checkForDuplicate(t),bn.constructors[e]==null&&(bn.constructors[e]=[]),bn.constructors[e].push(t)}static checkForDuplicate(e){for(let t in bn.constructors)bn.constructors[+t].forEach(r=>{if(r===e)throw new H("Duplicate callback constructor.")})}static clear(){bn.constructors={}}static createCallbacks(e){let t=[];for(let r in bn.constructors){let a=+r;e>=a&&t.push(...bn.constructors[a])}return t.map(r=>new r)}},Q2=bn;Q2.constructors={};function c7(e,t,r,a,n,s,i,o,l){let d=new d7,u=[new OW,...Q2.createCallbacks(t)];e!=null&&u.push(...e),u.push(d);let p=new u7(u);return p.setParams({epochs:r,initialEpoch:a,samples:n,steps:s,batchSize:i,verbose:t,doValidation:o,metrics:l}),{callbackList:p,history:d}}function nn(e,t={},r=!1){return fh(e,de.SerializationMap.getMap().classNameMap,t,"layer",r)}function of(e,t){return q(()=>{e.dtype!=="float32"&&(e=me(e,"float32"));let r=ke(yh(e),t,!0),a=td(r.shape,er()),n=Tr(Zn(r,a));return pe(e,n)})}function kl(e,t){return q(()=>Wt(yh(he(t,e)),-1))}function zm(e,t){return q(()=>Wt(Qt(he(t,e)),-1))}function ld(e,t){return q(()=>{let r=he(e,t),a=pa(Qt(e),er(),Number.MAX_VALUE),n=Qt(pe(r,a));return L(100,Wt(n,-1))})}function zW(e,t){return q(()=>{let r=pa(t,er(),Number.MAX_VALUE),a=Ea(ue(1,r)),n=pa(e,er(),Number.MAX_VALUE),s=Ea(ue(1,n));return Wt(yh(he(a,s)),-1)})}function DW(e,t){return q(()=>{let r=Zn(0,he(1,L(e,t)));return Wt(yh(r),-1)})}function _W(e,t){return q(()=>{let r=Zn(0,he(1,L(e,t)));return Wt(r,-1)})}function LW(e,t){return q(()=>{let r=ke(L(e,t),-1),a=hr(L(he(1,e),t),-1);return Zn(0,ue(1,he(a,r)))})}function BW(e,t){return q(()=>{let r=Math.log(2),a=he(t,e),n=he(ue(a,rd(L(-2,a))),r);return Wt(n,-1)})}function Mp(e,t,r=!1){return q(()=>{if(r)t=sd(t);else{let a=ke(t,t.shape.length-1,!0);t=pe(t,a)}return t=pa(t,er(),1-er()),zt(ke(L(me(e,"float32"),Ea(t)),t.shape.length-1))})}function lf(e,t,r=!1){return q(()=>{let a=me(dh(aW(e)),"int32");t=pa(t,er(),1-er());let n=t.shape,s=U(Ep(a,n[n.length-1]),n);return Mp(s,t,r)})}function WW(e,t){if(!w.arraysEqual(e.shape,t.shape))throw new H(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return q(()=>{let r=Fn(t),a=zt(Qt(t));return ue(he(r,L(t,e)),nm(Na(a)))})}function Dm(e,t){return q(()=>{let r;return r=pa(t,er(),1-er()),r=Ea(pe(r,he(1,r))),Wt(WW(e,r),-1)})}function VW(e,t){return q(()=>{let r=pa(e,er(),1),a=pa(t,er(),1);return ke(L(e,Ea(pe(r,a))),-1)})}function UW(e,t){return q(()=>{let r=Ea(ue(er(),t));return Wt(he(t,L(e,r)),-1)})}function eA(e,t){return q(()=>{let r=of(e,-1),a=of(t,-1),n=L(r,a);return zt(ke(n,-1))})}var uf={meanSquaredError:kl,meanAbsoluteError:zm,meanAbsolutePercentageError:ld,meanSquaredLogarithmicError:zW,squaredHinge:DW,hinge:_W,categoricalHinge:LW,logcosh:BW,categoricalCrossentropy:Mp,sparseCategoricalCrossentropy:lf,binaryCrossentropy:Dm,kullbackLeiblerDivergence:VW,poisson:UW,cosineProximity:eA};function I1(e){if(typeof e=="string"){if(e in uf)return uf[e];let t=`Unknown loss ${e}`;throw e.toLowerCase().includes("softmaxcrossentropy")&&(t=`Unknown loss ${e}. Use "categoricalCrossentropy" as the string name for tf.losses.softmaxCrossEntropy`),new H(t)}else return e}function tA(e,t){return q(()=>{let r=L(.5,Ra(t)),a=Sm(fa(t,r),e.dtype);return Wt(Ca(e,a),-1)})}function rA(e,t){return q(()=>Sm(Ca(Ta(e,-1),Ta(t,-1)),"float32"))}function f7(e,t){return q(()=>me(ke(ln(Ca(e,1),Ca(t,1))),"float32"))}function GW(e,t){return q(()=>me(ke(ln(Ca(e,1),Ca(t,0))),"float32"))}function jW(e,t){return q(()=>me(ke(ln(Ca(e,0),Ca(t,1))),"float32"))}function m7(e,t){return q(()=>{let r=f7(e,t),a=jW(e,t),n=ue(r,a);return me(zr(fa(n,0),pe(r,n),0),"float32")})}function HW(e,t){return q(()=>{let r=f7(e,t),a=GW(e,t),n=ue(r,a);return me(zr(fa(n,0),pe(r,n),0),"float32")})}function g7(e,t){return Dm(e,t)}function y7(e,t){return e.rank===t.rank&&(e=Ye(e,[e.rank-1])),t=Ta(t,-1),t.dtype!==e.dtype&&(t=me(t,e.dtype)),me(Ca(e,t),"float32")}var qW=kl,KW=kl,XW=zm,ZW=zm,YW=ld,JW=ld,aA=Mp,QW=eA,A7=lf,df={binaryAccuracy:tA,categoricalAccuracy:rA,precision:m7,categoricalCrossentropy:aA,sparseCategoricalCrossentropy:A7,mse:qW,MSE:KW,mae:XW,MAE:ZW,mape:YW,MAPE:JW,cosine:QW};function eV(e){if(typeof e=="string"&&e in df)return df[e];if(typeof e!="string"&&e!=null)return e;throw new H(`Unknown metric ${e}`)}function Nc(e){if(wn(e!==null,`Unknown LossOrMetricFn ${e}`),typeof e=="string")return e;{let t;for(let r of Object.keys(uf))if(uf[r]===e){t=r;break}if(t!==void 0)return t;for(let r of Object.keys(df))if(df[r]===e){t=r;break}return t!==void 0?t:e.name}}function tV(e){let t={Adagrad:()=>so.adagrad(.01),Adadelta:()=>so.adadelta(1,.95,er()),Adam:()=>so.adam(.001,.9,.999,er()),Adamax:()=>so.adamax(.002,.9,.999,er(),0),RMSProp:()=>so.rmsprop(.001,.9,0,er()),SGD:()=>so.sgd(.01)};if(t.adagrad=t.Adagrad,t.adadelta=t.Adadelta,t.adam=t.Adam,t.adamax=t.Adamax,t.rmsprop=t.RMSProp,t.sgd=t.SGD,e in t)return t[e]();throw new H(`Unknown Optimizer ${e}`)}var g3=1*1024*1024;function y3(e,t,r=!1){if(e==null||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype||!Y1(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(r){let a=JSON.stringify(e);a.length>g3&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${a.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= ${g3}.`)}}function Y1(e){if(e===null)return!0;if(typeof e=="object")if(Object.getPrototypeOf(e)===Object.prototype){let t=Object.keys(e);for(let r of t)if(typeof r!="string"||!Y1(e[r]))return!1;return!0}else if(Array.isArray(e)){for(let t of e)if(!Y1(t))return!1;return!0}else return!1;else{let t=typeof e;return t==="string"||t==="number"||t==="boolean"}}function rV(e,t,r,a=console.log){let n=nV(e),s=["Layer (type)","Input Shape","Output shape","Param #"];n?(t=t||90,r=r||[.32,.61,.89,1]):(t=t||115,r=r||[.24,.48,.7,.8,1]),r[r.length-1]<=1&&(r=r.map(u=>Math.floor(t*u)));let i;if(!n){s.push("Receives inputs"),i=[];for(let u in e.nodesByDepth)i.push(...e.nodesByDepth[u])}a("_".repeat(t)),pf(s,r,a),a("=".repeat(t));let o=e.layers;for(let u=0;u<o.length;++u)n?sV(o[u],r,a):iV(o[u],r,i,a),a((u===o.length-1?"=":"_").repeat(t));e.checkTrainableWeightsConsistency();let l=aV(e),d=sf(e.nonTrainableWeights);a(`Total params: ${l+d}`),a(`Trainable params: ${l}`),a(`Non-trainable params: ${d}`),a("_".repeat(t))}function aV(e){let t;return e.collectedTrainableWeights!=null?t=sf(e.collectedTrainableWeights):t=sf(e.trainableWeights),t}function nV(e){let t=!0,r=[],a=[];for(let n in e.nodesByDepth)r.push(e.nodesByDepth[n]);for(let n of r){if(n.length>1||n.length===1&&n[0].inboundLayers.length>1){t=!1;break}a.push(...n)}if(t)for(let n of e.layers){let s=!1;for(let i of n.inboundNodes)if(a.indexOf(i)!==-1)if(s){t=!1;break}else s=!0;if(!t)break}return t}function pf(e,t,r=console.log){let a="";for(let n=0;n<e.length;++n)n>0&&(a=a.slice(0,a.length-1)+" "),a+=e[n],a=a.slice(0,t[n]),a+=" ".repeat(t[n]-a.length);r(a)}function sV(e,t,r){let a,n;try{n=e.inboundNodes.map(l=>JSON.stringify(l.inputShapes)).join(",")}catch(l){n="multiple"}try{a=JSON.stringify(e.outputShape)}catch(l){a="multiple"}let s=e.name,i=e.getClassName(),o=[`${s} (${i})`,n,a,e.countParams().toString()];pf(o,t,r)}function iV(e,t,r,a){let n,s;try{s=e.inboundNodes.map(p=>JSON.stringify(p.inputShapes)).join(",")}catch(p){s="multiple"}try{n=JSON.stringify(e.outputShape)}catch(p){n="multiple"}let i=[];for(let p of e.inboundNodes)if(!(r!=null&&r.length>0&&r.indexOf(p)===-1))for(let h=0;h<p.inboundLayers.length;++h){let c=p.inboundLayers[h].name,f=p.nodeIndices[h],m=p.tensorIndices[h];i.push(`${c}[${f}][${m}]`)}let o=e.name,l=e.getClassName(),d=i.length===0?"":i[0],u=[`${o} (${l})`,s,n,e.countParams().toString(),d];pf(u,t,a);for(let p=1;p<i.length;++p)pf(["","","","",i[p]],t,a)}function x7(e,t,r){return(e==="inboundNodes"||e==="outputLayers"||e==="inputLayers")&&t===0&&typeof r=="string"}function $p(e,t){if(e===null)return null;if(typeof e=="string")return lo(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){let r=[],a=e.length;for(let n=0;n<a;++n){let s=e[n];x7(t,n,s)?r.push(s):r.push($p(s,t))}return r}else{let r={};for(let a of Object.keys(e)){let n=e[a];if(a==="name"&&typeof n=="string")r[a]=n;else{let s=lo(a);r[s]=$p(n,s)}}return r}}function J1(e,t){if(e==null)return null;if(typeof e=="string")return Wn(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){let r=[],a=e.length;for(let n=0;n<a;++n){let s=e[n];x7(t,n,s)?r.push(s):r.push(J1(s,t))}return r}else{let r={};for(let a of Object.keys(e)){let n=e[a],s=Wn(a);(a==="name"||a==="className")&&typeof n=="string"?r[s]=n:r[s]=J1(n,a)}return r}}var nA="0.0.0";function oV(e,t){if(e.dtype==null||e.dtype===t.dtype)return t;try{return me(t,e.dtype)}catch(r){throw new H(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${e.name}' (${e.dtype}).`)}}var ho=class{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof ho)for(let t in e.id2Value)this.id2Value[t]=e.id2Value[t],t in e.id2Mask&&(this.id2Mask[t]=e.id2Mask[t]);else{if(e==null)return;for(let t of e)this.add(t.key,t.value)}}add(e,t,r){if(this.id2Value[e.id]==null)this.id2Value[e.id]=oV(e,t),this.name2Id[e.name]=e.id,r!=null&&(this.id2Mask[e.id]=r);else throw new H(`Duplicate key: name=${e.name}, id=${e.id}`);return this}addFeed(e){this.add(e.key,e.value)}hasKey(e){return this.id2Value[e.id]!=null}names(){return Object.keys(this.name2Id)}getValue(e){if(e instanceof tn){if(this.id2Value[e.id]==null)throw new H(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}else{let t=this.name2Id[e];if(t==null)throw new H(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof tn){if(this.id2Value[e.id]==null)throw new H(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}else{let t=this.name2Id[e];if(t==null)throw new H(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){this.id2Mask!=null&&re(this.id2Mask)}},S1={},A3={};function dp(e,t,r,a){let n=r==null?!1:r.training,s=Array.isArray(e),i=s?e:[e],o=i.map(f=>f.name),l=[],d=t.names();for(let f of o)d.indexOf(f)!==-1?l.push(t.getValue(f)):l.push(null);a!=null&&(a.maxNumTensors=-1/0,a.minNumTensors=1/0);let u=o.join(",")+"|"+t.names().join(","),p,h;if(S1[u]==null){let f=lV(i,t);p=f.sorted,h=f.recipientCounts,S1[u]=p,A3[u]=h}p=S1[u],h={},n||Object.assign(h,A3[u]);let c=new ho(t);for(let f=0;f<p.length;++f){if(a!=null){let R=tf().numTensors;R>a.maxNumTensors&&(a.maxNumTensors=R),R<a.minNumTensors&&(a.minNumTensors=R)}let m=p[f],g=m.sourceLayer;if(g instanceof od)continue;let y=[],A=[],x=[],b=!1;for(let R of m.inputs){let z=c.getValue(R),M=c.getMask(R);y.push(z),A.push(M),M!=null&&(b=!0),n||(h[R.name]--,h[R.name]===0&&!t.hasKey(R)&&o.indexOf(R.name)===-1&&!z.isDisposed&&R.sourceLayer.stateful!==!0&&x.push(z))}b&&(r=r||{},r.mask=A[0]);let v=It(g.apply(y,r)),C=null;g.supportsMasking&&(C=g.computeMask(y,A));let T=dV(m),E=Array.isArray(T)?T:[T];for(let R=0;R<E.length;++R){c.hasKey(E[R])||c.add(E[R],v[R],Array.isArray(C)?C[0]:C);let z=o.indexOf(E[R].name);z!==-1&&(l[z]=v[R])}n||re(x)}return c.disposeMasks(),s?l:l[0]}function lV(e,t){w.assert(e!=null&&e.length>0,()=>"Expected at least one fetch, got none");let r=[],a={};if(e.length===1){let n=x3(e[0],t);r=n.sorted,a=n.recipientMap}else{let n=new Set;for(let s of e){let{sorted:i,recipientMap:o}=x3(s,t);for(let l of i)n.has(l.name)||(r.push(l),n.add(l.name));for(let l in o)a[l]==null&&(a[l]=new Set),o[l].forEach(d=>a[l].add(d))}}return{sorted:r,recipientCounts:uV(a)}}function uV(e){let t={};for(let r in e)t[r]=e[r].size;return t}function x3(e,t){let r=new Set,a=[],n={};for(let o of t.names())r.add(o);let s=[],i=[];for(s.push(e);s.length>0;){let o=s[s.length-1];if(r.has(o.name)){s.pop();continue}let l=i[i.length-1]===s.length-1;if(o.inputs.length===0||l)s.pop(),a.push(o),r.add(o.name),l&&i.pop();else{i.push(s.length-1);for(let d of o.inputs)n[d.name]==null&&(n[d.name]=new Set),n[d.name].add(o.name),!r.has(d.name)&&s.push(d)}}return{sorted:a,recipientMap:n}}function dV(e){let t;if(e.sourceLayer.inboundNodes.length===1)t=e.sourceLayer.output;else{let r=null;for(let a=0;a<e.sourceLayer.inboundNodes.length;++a)for(let n of e.sourceLayer.inboundNodes[a].outputTensors)if(n.id===e.id){r=a;break}t=e.sourceLayer.getOutputAt(r)}return t}var vn=class extends nt{constructor(e){super({});if(this.containerNodes=new Set,this.name=e.name,this.name==null){let y=this.getClassName().toLowerCase();this.name=Pm(y)}if(this.supportsMasking=!1,this.trainable_=!0,Array.isArray(e.inputs)?this.inputs=e.inputs.slice():this.inputs=[e.inputs],Array.isArray(e.outputs)?this.outputs=e.outputs.slice():this.outputs=[e.outputs],Cs(this.inputs).length!==this.inputs.length)throw new H(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(y=>y.name)}`);Cs(this.outputs).length!==this.outputs.length&&console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map(y=>y.name)}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(let y of this.outputs){let A=y.sourceLayer,x=y.nodeIndex,b=y.tensorIndex;this.outputLayers.push(A),this.outputLayersNodeIndices.push(x),this.outputLayersTensorIndices.push(b)}for(let y of this.inputs){let A=y.sourceLayer,x=y.nodeIndex,b=y.tensorIndex;wn(x===0,"input layer has >1 nodes"),wn(b===0,"input layer has >1 tensors"),this.inputLayers.push(A),this.inputLayersNodeIndices.push(x),this.inputLayersTensorIndices.push(b)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let y=0;y<this.inputLayers.length;y++){let A=this.inputLayers[y];if(!(A instanceof od))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${y} (0-based) originates from layer type ${A.getClassName()}.`);this.inputNames.push(A.name),this.feedInputShapes.push(A.batchInputShape),this.feedInputNames.push(A.name)}for(let y of this.outputLayers)this.outputNames.push(y.name);this.internalInputShapes=this.inputs.map(y=>y.shape),this.internalOutputShapes=this.outputs.map(y=>y.shape);let t={},r={},a={},n={},s={},i=[],o=(y,A,x,b,v,C)=>{(b==null||v==null||C==null)&&(b=y.sourceLayer,v=y.nodeIndex,C=y.tensorIndex);let T=b.inboundNodes[v];if(x.indexOf(T)!==-1)throw new en(`The tensor ${y.name} at layer "${b.name}" is part of a cycle.`);if(A.indexOf(T)!==-1)return;this.containerNodes.add(vn.nodeKey(b,v)),b.id in s||(s[b.id]=Object.keys(s).length),x.indexOf(T)===-1&&x.push(T);let E=T.inboundLayers.length;for(let R=0;R<E;R++){let z=T.inputTensors[R],M=T.inboundLayers[R],I=T.nodeIndices[R],D=T.tensorIndices[R];o(z,A,x,M,I,D)}for(A.push(T);x.indexOf(T)>=0;)x.splice(x.indexOf(T),1);i.push(T)},l=[],d=[];for(let y of this.outputs)o(y,l,d);let u=i.slice().reverse();for(let y of u){r[y.id]=y,y.id in t||(t[y.id]=0);let A=t[y.id],x=a[y.outboundLayer.id]==null?0:a[y.outboundLayer.id];A=Math.max(A,x),a[y.outboundLayer.id]=A,n[y.outboundLayer.id]=y.outboundLayer,t[y.id]=A;for(let b=0;b<y.inboundLayers.length;b++){let v=y.inboundLayers[b],C=y.nodeIndices[b],T=v.inboundNodes[C],E=t[T.id]==null?0:t[T.id];t[T.id]=Math.max(A+1,E),r[T.id]=T}}let p={};for(let y in t){let A=t[y];A in p||(p[A]=[]),p[A].push(r[y])}let h={};for(let y in a){let A=a[y];A in h||(h[A]=[]),h[A].push(n[y])}let c=Object.keys(h).map(y=>parseInt(y,10)).sort(Sc);this.layers=[];for(let y of c){let A=h[y];A.sort((x,b)=>{let v=s[x.id],C=s[b.id];return v<C?-1:v>C?1:0});for(let x of A)x instanceof vn&&this.internalContainerRefs.push(x),this.layers.push(x)}this.layersByDepth=h,c=Object.keys(p).map(y=>parseInt(y,10)).sort(Sc);let f=this.inputs.slice(),m=[];for(let y of c)for(let A of p[y]){let x=A.outboundLayer;if(x!=null){for(let b of A.inputTensors)if(f.indexOf(b)===-1)throw new en(`Graph disconnected: cannot obtain value for tensor ${b} at layer "${x.name}". The following previous layers were accessed without issue: ${m}`);for(let b of A.outputTensors)f.push(b);m.push(x.name)}}this.nodesByDepth=p;let g=this.layers.map(y=>y.name);for(let y of g){let A=g.filter(x=>x===y).length;if(A!==1)throw new en(`The name "${y}" is used ${A} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new Om({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map(y=>null),outputMasks:this.outputs.map(y=>null),inputShapes:this.inputs.map(y=>y.shape),outputShapes:this.outputs.map(y=>y.shape)}),this.built=!0,this._refCount=1}assertNotDisposed(){if(this._refCount===0)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();let e={refCountAfterDispose:null,numDisposedVariables:0};if(--this._refCount===0){for(let t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(let t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}set trainable(e){this.layers.forEach(t=>{t._trainableWeights.forEach(r=>r.trainable=e)}),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new H("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let e=[];for(let t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){let e=[];for(let t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){let t=[];for(let r of this.layers)t.push(...r.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){let r={},a=0;for(let s of this.layers)for(let i of s.weights){if(r[i.originalName]!=null)throw new H(`Duplicate weight name: ${i.originalName}`);r[i.originalName]=i,a++}let n=[];for(let s in e){let i=s;if(r[s]==null){let o=s.split("/");i=o.slice(0,-2).concat([o[o.length-1]]).join("/")}if(r[i]!=null)n.push([r[i],e[s]]);else if(t)throw new H(`Provided weight data has no target variable: ${s}`);delete r[i]}if(t){let s=[];for(let i in r)s.push(i);if(s.length>0)throw new H(`${s.length} of ${a} weights are not set: ${s}`)}J2(n)}updatedConfig(){let e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${nA}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){let r=J1(this.updatedConfig());return t?JSON.stringify(r):r}call(e,t){return q(()=>{e=It(e);let r=new ho;for(let a=0;a<this.inputs.length;++a)r.add(this.inputs[a],e[a]);return dp(this.outputs,r,t)})}computeMask(e,t){return q(()=>{e=It(e);let r;return t==null?r=ko(null,e.length):r=It(t),this.runInternalGraph(e,r)[1]})}computeOutputShape(e){let t=nf(e);if(t.length!==this.inputLayers.length)throw new H(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);let r={};for(let i=0;i<t.length;i++){let o=this.inputLayers[i],l=t[i],d=o.name+"_0_0";r[d]=l}let a=Object.keys(this.nodesByDepth).map(i=>parseInt(i,10)).sort(Sc);if(a.length>1)for(let i of a){let o=this.nodesByDepth[i];for(let l of o){let d=l.outboundLayer;if(this.inputLayers.map(f=>f.id).indexOf(d.id)!==-1)continue;let u=[];for(let f=0;f<l.inboundLayers.length;f++){let m=l.inboundLayers[f],g=l.nodeIndices[f],y=l.tensorIndices[f],A=`${m.name}_${g}_${y}`,x=r[A];u.push(x)}let p=d.computeOutputShape(ea(u)),h=nf(p),c=d.inboundNodes.indexOf(l);for(let f=0;f<h.length;f++){let m=`${d.name}_${c}_${f}`;r[m]=h[f]}}}let n=[],s=[];for(let i=0;i<this.outputLayers.length;i++){let o=this.outputLayers[i],l=this.outputLayersNodeIndices[i],d=this.outputLayersTensorIndices[i],u=`${o.name}_${l}_${d}`;s.push(u)}for(let i=0;i<s.length;i++){let o=s[i];wn(o in r),n.push(r[o])}return ea(n)}runInternalGraph(e,t){t==null&&(t=ko(null,e.length));let r={};for(let o=0;o<this.inputs.length;++o){let l=this.inputs[o],d=e[o],u=t[o];r[l.id]=[d,u]}let a=Object.keys(this.nodesByDepth).map(o=>parseInt(o,10)).sort(Sc);for(let o of a){let l=this.nodesByDepth[o];for(let d of l){let u=d.outboundLayer,p=d.inputTensors,h=d.outputTensors,c=new Array;for(let f of p)f.id in r&&c.push(r[f.id]);if(c.length===p.length){let f={},m,g,y,A;if(d.callArgs!=null&&(f=d.callArgs),c.length===1){let[x,b]=c[0];f.mask==null&&(f.mask=b),y=It(u.call(x,f)),A=It(u.computeMask(x,b)),m=[x],g=[b]}else m=c.map(x=>x[0]),g=c.map(x=>x[1]),f.mask==null&&(f.mask=g),y=It(u.call(m,f)),A=It(u.computeMask(m,g));if(u.activityRegularizer)throw new Be("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let x=0;x<h.length;++x){let b=h[x],v=y[x],C=A[x];r[b.id]=[v,C]}}}}let n=[],s=[],i=[];for(let o of this.outputs){wn(o.id in r,`Could not compute output ${o.name} : ${o.id}`);let[l,d]=r[o.id];i.push(l.shape),n.push(l),s.push(d)}return[n,s,i]}buildNodeConversionMap(e){let t={},r;for(let a of this.layers){r=a instanceof vn?1:0;for(let n=0;n<a.inboundNodes.length;n++){let s=vn.nodeKey(a,n);this.containerNodes.has(s)&&(t[s]=r,r+=1)}}return t}getLayer(e,t){if(t!=null){if(this.layers.length<=t)throw new H(`Was asked to retrieve layer at index ${t}, but model only has ${this.layers.length} layer(s).`);return this.layers[t]}else if(e==null)throw new H("Provide either a layer name or layer index");for(let r of this.layers)if(r.name===e)return r;throw new H(`No such layer: ${e}`)}calculateLosses(){return q(()=>{let e=[];for(let t of this.layers)for(let r=0;r<t.inboundNodes.length;++r){let a=vn.nodeKey(t,r);this.containerNodes.has(a)&&e.push(...t.calculateLosses())}return e})}getConfig(){let e={name:this.name},t=this.buildNodeConversionMap(this.layers),r=[];for(let s of this.layers){let i=s.getClassName(),o=s.getConfig(),l=[];for(let u=0;u<s.inboundNodes.length;u++){let p=s.inboundNodes[u],h=vn.nodeKey(s,u),c={};if(this.containerNodes.has(h)){if(p.callArgs)try{JSON.stringify(p.callArgs),c=p.callArgs}catch(f){console.warn(`Layer ${s.name} was passed non-serializable keyword arguments: ${p.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),c={}}if(p.inboundLayers.length>0){let f=[];for(let m=0;m<p.inboundLayers.length;m++){let g=p.inboundLayers[m],y=p.nodeIndices[m],A=p.tensorIndices[m],x=vn.nodeKey(g,y),b=t[x];b==null&&(b=0),f.push([g.name,b,A,c])}l.push(f)}}}let d={};d.name=s.name,d.className=i,d.config=o,d.inboundNodes=l,r.push(d)}e.layers=r;let a=[];for(let s=0;s<this.inputLayers.length;s++){let i=this.inputLayers[s],o=this.inputLayersNodeIndices[s],l=vn.nodeKey(i,o);if(!this.containerNodes.has(l))continue;let d=t[l];d==null&&(d=0);let u=this.inputLayersTensorIndices[s];a.push([i.name,d,u])}e.inputLayers=a;let n=[];for(let s=0;s<this.outputLayers.length;s++){let i=this.outputLayers[s],o=this.outputLayersNodeIndices[s],l=vn.nodeKey(i,o);if(!this.containerNodes.has(l))continue;let d=t[l];d==null&&(d=0);let u=this.outputLayersTensorIndices[s];n.push([i.name,d,u])}return e.outputLayers=n,e}static fromConfig(e,t,r={},a=!1){let n={},s={};function i(m,g){m.name in s?s[m.name].push(g):s[m.name]=[g]}function o(m,g){let y=[],A;for(let x of g){let b=x[0],v=x[1],C=x[2];if(A=x[3]==null?{}:x[3],!(b in n)){i(m,g);return}let T=n[b];if(T.inboundNodes.length<=v){i(m,g);return}let E=T.inboundNodes[v];y.push(E.outputTensors[C])}y.length>0&&m.apply(ea(y),A)}function l(m){let g=m.name,y=nn(m,t.customObjects!=null?t.customObjects:{});y.setFastWeightInitDuringBuild(a),n[g]=y,m.inboundNodes.forEach(A=>{if(!(A instanceof Array))throw new H(`Corrupted configuration, expected array for nodeData: ${A}`);i(y,A)})}let d=t.name,u=t.layers;for(let m of u)l(m);for(;!WB(s);)for(let m of u){let g=n[m.name];if(g.name in s){let y=s[g.name];delete s[g.name];for(let A of y)o(g,A)}}let p=[],h=[],c=t.inputLayers;for(let m of c){let g=m[0],y=m[1],A=m[2];wn(g in n);let x=n[g].inboundNodes[y].outputTensors;p.push(x[A])}let f=t.outputLayers;for(let m of f){let g=m[0],y=m[1],A=m[2];wn(g in n);let x=n[g].inboundNodes[y].outputTensors;h.push(x[A])}return new e({inputs:p,outputs:h,name:d})}get stateful(){if(this._stateful)throw new H("Container instance unexpectedly has _stateful = true. The statefulness of a Container is determined by the Layers it contains. Its _stateful property must remain the default false.");for(let e of this.layers)if(e.stateful)return!0;return!1}resetStates(){q(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}};function pV(e,t,r){let a=t.length;if(e==null||Array.isArray(e)&&e.length===0)return t.map(n=>null);if(a===1)return Array.isArray(e)&&e.length===1?e:typeof e=="object"&&t[0]in e?[e[t[0]]]:[e];if(Array.isArray(e)){if(e.length!==a)throw new Error(`Provided ${r} is an array of ${e.length} element(s), but the model has ${a} outputs. Make sure a set of weights is provided for each model output.`);return e}else if(typeof e=="object"&&Object.keys(e).length>0&&typeof e[Object.keys(e)[0]]=="object"){let n=[];return t.forEach(s=>{s in e?n.push(e[s]):n.push(null)}),n}else throw new Error(`The model has multiple (${a}) outputs, so ${r} must be either an array with ${a} elements or an object with ${t} keys. Provided ${r} not understood: ${JSON.stringify(e)}`)}function b7(e,t){return pV(e,t,"classWeight")}async function v7(e,t,r,a){if(t!=null||a!=null)throw new Error("Support sampleWeight is not implemented yet");if(r!=null){let n=q(()=>{if(e.shape.length===1)return Pr(e);if(e.shape.length===2){if(e.shape[1]>1)return Ta(e,1);if(e.shape[1]===1)return U(e,[e.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${e.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}else throw new Error(`Unexpected rank of target (y) tensor (${e.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)}),s=Array.from(await n.data());re(n);let i=[];return s.forEach(o=>{if(r[o]==null)throw new Error(`classWeight must contain all classes in the training data. The class ${o} exists in the data but not in classWeight`);i.push(r[o])}),St(i,"float32")}else return null}function hV(e,t){return L(e,t)}var cV=32;function w7(e,t){let r,a,n=t;r=n.xs,a=n.ys,w.assert(r!=null&&a!=null,()=>`A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates ${t}`);let s=b3("input",e.inputNames,r),i=b3("output",e.outputNames,a),o=s[0].shape[0];w.assert(s.length===e.inputs.length,()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${s.length} inputs. (Expected input keys: ${JSON.stringify(e.inputNames)})`),w.assert(i.length===e.outputs.length,()=>`LayersModel has ${e.outputs.length} outputs, but the dataset provides ${i.length} outputs. (Expected output keys: ${JSON.stringify(e.outputNames)})`);for(let l=0;l<s.length;l++)w.assert(s[l].shape[0]===o,()=>`Batch size mismatch: input ${e.inputNames[l]} has ${s[l].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`);for(let l=0;l<i.length;l++)w.assert(i[l].shape[0]===o,()=>`Batch size mismatch: output ${e.outputNames[l]} has ${i[l].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`);return{xs:s,ys:i}}function b3(e,t,r){if(r instanceof et)return[r];if(Array.isArray(r))return w.assert(r.length===t.length,()=>`Received an array of ${r.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`),r;{let a=[];for(let n of t){if(r[n]==null)throw new H(`The feature data generated by the dataset lacks the required ${e} key '${n}'.`);a.push(r[n])}return a}}function fV(e){if(e.length===3)throw new Be("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}async function mV(e,t,r){let a=r.batchesPerEpoch!=null;if(w.assert(e.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),w.assert(r!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),w.assert(r.epochs!=null&&r.epochs>0&&Number.isInteger(r.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${r.epochs}`),w.assert(!a||r.batchesPerEpoch>0&&Number.isInteger(r.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${r.batchesPerEpoch}`),w.assert(r.validationSplit==null,()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."),e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;try{let n=r.validationData!=null,s,i;if(n)if(v3(r.validationData))w.assert(r.validationBatches==null||r.validationBatches>0&&Number.isInteger(r.validationBatches),()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${r.validationBatches}`);else{let g=fV(r.validationData);s=g.xs,i=g.ys}let o=e.makeTrainFunction(),l=e.getDedupedMetricsNames(),d;n?d=l.slice().concat(l.map(g=>"val_"+g)):d=l.slice();let u=h7(r.callbacks,r.yieldEvery),p=r.verbose==null?1:r.verbose,{callbackList:h,history:c}=c7(u,p,r.epochs,null,null,gV(t,r),null,n,d);h.setModel(e),e.history=c,await h.onTrainBegin(),e.stopTraining_=!1;let f=r.initialEpoch==null?0:r.initialEpoch,m=await t.iterator();for(;f<r.epochs;){let g={};await h.onEpochBegin(f);let y=0,A=0;for(a||(m=await t.iterator());a?y<r.batchesPerEpoch:!0;){let x=await m.next();if(a&&x.done){console.warn(`You provided \`batchesPerEpoch\` as ${r.batchesPerEpoch}, but your dataset iterator ran out of data after ${y} batches; interrupting training. Make sure that your dataset can generate at least \`batchesPerEpoch * epochs\` batches (in this case, ${r.batchesPerEpoch*r.epochs} batches). You may need to use the repeat() function when building your dataset.`);break}if(x.value!=null){let{xs:b,ys:v}=w7(e,x.value),C={};C.batch=A,C.size=b[0].shape[0],await h.onBatchBegin(A,C);let T=[];if(r.classWeight!=null){let z=b7(r.classWeight,e.outputNames);for(let M=0;M<z.length;++M)T.push(await v7(v[M],null,z[M]))}let E=b.concat(v).concat(T),R=o(E);re(E);for(let z=0;z<l.length;++z){let M=l[z],I=R[z];C[M]=I,dr(I)}await h.onBatchEnd(A,C),l7(C),A++,y++}if(a?y>=r.batchesPerEpoch:x.done){if(n){let b;v3(r.validationData)?b=It(await e.evaluateDataset(r.validationData,{batches:r.validationBatches})):b=It(e.evaluate(s,i,{batchSize:r.validationBatchSize==null?cV:r.validationBatchSize,verbose:0}));for(let v=0;v<e.metricsNames.length;++v)g[`val_${e.metricsNames[v]}`]=b[v]}break}if(e.stopTraining_)break}if(await h.onEpochEnd(f,g),f++,e.stopTraining_)break}return await h.onTrainEnd(),await e.history.syncData(),e.history}finally{e.isTraining=!1}}function gV(e,t){let r=null;return t.batchesPerEpoch!=null?r=t.batchesPerEpoch:Number.isFinite(e.size)&&(r=e.size),r}function v3(e){return typeof e.iterator=="function"}function yV(e){return typeof e.next=="function"}async function AV(e,t,r){r=r||{};let a=r.batches!=null,n=e.testFunction,s=[];if(r.verbose>0)throw new Be("Verbose mode is not implemented yet.");w.assert(!a||r.batches>0&&Number.isInteger(r.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(r.batches)}`);let i=yV(t)?t:await t.iterator(),o=0,l=0;for(;a?l<r.batches:!0;){let d=await i.next();if(s=q(()=>{if(d.value){let{xs:u,ys:p}=w7(e,d.value),h=u.concat(p),c=q(()=>n(h));if(re(h),l===0)for(let m=0;m<c.length;++m)s.push(Se(0));let f=h[0].shape[0];for(let m=0;m<c.length;++m){let g=c[m],y=s[m];s[m]=q(()=>ue(s[m],L(f,g))),l>0&&re(y)}re(c),o+=f,++l}return s}),d.done){a&&console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${r.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let d=0;d<s.length;++d){let u=s[d];s[d]=pe(s[d],o),re(u)}return ea(s)}function Q1(e){w.assert(e>0&&Number.isInteger(e),()=>`batchSize is required to be a positive integer, but got ${e}`)}function pp(e,t,r){return e==null?[null]:Array.isArray(e)?e.map(a=>go(a,t,r-t)):go(e,t,r-t)}function sA(e,t){return q(()=>e==null?null:Array.isArray(e)?e.map(r=>sA(r,t)):t7(e,t.dtype==="int32"?t:me(t,"int32")))}function ey(e,t){let r=[],a=0,n=null;for(;a<e;)n=a+t,n>=e&&(n=e),r.push([a,n]),a=n;return r}async function xV(e,t,r,a,n,s,i,o,l,d,u,p,h,c,f){n==null&&(n=32),s==null&&(s=1),u==null&&(u=!0),h==null&&(h=0);let m=!1;if(l!=null&&d!=null&&(m=!0),f!=null&&(m=!0,c==null))throw new H("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");let g=e.checkNumSamples(r,n,c,"steps_per_epoch"),y;g!=null&&(y=dn(0,g)),i==null&&(i=1);let{callbackList:A,history:x}=c7(o,i,s,h,g,c,n,m,p);A.setModel(e),e.history=x,await A.onTrainBegin(),e.stopTraining_=!1;for(let b=h;b<s;++b){await A.onEpochBegin(b);let v={};if(c!=null)throw new Be("stepsPerEpoch mode is not implemented yet.");{if(u==="batch")throw new Be("batch shuffling is not implemneted yet");u&&w.shuffle(y);let C=St(y),T=ey(g,n);for(let E=0;E<T.length;++E){let R={};if(await A.onBatchBegin(E,R),q(()=>{let z=T[E][0],M=T[E][1],I=go(C,z,M-z);R.batch=E,R.size=M-z;let D=sA(r,I),O=t(D);for(let j=0;j<a.length;++j){let X=a[j],_=O[j];R[X]=_,dr(_)}if(E===T.length-1&&m){let j=e.testLoop(l,d,n);for(let X=0;X<a.length;++X){let _=a[X],K=j[X];dr(K),v["val_"+_]=K}}}),await A.onBatchEnd(E,R),l7(R),e.stopTraining_)break}C.dispose()}if(await A.onEpochEnd(b,v),e.stopTraining_)break}return await A.onTrainEnd(),await e.history.syncData(),e.history}async function bV(e,t,r,a={}){if(e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;let n,s,i,o,l,d,u,p,h;try{let c=a.batchSize==null?32:a.batchSize;Q1(c);let f=!1,m=await e.standardizeUserData(t,r,a.sampleWeight,a.classWeight,f,c);n=m[0],s=m[1],h=m[2];let g=!1,y;if(a.validationData!=null&&a.validationData.length>0){if(g=!0,a.validationData.length===2)l=a.validationData[0],d=a.validationData[1];else throw a.validationData.length===3?new Be("validationData including sample weights is not supported yet."):new H(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${a.validationData} is invalid.`);let E=!0,R=await e.standardizeUserData(l,d,null,null,E,c);u=R[0],p=R[1],y=u.concat(p)}else if(a.validationSplit!=null&&a.validationSplit>0&&a.validationSplit<1){g=!0;let E=Math.floor(n[0].shape[0]*(1-a.validationSplit)),R=n[0].shape[0];u=pp(n,E,R),i=n,n=pp(n,0,E),p=pp(s,E,R),o=s,s=pp(s,0,E),y=u.concat(p)}else a.validationSteps!=null&&(g=!0);let A=n.concat(s).concat(h);e.checkTrainableWeightsConsistency();let x=e.makeTrainFunction(),b=e.getDedupedMetricsNames(),v,C;g?(e.makeTestFunction(),v=e.testFunction,C=b.slice().concat(b.map(E=>"val_"+E))):(v=null,y=[],C=b.slice());let T=h7(a.callbacks,a.yieldEvery);return await xV(e,x,A,b,c,a.epochs,a.verbose,T,v,y,a.shuffle,C,a.initialEpoch,null,null)}finally{e.isTraining=!1,Qa(n,t),Qa(s,r),Qa(i,t),Qa(o,r),Qa(u,l),Qa(p,d),h!=null&&re(h)}}function k7(e){let t=[];e instanceof et&&(e=[e]);for(let r=0;r<e.length;++r){let a=e[r];if(a.rank===1)t.push(gh(a,1));else{if(a.rank===0)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");t.push(a)}}return t}function Qa(e,t){if(e==null)return;let r=[];if(t instanceof et)r.push(t.id);else if(Array.isArray(t))t.forEach(n=>r.push(n.id));else if(t!=null)for(let n in t){let s=t[n];r.push(s.id)}let a=[];if(e instanceof et)r.indexOf(e.id)===-1&&a.push(e);else if(Array.isArray(e))e.forEach(n=>{r.indexOf(n.id)===-1&&a.push(n)});else if(e!=null)for(let n in e){let s=e[n];r.indexOf(s.id)===-1&&a.push(s)}a.forEach(n=>{n.isDisposed||n.dispose()})}function vV(e){return e instanceof et}function ty(e){return Array.isArray(e)}function w3(e){return!vV(e)&&!ty(e)}function k3(e,t,r,a=!0,n=""){if(t==null||t.length===0){if(e!=null){let i=!1;if(ty(e)&&e.length>0)i=!0;else if(w3(e)){for(let o in e)if(e.hasOwnProperty(o)){i=!0;break}}else i=!0;if(i)throw new H(`Error when checking model ${n} expected no data, but got ${e}`)}return[]}if(e==null)return t.map(i=>null);let s;if(w3(e)){e=e,s=[];for(let i of t){if(e[i]==null)throw new H(`No data provided for "${i}". Need data for each key in: ${t}`);s.push(e[i])}}else if(ty(e)){if(e=e,e.length!==t.length)throw new H(`Error when checking model ${n}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${e}`);s=e}else{if(e=e,t.length>1)throw new H(`The model ${n} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);s=[e]}if(s=k7(s),r!=null)for(let i=0;i<t.length;++i){if(r[i]==null)continue;let o=s[i];if(o.shape.length!==r[i].length)throw new H(`Error when checking ${n}: expected ${t[i]} to have ${r[i].length} dimension(s). but got array with shape ${o.shape}`);for(let l=0;l<r[i].length;++l){if(l===0&&!a)continue;let d=o.shape[l],u=r[i][l];if(u!=null&&u>=0&&d!==u)throw new H(`${n} expected a batch of elements where each example has shape [${r[i].slice(1,r[i].length)}] (i.e.,tensor shape [*,${r[i].slice(1,r[i].length)}]) but the ${n} received an input with ${o.shape[0]} examples, each with shape [${o.shape.slice(1,o.shape.length)}] (tensor shape [${o.shape}])`)}}return s}function wV(e,t,r){let a=Cs(e.map(s=>s.shape[0]));a.sort();let n=Cs(t.map(s=>s.shape[0]));if(n.sort(),a.length>1)throw new H(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map(s=>s.shape))}`);if(n.length>1)throw new H(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map(s=>s.shape))}`);if(a.length>0&&n.length>0&&!w.arraysEqual(a,n))throw new H(`Input Tensors should have the same number of samples as target Tensors. Found ${a[0]} input sample(s) and ${n[0]} target sample(s).`)}function kV(e,t,r){let a=[kl,Dm,Mp];for(let n=0;n<e.length;++n){let s=e[n],i=t[n],o=r[n];if(i!=null){if(i===Mp&&s.shape[s.shape.length-1]===1)throw new H(`You are passing a target array of shape ${s.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(a.indexOf(i)!==-1){let l=s.shape.slice(1),d=o.slice(1);for(let u=0;u<l.length;++u){let p=l[u],h=d[u];if(h!=null&&p!==h)throw new H(`A target Tensor with shape ${s.shape} was passed for an output of shape ${o}, while using a loss function that expects targets to have the same shape as the output.`)}}}}}function I3(e,t,r,a=!0,n=""){let s;if(Array.isArray(e)){if(e.length!==t.length)throw new H(`Error when checking model ${n}: the Array of Tensors that you are passing to your model is not the size the the model expected. Expected to see ${t.length} Tensor(s), but instead got ${e.length} Tensors(s).`);s=e}else{if(t.length>1)throw new H(`The model expects ${t.length} ${n} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);s=[e]}if(r!=null)for(let i=0;i<t.length;++i){if(r[i]==null)continue;let o=s[i];if(o.shape.length!==r[i].length)throw new H(`Error when checking ${n}: expected ${t[i]} to have ${r[i].length} dimension(s), but got array with shape ${JSON.stringify(o.shape)}`);for(let l=0;l<r[i].length;++l){if(l===0&&!a)continue;let d=o.shape[l],u=r[i][l];if(u!=null&&u!==d)throw new H(`Error when checking ${n}: expected ${t[i]} to have shape ${JSON.stringify(r[i])} but got array with shape ${JSON.stringify(o.shape)}.`)}}}function IV(e,t){if(e==null||Array.isArray(e)&&e.length===0)return t.map(a=>[]);let r;if(typeof e=="string"||typeof e=="function")r=[e];else if(Array.isArray(e)||typeof e=="object")r=e;else throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);if(Array.isArray(r))return t.map(a=>r);{let a=[];for(let n of t){let s=r.hasOwnProperty(n)?r[n]:[];Array.isArray(s)||(s=[s]),a.push(s)}return a}}var SV="layers-model",jn=class extends vn{constructor(e){super(e);this.isTraining=!1}summary(e,t,r=console.log){if(!this.built)throw new H("This model has never been called, thus its weights have not been created yet. So no summary can be displayed. Build the model first (e.g., by calling it on some test data).");rV(this,e,t,r)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=tV(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof Jn))throw new H("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(!Array.isArray(e.loss)&&typeof e.loss!="string"&&typeof e.loss!="function"){e.loss=e.loss;for(let s in e.loss)if(this.outputNames.indexOf(s)===-1)throw new H(`Unknown entry in loss dictionary: "${s}". Only expected the following keys: ${this.outputNames}`);for(let s of this.outputNames)e.loss[s]==null&&console.warn(`Output "${s}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${s} during training`),t.push(I1(e.loss[s]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new H(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);t=e.loss.map(s=>I1(s))}else{let s=I1(e.loss);this.outputs.forEach(i=>{t.push(s)})}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let s=0;s<this.outputs.length;++s){let i=this.internalOutputShapes[s],o=this.outputNames[s];this.feedOutputNames.push(o),this.feedOutputShapes.push(i),this.feedLossFns.push(this.lossFunctions[s])}let r=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],mo("loss",()=>{for(let s=0;s<this.outputs.length;++s){if(r.indexOf(s)!==-1)continue;let i=this.lossFunctions[s];this.outputs.length>1&&(this.metricsTensors.push([i,s]),this.metricsNames.push(this.outputNames[s]+"_loss"))}});let a=IV(e.metrics,this.outputNames),n=(s,i,o)=>{this.outputNames.length>1&&(i=this.outputNames[s]+"_"+i),this.metricsNames.push(i),this.metricsTensors.push([o,s])};mo("metric",()=>{for(let s=0;s<this.outputs.length;++s){if(r.indexOf(s)!==-1)continue;let i=a[s];(o=>{let l="",d,u,p;for(let h of o){if(typeof h=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(h)!==-1){let f=this.internalOutputShapes[s];f[f.length-1]===1||this.lossFunctions[s]===Dm?["accuracy","acc"].indexOf(h)!==-1?u=tA:["crossentropy","ce"].indexOf(h)!==-1&&(u=g7):this.lossFunctions[s]===lf?["accuracy","acc"].indexOf(h)!==-1?u=y7:["crossentropy","ce"].indexOf(h)!==-1&&(u=A7):["accuracy","acc"].indexOf(h)!==-1?u=rA:["crossentropy","ce"].indexOf(h)!==-1&&(u=aA);let m;["accuracy","acc"].indexOf(h)!==-1?m="acc":["crossentropy","ce"].indexOf(h)!==-1&&(m="ce"),p=u,d=l+m}else p=eV(h),d=l+Nc(h);let c;mo(d,()=>{c=p}),n(s,d,c)}})(i)}}),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){this.collectedTrainableWeights!=null&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(e,t,r={}){let a=r.batchSize==null?32:r.batchSize;Q1(a);let n=!0,s=this.standardizeUserDataXY(e,t,n,a);try{let i=s[0].concat(s[1]);this.makeTestFunction();let o=this.testFunction,l=this.testLoop(o,i,a,r.verbose,r.steps);return ea(l)}finally{Qa(s[0],e),Qa(s[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),AV(this,e,t)}checkNumSamples(e,t,r,a="steps"){let n;if(r!=null){if(n=null,t!=null)throw new H(`If ${a} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else if(e!=null)Array.isArray(e)?n=e[0].shape[0]:n=e.shape[0];else throw new H(`Either the input data should have a defined shape, or ${a} shoud be specified.`);return n}execute(e,t){if(Array.isArray(t)&&t.length===0)throw new H("`outputs` is an empty Array, which is not allowed.");let r=Array.isArray(t),a=r?t:[t],n=this.retrieveSymbolicTensors(a),s=new ho;if(e instanceof et&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new H(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let o=0;o<this.inputs.length;++o)s.add(this.inputs[o],e[o])}else for(let o of this.inputs){let l=e[o.name];if(l==null)throw new H(`No value is provided for the model's input ${o.name}`);s.add(o,l)}let i=dp(n,s);return r?i:i[0]}retrieveSymbolicTensors(e){let t=ko(null,e.length),r=e.length;for(let a of this.layers){let n=Array.isArray(a.output)?a.output:[a.output],s=n.map(i=>i.name);for(let i=0;i<e.length;++i){let o=s.indexOf(e[i]);if(o!==-1&&(t[i]=n[o],r--),r===0)break}if(r===0)break}if(r>0){let a=[];throw t.forEach((n,s)=>{n==null&&a.push(e[s])}),new H(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(a)}`)}return t}predictLoop(e,t=32,r=!1){return q(()=>{let a=this.checkNumSamples(e);if(r)throw new Be("Verbose predictLoop() is not implemented yet.");let n=ey(a,t),s=this.outputs.map(i=>[]);for(let i=0;i<n.length;++i)q(()=>{let o=n[i][0],l=n[i][1],d=pp(e,o,l),u=[];if(Array.isArray(d))for(let h=0;h<d.length;++h)u.push({key:this.inputs[h],value:d[h]});else u.push({key:this.inputs[0],value:d});let p=new ho(u);return dp(this.outputs,p)}).forEach((o,l)=>s[l].push(o));return ea(s.map(i=>kt(i,0)))})}predict(e,t={}){let r=k7(e);I3(r,this.inputNames,this.feedInputShapes,!1);try{let a=t.batchSize==null?32:t.batchSize;return Q1(a),this.predictLoop(r,a)}finally{Qa(r,e)}}predictOnBatch(e){I3(e,this.inputNames,this.feedInputShapes,!0);let t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,r=!0,a){if(this.optimizer_==null)throw new en("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");let n=[];for(let s=0;s<this.feedOutputShapes.length;++s){let i=this.feedOutputShapes[s];this.feedLossFns[s]===lf?n.push(i.slice(0,i.length-1).concat([1])):n.push(i)}if(e=k3(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=k3(t,this.feedOutputNames,n,!1,"target"),wV(e,t,null),kV(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&a!=null&&a>0&&e[0].shape[0]%a!==0)throw new H(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${a}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,r,a,n=!0,s){let[i,o]=this.standardizeUserDataXY(e,t,n,s);if(r!=null)throw new Error("sample weight is not supported yet.");let l=null;if(a!=null){let d=b7(a,this.outputNames);l=[];for(let u=0;u<d.length;++u)l.push(await v7(o[u],null,d[u]))}return[i,o,l]}testLoop(e,t,r,a=0,n){return q(()=>{let s=this.checkNumSamples(t,r,n,"steps"),i=[];if(a>0)throw new Be("Verbose mode is not implemented yet.");if(n!=null)throw new Be("steps mode in testLoop() is not implemented yet");{let o=ey(s,r),l=St(dn(0,s));for(let d=0;d<o.length;++d){let u=o[d][0],p=o[d][1],h=go(l,u,p-u),c=sA(t,h),f=e(c);if(d===0)for(let m=0;m<f.length;++m)i.push(Se(0));for(let m=0;m<f.length;++m){let g=f[m];i[m]=ue(i[m],L(p-u,g))}}for(let d=0;d<i.length;++d)i[d]=pe(i[d],s)}return i})}getDedupedMetricsNames(){let e=this.metricsNames,t=[];for(let r=0;r<e.length;++r){let a=e[r],n=a;l3(e,a)>1&&(n+=`_${l3(e.slice(0,r),a)}`),t.push(n)}return t}makeTrainFunction(){return e=>{let t=[],r=e.slice(0,this.inputs.length),a=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),n=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+this.outputs.length*2),s=[],i=()=>{let d=[];for(let c=0;c<this.inputs.length;++c)d.push({key:this.inputs[c],value:r[c]});let u=new ho(d),p=dp(this.outputs,u,{training:!0}),h;for(let c=0;c<this.lossFunctions.length;++c){let f=this.lossFunctions[c](a[c],p[c]);n[c]!=null&&(f=hV(f,n[c]));let m=Wt(f);t.push(m),c===0?h=f:h=ue(h,f)}for(let c=0;c<this.metricsTensors.length;++c){let f;if(this.outputs.length>1&&c<this.outputs.length)f=t[c];else{let m=this.metricsTensors[c][0],g=this.metricsTensors[c][1];f=Wt(m(a[g],p[g]))}dr(f),s.push(f)}return h=Wt(h),this.calculateLosses().forEach(c=>{h=ue(h,c)}),h},o=this.collectedTrainableWeights.map(d=>d.read()),l=!0;return[this.optimizer_.minimize(i,l,o)].concat(s)}}makeTestFunction(){this.testFunction=e=>q(()=>{let t=[],r,a=e.slice(0,this.inputs.length),n=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),s=[];for(let l=0;l<this.inputs.length;++l)s.push({key:this.inputs[l],value:a[l]});let i=new ho(s),o=dp(this.outputs,i);for(let l=0;l<this.lossFunctions.length;++l){let d=this.lossFunctions[l],u=Wt(d(n[l],o[l]));l===0?r=u:r=ue(r,u),t.push(r)}for(let l=0;l<this.metricsTensors.length;++l){let d=this.metricsTensors[l][0],u=this.metricsTensors[l][1],p=Wt(d(n[u],o[u]));t.push(p)}return t})}async fit(e,t,r={}){return bV(this,e,t,r)}async fitDataset(e,t){return mV(this,e,t)}async trainOnBatch(e,t){let r=await this.standardizeUserData(e,t),a=r[0],n=r[1],s=this.makeTrainFunction()(a.concat(n)),i=[];for(let o of s){let l=await o.data();i.push(l[0])}return re(s),Qa(r[0],e),Qa(r[1],t),ea(i)}getNamedWeights(e){let t=[],r=e!=null&&e.trainableOnly,a=r?this.trainableWeights:this.weights,n=this.getWeights(r);for(let s=0;s<a.length;++s)r&&!a[s].trainable||t.push({name:a[s].originalName,tensor:n[s]});return t}set stopTraining(e){this.stopTraining_=e}get stopTraining(){return this.stopTraining_}get optimizer(){return this.optimizer_}set optimizer(e){this.optimizer_!==e&&(this.optimizer_=e,this.isOptimizerOwned=!1)}dispose(){let e=super.dispose();if(e.refCountAfterDispose===0&&this.optimizer!=null&&this.isOptimizerOwned){let t=tf().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-tf().numTensors}return e}getLossIdentifiers(){let e;if(typeof this.loss=="string")e=Wn(this.loss);else if(Array.isArray(this.loss)){for(let t of this.loss)if(typeof t!="string")throw new Error("Serialization of non-string loss is not supported.");e=this.loss.map(t=>Wn(t))}else{let t=Object.keys(this.loss);e={};let r=this.loss;for(let a of t)if(typeof r[a]=="string")e[a]=Wn(r[a]);else throw new Error("Serialization of non-string loss is not supported.")}return e}getMetricIdentifiers(){if(typeof this.metrics=="string"||typeof this.metrics=="function")return[Wn(Nc(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>Wn(Nc(e)));{let e={};for(let t in this.metrics)e[t]=Wn(Nc(this.metrics[t]));return e}}getTrainingConfig(){return{loss:this.getLossIdentifiers(),metrics:this.getMetricIdentifiers(),optimizer_config:{class_name:this.optimizer.getClassName(),config:this.optimizer.getConfig()}}}loadTrainingConfig(e){if(e.weighted_metrics!=null)throw new Error("Loading weight_metrics is not supported yet.");if(e.loss_weights!=null)throw new Error("Loading loss_weights is not supported yet.");if(e.sample_weight_mode!=null)throw new Error("Loading sample_weight_mode is not supported yet.");let t=$p(e.optimizer_config),r=nn(t),a;if(typeof e.loss=="string")a=lo(e.loss);else if(Array.isArray(e.loss))a=e.loss.map(s=>lo(s));else if(e.loss!=null){a={};for(let s in e.loss)a[s]=lo(e.loss[s])}let n;if(Array.isArray(e.metrics))n=e.metrics.map(s=>lo(s));else if(e.metrics!=null){n={};for(let s in e.metrics)n[s]=lo(e.metrics[s])}this.compile({loss:a,metrics:n,optimizer:r})}async save(e,t){if(typeof e=="string"){let i=Ir.getSaveHandlers(e);if(i.length===0)throw new H(`Cannot find any save handlers for URL '${e}'`);if(i.length>1)throw new H(`Found more than one (${i.length}) save handlers for URL '${e}'`);e=i[0]}if(e.save==null)throw new H("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");let r=await Ir.encodeWeights(this.getNamedWeights(t)),a=!1,n=null,s={modelTopology:this.toJSON(n,a),format:SV,generatedBy:`TensorFlow.js tfjs-layers v${nA}`,convertedBy:null};if((t==null?!1:t.includeOptimizer)&&this.optimizer!=null){s.trainingConfig=this.getTrainingConfig();let i="optimizer",{data:o,specs:l}=await Ir.encodeWeights(await this.optimizer.getWeights(),i);r.specs.push(...l),r.data=Ir.concatenateArrayBuffers([r.data,o])}return this.userDefinedMetadata!=null&&(y3(this.userDefinedMetadata,this.name,!0),s.userDefinedMetadata=this.userDefinedMetadata),s.weightData=r.data,s.weightSpecs=r.specs,e.save(s)}setUserDefinedMetadata(e){y3(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}};jn.className="Model";de.registerClass(jn);var I7=class extends jn{};I7.className="Functional";de.registerClass(I7);async function TV(e,t){"modelTopology"in e||(e={modelTopology:e}),e=e;let r=e.modelTopology;r.model_config!=null&&(r=r.model_config);let a=$p(r),n=nn(a,t);if(e.weightsManifest!=null){let s=await Ir.loadWeights(e.weightsManifest,e.pathPrefix,n.weights.map(o=>o.originalName)),i={};for(let o of n.weights)i[o.originalName]=s[o.originalName];n.loadWeights(i),re(s)}return n}async function CV(e,t){if(t==null&&(t={}),typeof e=="string"){let r=Ir.getLoadHandlers(e,t);if(r.length===0)r.push(Ir.browserHTTPRequest(e,t));else if(r.length>1)throw new H(`Found more than one (${r.length}) load handlers for URL '${e}'`);e=r[0]}return NV(e,void 0,t)}async function NV(e,t,r){if(r==null&&(r={}),e.load==null)throw new H("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let a=await e.load(),n=a.modelTopology;n.model_config!=null&&(n=n.model_config);let s=r.strict==null?!0:r.strict,i=a.weightData!=null&&a.weightSpecs!=null&&s,o=nn($p(n),t,i),l=a.trainingConfig;if(l!=null&&o.loadTrainingConfig(l),a.userDefinedMetadata!=null&&o.setUserDefinedMetadata(a.userDefinedMetadata),a.weightData!=null){if(a.weightSpecs==null)throw new H("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");let{modelWeights:d,optimizerWeights:u}=EV(a.weightData,a.weightSpecs);o.loadWeights(d,s),o.optimizer!=null&&u.length>0&&await o.optimizer.setWeights(u),re(d),re(u.map(p=>p.tensor))}return o}function EV(e,t){let r=Ir.decodeWeights(e,t),a={},n=[];return t.forEach(s=>{s.group==="optimizer"?n.push({name:s.name,tensor:r[s.name]}):a[s.name]=r[s.name]}),{modelWeights:a,optimizerWeights:n}}var ry=class extends jn{constructor(e){super({inputs:[],outputs:[]});if(e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:Pm("sequential_"),e.layers!=null)for(let t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some(t=>t<0))throw new H(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){let t=e instanceof ry||e instanceof jn,r;if(t){if(r=e,r.outputs.length!==1)throw new H("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(r.inputs.length!==1)throw new H("All layers in a Sequential model should have a single input tensor. For multi-input layers, use the functional API.")}if(this.outputs.length===0){if(e.inboundNodes.length===0){if(e.batchInputShape==null)throw new H("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");let a=o7({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(a)}if(t)this.outputs=r.outputs,this.inputs=r.inputs;else{if(e.inboundNodes.length!==1)throw new H(`A layer added to a Sequential model must not already be connected somewhere else. LayersModel received layer ${e.name} which has ${e.inboundNodes.length} pre-existing inbound connections.`);if(e.inboundNodes[0].outputTensors.length!==1)throw new H("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[e.inboundNodes[0].outputTensors[0]],this.inputs=i7(this.outputs[0])}this.inboundNodes=[],new Om({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:ko(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(a=>a.shape),outputShapes:this.outputs[0].shape})}else{let a=e.apply(this.outputs[0]);if(Array.isArray(a))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[a],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1}pop(){if(this.layers.length===0)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),this.layers.length===0)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{let e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(e,t){return this.model==null&&this.build(),this.model.call(e,t)}build(e){if(mt(e),this.inputs.length===0||this.outputs.length===0)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new jn({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0}countParams(){return this.built||this.build(),super.countParams()}summary(e,t,r=console.log){this.built||this.build(),super.summary(e,t,r)}setWeights(e){this.model==null&&this.build(),this.model.setWeights(e)}evaluate(e,t,r={}){if(!this.built)throw new en("The model needs to be compiled before being used.");return this.model.evaluate(e,t,r)}async evaluateDataset(e,t){if(!this.built)throw new en("The model needs to be compiled before being used.");return this.model.evaluateDataset(e,t)}predict(e,t={}){return this.model==null&&this.build(),this.model.predict(e,t)}predictOnBatch(e){return this.model==null&&this.build(),this.model.predictOnBatch(e)}compile(e){this.build(),this.model.compile(e),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames}get optimizer(){return this.model==null?void 0:this.model.optimizer}set optimizer(e){this.model.optimizer=e}async fit(e,t,r={}){if(!this.built)throw new en("The model needs to be compiled before being used.");return this.model.fit(e,t,r)}async fitDataset(e,t){if(!this.built)throw new en("The model needs to be compiled before being used.");return this.model.fitDataset(e,t)}async trainOnBatch(e,t){return this.model.trainOnBatch(e,t)}static fromConfig(e,t,r={},a=!1){let n,s={};if(t instanceof Array){if(t[0].className==null||t[0].className==="Merge")throw new H("Legacy serialization format not supported yet.");n=t}else w.assert(t.layers!=null,()=>"When the config data for a Sequential model is not an Array, it must be an Object that contains the 'layers' field."),n=t.layers,delete t.layers,s=t;let i=new e(s);if(!(i instanceof ry))throw new Be(`Sequential.fromConfig called on non-Sequential input: ${i}`);for(let o of n){let l=nn(o,void 0,a);a&&l.setFastWeightInitDuringBuild(!0),i.add(l)}return i}set stopTraining(e){if(this.model==null)throw new H("Cannot set the stopTraining property of a sequential model before it is compiled.");this.model.stopTraining=e}get stopTraining(){if(this.model==null)throw new H("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){let e=[];for(let t of this.layers){let r={};r.className=t.getClassName(),r.config=t.getConfig(),e.push(r)}return{name:this.name,layers:e}}},_m=ry;_m.className="Sequential";de.registerClass(_m);function RV(e){return new jn(e)}function FV(e){return new _m(e)}function MV(e,t){return t==null&&(t={}),CV(e,t)}function S7(e){return o7(e)}function $V(e,t){Q2.registerCallbackConstructor(e,t)}var na=class extends de.Serializable{getConfig(){return{}}},T7=class extends na{apply(e,t=1){return sW(e,t)}};T7.className="elu";de.registerClass(T7);var C7=class extends na{apply(e){return I2(e)}};C7.className="selu";de.registerClass(C7);var N7=class extends na{apply(e){return Fn(e)}};N7.className="relu";de.registerClass(N7);var E7=class extends na{apply(e){return q(()=>ph(6,Fn(e)))}};E7.className="relu6";de.registerClass(E7);var R7=class extends na{apply(e){return e}};R7.className="linear";de.registerClass(R7);var F7=class extends na{apply(e){return Sr(e)}};F7.className="sigmoid";de.registerClass(F7);var M7=class extends na{apply(e){return oW(e)}};M7.className="hardSigmoid";de.registerClass(M7);var $7=class extends na{apply(e){return rd(e)}};$7.className="softplus";de.registerClass($7);var P7=class extends na{apply(e){return iW(e)}};P7.className="softsign";de.registerClass(P7);var O7=class extends na{apply(e){return hu(e)}};O7.className="tanh";de.registerClass(O7);var iA=class extends na{apply(e,t=-1){return sd(e,t)}};iA.className="softmax";de.registerClass(iA);var z7=class extends na{apply(e,t=-1){return c2(e,t)}};z7.className="logSoftmax";de.registerClass(z7);var D7=class extends na{apply(e,t=1){return q(()=>L(Sr(L(e,t)),e))}};D7.className="swish";de.registerClass(D7);var _7=class extends na{apply(e){return q(()=>L(e,hu(rd(e))))}};_7.className="mish";de.registerClass(_7);function Bs(e){return e.getClassName()}function T1(e,t={}){return fh(e,de.SerializationMap.getMap().classNameMap,t,"activation")}function Ws(e){if(e==null){let t={};return t.className="linear",t.config={},T1(t)}if(typeof e=="string"){let t={};return t.className=e,t.config={},T1(t)}else return e instanceof na?e:T1(e)}function oA(e){if(e!=null&&typeof e!="object")throw new Error(`Argument to L1L2 regularizer's constructor is expected to be an object, but received: ${e}`)}var L7=class extends de.Serializable{},xh=class extends L7{constructor(e){super();oA(e),this.l1=e==null||e.l1==null?.01:e.l1,this.l2=e==null||e.l2==null?.01:e.l2,this.hasL1=this.l1!==0,this.hasL2=this.l2!==0}apply(e){return q(()=>{let t=Vt([1]);return this.hasL1&&(t=ue(t,ke(L(this.l1,Qt(e))))),this.hasL2&&(t=ue(t,ke(L(this.l2,yh(e))))),U(t,[])})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}};xh.className="L1L2";de.registerClass(xh);function PV(e){return oA(e),new xh({l1:e!=null?e.l1:null,l2:0})}function OV(e){return oA(e),new xh({l2:e!=null?e.l2:null,l1:0})}var S3={l1l2:"L1L2"};function xt(e){return D2(e)}function T3(e,t={}){return fh(e,de.SerializationMap.getMap().classNameMap,t,"regularizer")}function Mt(e){if(e==null)return null;if(typeof e=="string"){let t={className:e in S3?S3[e]:e,config:{}};return T3(t)}else return e instanceof L7?e:T3(e)}var lA=class extends nt{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=Ve(e);let r=Fn(e);return this.maxValue!=null&&(r=pa(r,0,this.maxValue)),r}computeOutputShape(e){return e}getConfig(){let e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}};lA.className="ReLU";de.registerClass(lA);var uA=class extends nt{constructor(e){super(e==null?{}:e);this.DEFAULT_ALPHA=.3,e==null&&(e={}),this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){let r=Ve(e);return am(r,this.alpha)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};uA.className="LeakyReLU";de.registerClass(uA);var dA=class extends nt{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=Ft(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=Mt(e.alphaRegularizer),this.alphaConstraint=ar(e.alphaConstraint),e.sharedAxes==null)this.sharedAxes=null;else if(Array.isArray(e.sharedAxes))this.sharedAxes=e.sharedAxes;else if(typeof e.sharedAxes=="number")this.sharedAxes=[e.sharedAxes];else throw new H(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=mt(e);let t=e.slice(1);if(this.sharedAxes!=null)for(let a of this.sharedAxes)t[a-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);let r={};if(this.sharedAxes!=null)for(let a=1;a<e.length;++a)r[a]=e[a];this.inputSpec=[new qt({ndim:e.length,axes:r})],this.built=!0}call(e,t){return e=Ve(e),dm(e,this.alpha.read())}getConfig(){let e={alphaInitializer:Pt(this.alphaInitializer),alphaRegularizer:xt(this.alphaRegularizer),alphaConstraint:rr(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}};dA.className="PReLU";de.registerClass(dA);var pA=class extends nt{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA=1,e==null&&(e={}),e.alpha!=null&&e.alpha!==this.DEFAULT_ALPHA)throw new Be(`Non-default alpha value (${e.alpha}) is not supported by the ELU layer yet.`);this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){let r=Ve(e);return uh(r)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};pA.className="ELU";de.registerClass(pA);var hA=class extends nt{constructor(e){super(e==null?{}:e);this.DEFAULT_THETA=1,e==null&&(e={}),this.theta=e.theta==null?this.DEFAULT_THETA:e.theta}call(e,t){let r=Ve(e);return L(r,me(fa(r,this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){let e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}};hA.className="ThresholdedReLU";de.registerClass(hA);var cA=class extends nt{constructor(e){super(e==null?{}:e);this.DEFAULT_AXIS=1,e==null&&(e={}),this.softmax=new iA().apply,this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis}call(e,t){let r=Ve(e);return this.softmax(r,this.axis)}computeOutputShape(e){return e}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};cA.className="Softmax";de.registerClass(cA);function lu(e,t,r){if(typeof e=="number")return ko(e,t);if(e.length!==t)throw new H(`The ${r} argument must be an integer or tuple of ${t} integers. Received: ${e.length} elements.`);for(let a=0;a<t;++a){let n=e[a];if(!tW(n))throw new H(`The ${r} argument must be an integer or tuple of ${t} integers. Received: ${JSON.stringify(e)} including a non-integer number ${n}`)}return e}function sn(e,t,r,a,n=1){if(e==null)return e;let s=t+(t-1)*(n-1),i;return r==="same"?i=e:i=e-s+1,Math.floor((i+a-1)/a)}function kn(e,t,r,a){if(e==null)return null;if(a==="valid")e=e*t+Ls([r-t,0]);else if(a==="same")e=e*t;else throw new H(`Unsupport padding mode: ${a}.`);return e}function fA(e,t){return q(()=>(Ut(t),t==="channelsFirst"?rt(e,[0,2,3,1]):e))}function B7(e,t){return q(()=>(Ut(t),t==="channelsFirst"?rt(e,[0,2,3,4,1]):e))}function zV(e,t,r,a=1,n="valid",s,i=1){return q(()=>{if(s==null&&(s=un()),Ut(s),e.shape.length!==3)throw new H(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(t.shape.length!==3)throw new H(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(r!=null&&r.shape.length!==1)throw new H(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(s==="channelsFirst"&&(e=rt(e,[0,2,1])),n==="causal")throw new Be("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let o=s2(e,t,a,n==="same"?"same":"valid","NWC",i);return r!=null&&(o=fn(o,r)),o})}function C3(e,t,r,a=[1,1],n="valid",s,i,o=null){return q(()=>{if(s==null&&(s=un()),Ut(s),e.rank!==3&&e.rank!==4)throw new H(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(t.rank!==3&&t.rank!==4)throw new H(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=fA(e,s);if(n==="causal")throw new Be("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=_s.conv2d({x:l,filter:t,strides:a,pad:n==="same"?"same":"valid",dilations:i,dataFormat:"NHWC",bias:r,activation:o}),s==="channelsFirst"&&(l=rt(l,[0,3,1,2])),l})}function DV(e,t,r,a=[1,1,1],n="valid",s,i){return q(()=>{if(s==null&&(s=un()),Ut(s),e.rank!==4&&e.rank!==5)throw new H(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(t.rank!==4&&t.rank!==5)throw new H(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let o=B7(e,s);if(n==="causal")throw new Be("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=l2(o,t,a,n==="same"?"same":"valid","NDHWC",i),r!=null&&(o=fn(o,r)),s==="channelsFirst"&&(o=rt(o,[0,4,1,2,3])),o})}var mA=class extends nt{constructor(e,t){super(t);if(this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",mA.verifyArgs(t),this.rank=e,pr(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new Be(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=lu(t.kernelSize,e,"kernelSize"),this.strides=lu(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,Pa(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,Ut(this.dataFormat),this.activation=Ws(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=Ft(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=ar(t.biasConstraint),this.biasRegularizer=Mt(t.biasRegularizer),this.activityRegularizer=Mt(t.activityRegularizer),this.dilationRate=lu(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new H(`dilationRate must be a number or an array of a single number for 1D convolution, but received ${JSON.stringify(this.dilationRate)}`);if(this.rank===2){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==2)throw new H(`dilationRate must be a number or array of two numbers for 2D convolution, but received ${JSON.stringify(this.dilationRate)}`)}else if(this.rank===3){if(typeof this.dilationRate=="number")this.dilationRate=[this.dilationRate,this.dilationRate,this.dilationRate];else if(this.dilationRate.length!==3)throw new H(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if(wn("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!_2(e.kernelSize,"number",1,3))throw new H(`BaseConv expects config.kernelSize to be number or number[] with length 1, 2, or 3, but received ${JSON.stringify(e.kernelSize)}.`)}getConfig(){let e={kernelSize:this.kernelSize,strides:this.strides,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,activation:Bs(this.activation),useBias:this.useBias,biasInitializer:Pt(this.biasInitializer),biasRegularizer:xt(this.biasRegularizer),activityRegularizer:xt(this.activityRegularizer),biasConstraint:rr(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}},bh=class extends mA{constructor(e,t){super(e,t);this.kernel=null,bh.verifyArgs(t),this.filters=t.filters,pr(this.filters,"filters"),this.kernelInitializer=Ft(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=ar(t.kernelConstraint),this.kernelRegularizer=Mt(t.kernelRegularizer)}build(e){e=mt(e);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new H(`The channel dimension of the input should be defined. Found ${e[t]}`);let r=e[t],a=this.kernelSize.concat([r,this.filters]);this.kernel=this.addWeight("kernel",a,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[t]:r}}],this.built=!0}call(e,t){return q(()=>{e=Ve(e);let r,a=this.bias==null?null:this.bias.read(),n=Xk(this.activation.getClassName());if(n!=null&&this.rank===2)r=C3(e,this.kernel.read(),a,this.strides,this.padding,this.dataFormat,this.dilationRate,n);else{if(this.rank===1)r=zV(e,this.kernel.read(),a,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)r=C3(e,this.kernel.read(),a,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)r=DV(e,this.kernel.read(),a,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new Be("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(r=this.activation.apply(r))}return r})}computeOutputShape(e){e=mt(e);let t=[],r=this.dataFormat==="channelsLast"?e.slice(1,e.length-1):e.slice(2);for(let n=0;n<r.length;++n){let s=sn(r[n],this.kernelSize[n],this.padding,this.strides[n],typeof this.dilationRate=="number"?this.dilationRate:this.dilationRate[n]);t.push(s)}let a=[e[0]];return this.dataFormat==="channelsLast"?(a=a.concat(t),a.push(this.filters)):(a.push(this.filters),a=a.concat(t)),a}getConfig(){let e={filters:this.filters,kernelInitializer:Pt(this.kernelInitializer),kernelRegularizer:xt(this.kernelRegularizer),kernelConstraint:rr(this.kernelConstraint)},t=super.getConfig();return Object.assign(e,t),e}static verifyArgs(e){if(!("filters"in e)||typeof e.filters!="number"||e.filters<1)throw new H(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}},W7=class extends bh{constructor(e){super(2,e);W7.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!_2(e.kernelSize,"number",1,2))throw new H(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}},Lm=W7;Lm.className="Conv2D";de.registerClass(Lm);var V7=class extends bh{constructor(e){super(3,e);V7.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!(Array.isArray(e.kernelSize)&&(e.kernelSize.length===1||e.kernelSize.length===3)))throw new H(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}},Bm=V7;Bm.className="Conv3D";de.registerClass(Bm);var gA=class extends Lm{constructor(e){super(e);if(this.inputSpec=[new qt({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new H(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=mt(e),e.length!==4)throw new H("Input should have rank 4; Received input shape: "+JSON.stringify(e));let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new H("The channel dimension of the inputs should be defined. Found `None`.");let r=e[t],a=this.kernelSize.concat([this.filters,r]);this.kernel=this.addWeight("kernel",a,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new qt({ndim:4,axes:{[t]:r}})],this.built=!0}call(e,t){return q(()=>{let r=Ve(e);if(r.shape.length!==4)throw new H(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${r.shape.length}`);let a=r.shape,n=a[0],s,i;this.dataFormat==="channelsFirst"?(s=2,i=3):(s=1,i=2);let o=a[s],l=a[i],d=this.kernelSize[0],u=this.kernelSize[1],p=this.strides[0],h=this.strides[1],c=kn(o,p,d,this.padding),f=kn(l,h,u,this.padding),m=[n,c,f,this.filters];this.dataFormat!=="channelsLast"&&(r=rt(r,[0,2,3,1]));let g=o2(r,this.kernel.read(),m,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(g=rt(g,[0,3,1,2])),this.bias!=null&&(g=fn(g,this.bias.read(),this.dataFormat)),this.activation!=null&&(g=this.activation.apply(g)),g})}computeOutputShape(e){e=mt(e);let t=e.slice(),r,a,n;this.dataFormat==="channelsFirst"?(r=1,a=2,n=3):(r=3,a=1,n=2);let s=this.kernelSize[0],i=this.kernelSize[1],o=this.strides[0],l=this.strides[1];return t[r]=this.filters,t[a]=kn(t[a],o,s,this.padding),t[n]=kn(t[n],l,i,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};gA.className="Conv2DTranspose";de.registerClass(gA);var yA=class extends Bm{constructor(e){super(e);if(this.inputSpec=[new qt({ndim:5})],this.padding!=="same"&&this.padding!=="valid")throw new H(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=mt(e),e.length!==5)throw new H("Input should have rank 5; Received input shape: "+JSON.stringify(e));let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new H("The channel dimension of the inputs should be defined. Found `None`.");let r=e[t],a=this.kernelSize.concat([this.filters,r]);this.kernel=this.addWeight("kernel",a,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new qt({ndim:5,axes:{[t]:r}})],this.built=!0}call(e,t){return q(()=>{let r=Ve(e);if(r.shape.length!==5)throw new H(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${r.shape.length}`);let a=r.shape,n=a[0],s,i,o;this.dataFormat==="channelsFirst"?(o=2,s=3,i=4):(o=1,s=2,i=3);let l=a[o],d=a[s],u=a[i],p=this.kernelSize[0],h=this.kernelSize[1],c=this.kernelSize[2],f=this.strides[0],m=this.strides[1],g=this.strides[2],y=kn(l,f,p,this.padding),A=kn(d,m,h,this.padding),x=kn(u,g,c,this.padding),b=[n,y,A,x,this.filters];this.dataFormat!=="channelsLast"&&(r=rt(r,[0,2,3,4,1]));let v=Zw(r,this.kernel.read(),b,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(v=rt(v,[0,4,1,2,3])),this.bias!==null&&(v=fn(v,this.bias.read(),this.dataFormat)),this.activation!==null&&(v=this.activation.apply(v)),v})}computeOutputShape(e){e=mt(e);let t=e.slice(),r,a,n,s;this.dataFormat==="channelsFirst"?(r=1,a=2,n=3,s=4):(r=4,a=1,n=2,s=3);let i=this.kernelSize[0],o=this.kernelSize[1],l=this.kernelSize[2],d=this.strides[0],u=this.strides[1],p=this.strides[2];return t[r]=this.filters,t[a]=kn(t[a],d,i,this.padding),t[n]=kn(t[n],u,o,this.padding),t[s]=kn(t[s],p,l,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};yA.className="Conv3DTranspose";de.registerClass(yA);var U7=class extends bh{constructor(e,t){super(e,t);if(this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,t.filters==null)throw new H("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new H("Fields kernelInitializer, kernelRegularizer and kernelConstraint are invalid for SeparableConv2D. Use depthwiseInitializer, depthwiseRegularizer, depthwiseConstraint, pointwiseInitializer, pointwiseRegularizer and pointwiseConstraint instead.");if(t.padding!=null&&t.padding!=="same"&&t.padding!=="valid")throw new H(`SeparableConv${this.rank}D supports only padding modes: 'same' and 'valid', but received ${JSON.stringify(t.padding)}`);this.depthMultiplier=t.depthMultiplier==null?1:t.depthMultiplier,this.depthwiseInitializer=Ft(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=Mt(t.depthwiseRegularizer),this.depthwiseConstraint=ar(t.depthwiseConstraint),this.pointwiseInitializer=Ft(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=Mt(t.pointwiseRegularizer),this.pointwiseConstraint=ar(t.pointwiseConstraint)}build(e){if(e=mt(e),e.length<this.rank+2)throw new H(`Inputs to SeparableConv${this.rank}D should have rank ${this.rank+2}, but received input shape: ${JSON.stringify(e)}`);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null||e[t]<0)throw new H(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);let r=e[t],a=this.kernelSize.concat([r,this.depthMultiplier]),n=[];for(let i=0;i<this.rank;++i)n.push(1);n.push(r*this.depthMultiplier,this.filters);let s=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",a,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,s,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",n,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,s,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,s,this.biasConstraint):this.bias=null,this.inputSpec=[new qt({ndim:this.rank+2,axes:{[t]:r}})],this.built=!0}call(e,t){return q(()=>{e=Ve(e);let r;if(this.rank===1)throw new Be("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=rt(e,[0,2,3,1])),r=yk(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(r=fn(r,this.bias.read(),this.dataFormat)),this.activation!=null&&(r=this.activation.apply(r)),this.dataFormat==="channelsFirst"&&(r=rt(r,[0,3,1,2])),r})}getConfig(){let e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=Pt(this.depthwiseInitializer),e.pointwiseInitializer=Pt(this.pointwiseInitializer),e.depthwiseRegularizer=xt(this.depthwiseRegularizer),e.pointwiseRegularizer=xt(this.pointwiseRegularizer),e.depthwiseConstraint=rr(this.depthwiseConstraint),e.pointwiseConstraint=rr(this.pointwiseConstraint),e}};U7.className="SeparableConv";var AA=class extends U7{constructor(e){super(2,e)}};AA.className="SeparableConv2D";de.registerClass(AA);var G7=class extends bh{constructor(e){super(1,e);G7.verifyArgs(e),this.inputSpec=[{ndim:3}]}getConfig(){let e=super.getConfig();return delete e.rank,delete e.dataFormat,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!_2(e.kernelSize,"number",1,1))throw new H(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}},xA=G7;xA.className="Conv1D";de.registerClass(xA);var bA=class extends nt{constructor(e){super(e);typeof e.cropping=="number"?this.cropping=[[e.cropping,e.cropping],[e.cropping,e.cropping]]:typeof e.cropping[0]=="number"?this.cropping=[[e.cropping[0],e.cropping[0]],[e.cropping[1],e.cropping[1]]]:this.cropping=e.cropping,this.dataFormat=e.dataFormat===void 0?"channelsLast":e.dataFormat,this.inputSpec=[{ndim:4}]}computeOutputShape(e){return this.dataFormat==="channelsFirst"?[e[0],e[1],e[2]-this.cropping[0][0]-this.cropping[0][1],e[3]-this.cropping[1][0]-this.cropping[1][1]]:[e[0],e[1]-this.cropping[0][0]-this.cropping[0][1],e[2]-this.cropping[1][0]-this.cropping[1][1],e[3]]}call(e,t){return q(()=>{if(e=Ve(e),this.dataFormat==="channelsLast"){let r=Tc(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Tc(r,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{let r=Tc(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Tc(r,this.cropping[1][0],e.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}})}getConfig(){let e={cropping:this.cropping,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};bA.className="Cropping2D";de.registerClass(bA);var vA=class extends nt{constructor(e){super(e);this.DEFAULT_SIZE=[2,2],this.inputSpec=[{ndim:4}],this.size=e.size==null?this.DEFAULT_SIZE:e.size,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Ut(this.dataFormat),this.interpolation=e.interpolation==null?"nearest":e.interpolation,JB(this.interpolation)}computeOutputShape(e){if(this.dataFormat==="channelsFirst"){let t=e[2]==null?null:this.size[0]*e[2],r=e[3]==null?null:this.size[1]*e[3];return[e[0],e[1],t,r]}else{let t=e[1]==null?null:this.size[0]*e[1],r=e[2]==null?null:this.size[1]*e[2];return[e[0],t,r,e[3]]}}call(e,t){return q(()=>{let r=Ve(e),a=r.shape;if(this.dataFormat==="channelsFirst"){r=rt(r,[0,2,3,1]);let n=this.size[0]*a[2],s=this.size[1]*a[3],i=this.interpolation==="nearest"?Ie.resizeNearestNeighbor(r,[n,s]):Ie.resizeBilinear(r,[n,s]);return rt(i,[0,3,1,2])}else{let n=this.size[0]*a[1],s=this.size[1]*a[2];return this.interpolation==="nearest"?Ie.resizeNearestNeighbor(r,[n,s]):Ie.resizeBilinear(r,[n,s])}})}getConfig(){let e={size:this.size,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};vA.className="UpSampling2D";de.registerClass(vA);function _V(e,t,r=[1,1],a="valid",n,s){return q(()=>{n==null&&(n=un()),Ut(n);let i=fA(e,n);if(e.rank!==4)throw new H(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(t.rank!==4)throw new H(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return i=lh(i,t,r,a==="same"?"same":"valid","NHWC",s),n==="channelsFirst"&&(i=rt(i,[0,3,1,2])),i})}var wA=class extends mA{constructor(e){super(2,e);this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=Ft(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=ar(e.depthwiseConstraint),this.depthwiseRegularizer=Mt(e.depthwiseRegularizer)}build(e){if(e=mt(e),e.length<4)throw new H(`Inputs to DepthwiseConv2D should have rank 4. Received input shape: ${JSON.stringify(e)}.`);let t=this.dataFormat==="channelsFirst"?1:3;if(e[t]==null||e[t]<0)throw new H(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);let r=e[t],a=[this.kernelSize[0],this.kernelSize[1],r,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",a,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[r*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return q(()=>{e=Ve(e);let r=_V(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(r=fn(r,this.bias.read(),this.dataFormat)),this.activation!=null&&(r=this.activation.apply(r)),r})}computeOutputShape(e){e=mt(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],r=this.dataFormat==="channelsFirst"?e[3]:e[2],a=this.dataFormat==="channelsFirst"?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,n=sn(t,this.kernelSize[0],this.padding,this.strides[0]),s=sn(r,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[e[0],a,n,s]:[e[0],n,s,a]}getConfig(){let e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=Pt(this.depthwiseInitializer),e.depthwiseRegularizer=xt(this.depthwiseRegularizer),e.depthwiseConstraint=rr(this.depthwiseRegularizer),e}};wA.className="DepthwiseConv2D";de.registerClass(wA);function j7(e,t,r,a){if(Array.isArray(e)){if(t!=null||r!=null)throw new H("When inputs is an array, neither initialState or constants should be provided");a!=null&&(r=e.slice(e.length-a,e.length),e=e.slice(0,e.length-a)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function n(s){return s==null||Array.isArray(s)?s:[s]}return t=n(t),r=n(r),{inputs:e,initialState:t,constants:r}}function H7(e,t,r,a=!1,n,s,i=!1,o=!1){return q(()=>{let l=t.shape.length;if(l<3)throw new H(`Input should be at least 3D, but is ${l}D.`);let d=[1,0].concat(dn(2,l));if(t=rt(t,d),s!=null)throw new Be("The rnn() functoin of the deeplearn.js backend does not support constants yet.");i&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),n!=null&&(n=me(me(n,"bool"),"float32"),n.rank===l-1&&(n=Ht(n,-1)),n=rt(n,d)),a&&(t=Fa(t,0),n!=null&&(n=Fa(n,0)));let u=[],p,h=r,c=t.shape[0],f=ra(t),m;n!=null&&(m=ra(n));for(let y=0;y<c;++y){let A=f[y],x=q(()=>e(A,h));if(n==null)p=x[0],h=x[1];else{let b=q(()=>{let v=m[y],C=he(Ra(v),v),T=ue(L(x[0],v),L(h[0],C)),E=h.map((R,z)=>ue(L(x[1][z],v),L(R,C)));return{output:T,newStates:E}});p=b.output,h=b.newStates}o&&u.push(p)}let g;return o&&(g=nr(u,1)),[p,g,h]})}var q7=class extends nt{constructor(e){super(e);let t;if(e.cell==null)throw new H("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new Um({cells:e.cell}):t=e.cell,t.stateSize==null)throw new H("The RNN cell should have an attribute `stateSize` (tuple of integers, one integer per RNN state).");this.cell=t,this.returnSequences=e.returnSequences==null?!1:e.returnSequences,this.returnState=e.returnState==null?!1:e.returnState,this.goBackwards=e.goBackwards==null?!1:e.goBackwards,this._stateful=e.stateful==null?!1:e.stateful,this.unroll=e.unroll==null?!1:e.unroll,this.supportsMasking=!0,this.inputSpec=[new qt({ndim:3})],this.stateSpec=null,this.states_=null,this.numConstants=null,this.keptStates=[]}getStates(){if(this.states_==null){let e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;return dn(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){X1(e)&&(e=e[0]),e=e;let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);let r=t[0],a;if(this.returnSequences?a=[e[0],e[1],r]:a=[e[0],r],this.returnState){let n=[];for(let s of t)n.push([e[0],s]);return[a].concat(n)}else return a}computeMask(e,t){return q(()=>{Array.isArray(t)&&(t=t[0]);let r=this.returnSequences?t:null;if(this.returnState){let a=this.states.map(n=>null);return[r].concat(a)}else return r})}get states(){if(this.states_==null){let e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let r=0;r<e;++r)t.push(null);return t}else return this.states_}set states(e){this.states_=e}build(e){if(this.numConstants!=null)throw new Be("Constants support is not implemented in RNN yet.");X1(e)&&(e=e[0]),e=e;let t=this.stateful?e[0]:null,r=e.slice(2);this.inputSpec[0]=new qt({shape:[t,null,...r]});let a=[e[0]].concat(e.slice(2));this.cell.build(a);let n;if(Array.isArray(this.cell.stateSize)?n=this.cell.stateSize:n=[this.cell.stateSize],this.stateSpec!=null){if(!w.arraysEqual(this.stateSpec.map(s=>s.shape[s.shape.length-1]),n))throw new H(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=n.map(s=>new qt({shape:[null,s]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){q(()=>{if(!this.stateful)throw new Bn("Cannot call resetStates() on an RNN Layer that is not stateful.");let r=this.inputSpec[0].shape[0];if(r==null)throw new H("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.states_==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(a=>Vt([r,a])):this.states_=[Vt([r,this.cell.stateSize])];else if(e==null)re(this.states_),this.keptStates!=null&&(re(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(a=>Vt([r,a])):this.states_[0]=Vt([r,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new H(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t===!0?this.keptStates.push(this.states_.slice()):re(this.states_);for(let a=0;a<this.states_.length;++a){let n=e[a],s=Array.isArray(this.cell.stateSize)?this.cell.stateSize[a]:this.cell.stateSize,i=[r,s];if(!w.arraysEqual(n.shape,i))throw new H(`State ${a} is incompatible with layer ${this.name}: expected shape=${i}, received shape=${n.shape}`);this.states_[a]=n}}this.states_=this.states_.map(a=>dr(a.clone()))})}apply(e,t){let r=t==null?null:t.initialState,a=t==null?null:t.constants;t==null&&(t={});let n=j7(e,r,a,this.numConstants);e=n.inputs,r=n.initialState,a=n.constants;let s=[],i=[];if(r!=null){t.initialState=r,s=s.concat(r),this.stateSpec=[];for(let o of r)this.stateSpec.push(new qt({shape:o.shape}));i=i.concat(this.stateSpec)}if(a!=null&&(t.constants=a,s=s.concat(a),this.numConstants=a.length),s[0]instanceof tn){let o=[e].concat(s),l=this.inputSpec.concat(i),d=this.inputSpec;this.inputSpec=l;let u=super.apply(o,t);return this.inputSpec=d,u}else return super.apply(e,t)}call(e,t){return q(()=>{let r=t==null?null:t.mask,a=t==null?null:t.training,n=t==null?null:t.initialState;e=Ve(e),n==null&&(this.stateful?n=this.states_:n=this.getInitialState(e));let s=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(n.length!==s)throw new H(`RNN Layer has ${s} state(s) but was passed ${n.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");let i={training:a},o=H7((h,c)=>{let f=this.cell.call([h].concat(c),i);return[f[0],f.slice(1)]},e,n,this.goBackwards,r,null,this.unroll,this.returnSequences),l=o[0],d=o[1],u=o[2];this.stateful&&this.resetStates(u,a);let p=this.returnSequences?d:l;return this.returnState?[p].concat(u):p})}getInitialState(e){return q(()=>{let t=Vt(e.shape);return t=ke(t,[1,2]),t=gh(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(r=>r>1?q1(t,[1,r]):t):this.cell.stateSize>1?[q1(t,[1,this.cell.stateSize])]:[t]})}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.cell!=null&&this.cell.setFastWeightInitDuringBuild(e)}getConfig(){let e=super.getConfig(),t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};this.numConstants!=null&&(t.numConstants=this.numConstants);let r=this.cell.getConfig();return this.getClassName()===q7.className&&(t.cell={className:this.cell.getClassName(),config:r}),{...r,...e,...t}}static fromConfig(e,t,r={}){let a=t.cell,n=nn(a,r);return new e(Object.assign(t,{cell:n}))}},Qn=q7;Qn.className="RNN";de.registerClass(Qn);var vh=class extends nt{},Wm=class extends vh{constructor(e){super(e);this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,pr(this.units,"units"),this.activation=Ws(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Ft(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ft(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ft(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Mt(e.kernelRegularizer),this.recurrentRegularizer=Mt(e.recurrentRegularizer),this.biasRegularizer=Mt(e.biasRegularizer),this.kernelConstraint=ar(e.kernelConstraint),this.recurrentConstraint=ar(e.recurrentConstraint),this.biasConstraint=ar(e.biasConstraint),this.dropout=yu([1,Ls([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=yu([1,Ls([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=mt(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return q(()=>{if(e=e,e.length!==2)throw new H(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let r=e[1];e=e[0];let a=t.training==null?!1:t.training;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Vs({ones:()=>Ra(e),rate:this.dropout,training:a,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Vs({ones:()=>Ra(r),rate:this.recurrentDropout,training:a,dropoutFunc:this.dropoutFunc}));let n,s=this.dropoutMask,i=this.recurrentDropoutMask;s!=null?n=Sn(L(e,s),this.kernel.read()):n=Sn(e,this.kernel.read()),this.bias!=null&&(n=fn(n,this.bias.read())),i!=null&&(r=L(r,i));let o=ue(n,Sn(r,this.recurrentKernel.read()));return this.activation!=null&&(o=this.activation.apply(o)),[o,o]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:Bs(this.activation),useBias:this.useBias,kernelInitializer:Pt(this.kernelInitializer),recurrentInitializer:Pt(this.recurrentInitializer),biasInitializer:Pt(this.biasInitializer),kernelRegularizer:xt(this.kernelRegularizer),recurrentRegularizer:xt(this.recurrentRegularizer),biasRegularizer:xt(this.biasRegularizer),activityRegularizer:xt(this.activityRegularizer),kernelConstraint:rr(this.kernelConstraint),recurrentConstraint:rr(this.recurrentConstraint),biasConstraint:rr(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return{...e,...t}}};Wm.className="SimpleRNNCell";de.registerClass(Wm);var kA=class extends Qn{constructor(e){e.cell=new Wm(e);super(e)}call(e,t){return q(()=>{this.cell.dropoutMask!=null&&(re(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(re(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let r=t==null?null:t.mask,a=t==null?null:t.training,n=t==null?null:t.initialState;return super.call(e,{mask:r,training:a,initialState:n})})}static fromConfig(e,t){return new e(t)}};kA.className="SimpleRNN";de.registerClass(kA);var Vm=class extends vh{constructor(e){super(e);if(this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.resetAfter)throw new H("GRUCell does not support reset_after parameter set to true.");this.units=e.units,pr(this.units,"units"),this.activation=Ws(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Ws(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Ft(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ft(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ft(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Mt(e.kernelRegularizer),this.recurrentRegularizer=Mt(e.recurrentRegularizer),this.biasRegularizer=Mt(e.biasRegularizer),this.kernelConstraint=ar(e.kernelConstraint),this.recurrentConstraint=ar(e.recurrentConstraint),this.biasConstraint=ar(e.biasConstraint),this.dropout=yu([1,Ls([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=yu([1,Ls([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=mt(e);let t=e[e.length-1];this.kernel=this.addWeight("kernel",[t,this.units*3],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*3],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units*3],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return q(()=>{if(e=e,e.length!==2)throw new H(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);let r=t.training==null?!1:t.training,a=e[1];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Vs({ones:()=>Ra(e),rate:this.dropout,training:r,count:3,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Vs({ones:()=>Ra(a),rate:this.recurrentDropout,training:r,count:3,dropoutFunc:this.dropoutFunc}));let n=this.dropoutMask,s=this.recurrentDropoutMask,i,o,l;0<this.dropout&&this.dropout<1&&(e=L(e,n[0]));let d=Sn(e,this.kernel.read());this.useBias&&(d=fn(d,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(a=L(a,s[0]));let u=this.recurrentKernel.read(),[p,h]=Kt(u,[2*this.units,this.units],u.rank-1),c=Sn(a,p),[f,m,g]=Kt(d,3,d.rank-1),[y,A]=Kt(c,2,c.rank-1);i=this.recurrentActivation.apply(ue(f,y)),o=this.recurrentActivation.apply(ue(m,A));let x=Sn(L(o,a),h);l=this.activation.apply(ue(g,x));let b=ue(L(i,a),L(ue(1,zt(i)),l));return[b,b]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:Bs(this.activation),recurrentActivation:Bs(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Pt(this.kernelInitializer),recurrentInitializer:Pt(this.recurrentInitializer),biasInitializer:Pt(this.biasInitializer),kernelRegularizer:xt(this.kernelRegularizer),recurrentRegularizer:xt(this.recurrentRegularizer),biasRegularizer:xt(this.biasRegularizer),activityRegularizer:xt(this.activityRegularizer),kernelConstraint:rr(this.kernelConstraint),recurrentConstraint:rr(this.recurrentConstraint),biasConstraint:rr(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return{...e,...t}}};Vm.className="GRUCell";de.registerClass(Vm);var IA=class extends Qn{constructor(e){e.implementation===0&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new Vm(e);super(e)}call(e,t){return q(()=>{this.cell.dropoutMask!=null&&(re(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(re(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let r=t==null?null:t.mask,a=t==null?null:t.training,n=t==null?null:t.initialState;return super.call(e,{mask:r,training:a,initialState:n})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};IA.className="GRU";de.registerClass(IA);var wh=class extends vh{constructor(e){super(e);this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",this.units=e.units,pr(this.units,"units"),this.activation=Ws(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Ws(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Ft(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Ft(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Ft(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=Mt(e.kernelRegularizer),this.recurrentRegularizer=Mt(e.recurrentRegularizer),this.biasRegularizer=Mt(e.biasRegularizer),this.kernelConstraint=ar(e.kernelConstraint),this.recurrentConstraint=ar(e.recurrentConstraint),this.biasConstraint=ar(e.biasConstraint),this.dropout=yu([1,Ls([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=yu([1,Ls([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;e=mt(e);let r=e[e.length-1];this.kernel=this.addWeight("kernel",[r,this.units*4],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*4],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint);let a;if(this.useBias){if(this.unitForgetBias){let n=this.biasInitializer,s=this.units;a=new(t=class extends qa{apply(i,o){let l=n.apply([s]),d=new Cm().apply([s]),u=n.apply([s*2]);return h3(h3(l,d),u)}},t.className="CustomInit",t)}else a=this.biasInitializer;this.bias=this.addWeight("bias",[this.units*4],null,a,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return q(()=>{let r=t.training==null?!1:t.training;if(e=e,e.length!==3)throw new H(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let a=e[1],n=e[2];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Vs({ones:()=>Ra(e),rate:this.dropout,training:r,count:4,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Vs({ones:()=>Ra(a),rate:this.recurrentDropout,training:r,count:4,dropoutFunc:this.dropoutFunc}));let s=this.dropoutMask,i=this.recurrentDropoutMask,o,l,d,u;0<this.dropout&&this.dropout<1&&(e=L(e,s[0]));let p=Sn(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(a=L(a,i[0])),p=ue(p,Sn(a,this.recurrentKernel.read())),this.useBias&&(p=fn(p,this.bias.read()));let[h,c,f,m]=Kt(p,4,p.rank-1);o=this.recurrentActivation.apply(h),l=this.recurrentActivation.apply(c),d=ue(L(l,n),L(o,this.activation.apply(f))),u=this.recurrentActivation.apply(m);let g=L(u,this.activation.apply(d));return[g,g,d]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:Bs(this.activation),recurrentActivation:Bs(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Pt(this.kernelInitializer),recurrentInitializer:Pt(this.recurrentInitializer),biasInitializer:Pt(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:xt(this.kernelRegularizer),recurrentRegularizer:xt(this.recurrentRegularizer),biasRegularizer:xt(this.biasRegularizer),activityRegularizer:xt(this.activityRegularizer),kernelConstraint:rr(this.kernelConstraint),recurrentConstraint:rr(this.recurrentConstraint),biasConstraint:rr(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return{...e,...t}}};wh.className="LSTMCell";de.registerClass(wh);var SA=class extends Qn{constructor(e){e.implementation===0&&console.warn("`implementation=0` has been deprecated, and now defaults to `implementation=1`. Please update your layer call."),e.cell=new wh(e);super(e)}call(e,t){return q(()=>{this.cell.dropoutMask!=null&&(re(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(re(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let r=t==null?null:t.mask,a=t==null?null:t.training,n=t==null?null:t.initialState;return super.call(e,{mask:r,training:a,initialState:n})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};SA.className="LSTM";de.registerClass(SA);var Um=class extends vh{constructor(e){super(e);this.cells=e.cells}get stateSize(){let e=[];for(let t of this.cells.slice().reverse())Array.isArray(t.stateSize)?e.push(...t.stateSize):e.push(t.stateSize);return e}call(e,t){return q(()=>{e=e;let r=e.slice(1),a=[];for(let i of this.cells.slice().reverse())Array.isArray(i.stateSize)?a.push(r.splice(0,i.stateSize.length)):a.push(r.splice(0,1));a.reverse();let n=[],s;for(let i=0;i<this.cells.length;++i){let o=this.cells[i];r=a[i],i===0?s=[e[0]].concat(r):s=[s[0]].concat(r),s=o.call(s,t),n.push(s.slice(1))}r=[];for(let i of n.slice().reverse())r.push(...i);return[s[0]].concat(r)})}build(e){X1(e)&&(e=e[0]),e=e;let t;this.cells.forEach((r,a)=>{mo(`RNNCell_${a}`,()=>{r.build(e),Array.isArray(r.stateSize)?t=r.stateSize[0]:t=r.stateSize,e=[e[0],t]})}),this.built=!0}getConfig(){let e=super.getConfig(),t=a=>({className:a.getClassName(),config:a.getConfig()}),r={cells:this.cells.map(t)};return{...e,...r}}static fromConfig(e,t,r={}){let a=[];for(let n of t.cells)a.push(nn(n,r));return new e({cells:a})}get trainableWeights(){if(!this.trainable)return[];let e=[];for(let t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){let e=[];for(let t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){let t=[];for(let r of this.cells)t.push(...r.trainableWeights);return t.concat(e)}return e}getWeights(){let e=[];for(let t of this.cells)e.push(...t.weights);return Z1(e)}setWeights(e){let t=[];for(let r of this.cells){let a=r.weights.length,n=e.splice(a);for(let s=0;s<r.weights.length;++s)t.push([r.weights[s],n[s]])}J2(t)}};Um.className="StackedRNNCells";de.registerClass(Um);function Vs(e){let{ones:t,rate:r,training:a=!1,count:n=1,dropoutFunc:s}=e,i=()=>s!=null?s(t(),r):r7(t(),r),o=()=>Ah(i,t,a);return!n||n<=1?dr(o().clone()):Array(n).fill(void 0).map(o).map(l=>dr(l.clone()))}var K7=class extends Qn{constructor(e){if(e.unroll)throw new Be("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new Be("It is not possible at the moment to stack convolutional cells.");super(e);this.inputSpec=[new qt({ndim:5})]}call(e,t){return q(()=>{if(this.cell.dropoutMask!=null&&(re(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(re(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new H("ConvRNN2D cell does not support constants");let r=t==null?null:t.mask,a=t==null?null:t.training,n=t==null?null:t.initialState;return super.call(e,{mask:r,training:a,initialState:n})})}computeOutputShape(e){let t=this.computeSingleOutputShape(e);return this.returnSequences||(t=[t[0],...t.slice(2)]),this.returnState&&(t=[t,...Array(2).fill([e[0],...t.slice(-3)])]),t}getInitialState(e){return q(()=>{let{stateSize:t}=this.cell,r=e.shape,a=this.computeSingleOutputShape(r),n=[a[0],...a.slice(2)],s=Vt(n);return Array.isArray(t)?Array(t.length).fill(s):[s]})}resetStates(e,t=!1){q(()=>{if(!this.stateful)throw new Bn("Cannot call resetStates() on an RNN Layer that is not stateful.");let r=this.inputSpec[0].shape,a=this.computeSingleOutputShape(r),n=[a[0],...a.slice(2)];if(r[0]==null)throw new H("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.getStates()==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>Vt(n)):this.states_=[Vt(n)];else if(e==null)re(this.states_),this.keptStates!=null&&(re(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>Vt(n)):this.states_[0]=Vt(n);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new H(`Layer ${this.name} expects ${this.states_.length} state(s), but it received ${e.length} state value(s). Input received: ${e}`);t?this.keptStates.push(this.states_.slice()):re(this.states_);for(let s=0;s<this.states_.length;++s){let i=e[s],o=n;if(!w.arraysEqual(i.shape,o))throw new H(`State ${s} is incompatible with layer ${this.name}: expected shape=${o}, received shape=${i.shape}`);this.states_[s]=i}}this.states_=this.states_.map(s=>dr(s.clone()))})}computeSingleOutputShape(e){let{dataFormat:t,filters:r,kernelSize:a,padding:n,strides:s,dilationRate:i}=this.cell,o=t==="channelsFirst",l=e[o?3:2],d=e[o?4:3],u=sn(l,a[0],n,s[0],i[0]),p=sn(d,a[1],n,s[1],i[1]);return[...e.slice(0,2),...o?[r,u,p]:[u,p,r]]}};K7.className="ConvRNN2D";var Gm=class extends wh{constructor(e){let{filters:t,kernelSize:r,strides:a,padding:n,dataFormat:s,dilationRate:i}=e;super({...e,units:t});this.filters=t,pr(this.filters,"filters"),this.kernelSize=lu(r,2,"kernelSize"),this.kernelSize.forEach(o=>pr(o,"kernelSize")),this.strides=lu(a||1,2,"strides"),this.strides.forEach(o=>pr(o,"strides")),this.padding=n||"valid",Pa(this.padding),this.dataFormat=s||"channelsLast",Ut(this.dataFormat),this.dilationRate=lu(i||1,2,"dilationRate"),this.dilationRate.forEach(o=>pr(o,"dilationRate"))}build(e){var t;e=mt(e);let r=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[r]==null)throw new H(`The channel dimension of the input should be defined. Found ${e[r]}`);let a=e[r],n=4,s=this.kernelSize.concat([a,this.filters*n]);this.kernel=this.addWeight("kernel",s,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);let i=this.kernelSize.concat([this.filters,this.filters*n]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",i,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let o;if(this.unitForgetBias){let l=this.biasInitializer,d=this.filters;o=new(t=class extends qa{apply(u,p){let h=l.apply([d]),c=da([d]),f=l.apply([d*2]);return G2([h,c,f])}},t.className="CustomInit",t)}else o=this.biasInitializer;this.bias=this.addWeight("bias",[this.filters*n],null,o,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return q(()=>{if(e.length!==3)throw new H(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let r=t.training||!1,a=e[0],n=e[1],s=e[2],i=4;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Vs({ones:()=>Ra(a),rate:this.dropout,training:r,count:i,dropoutFunc:this.dropoutFunc}));let o=this.dropoutMask,l=(W,ee,Q)=>!ee||!ee[Q]?W:L(ee[Q],W),d=l(a,o,0),u=l(a,o,1),p=l(a,o,2),h=l(a,o,3);0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Vs({ones:()=>Ra(n),rate:this.recurrentDropout,training:r,count:i,dropoutFunc:this.dropoutFunc}));let c=this.recurrentDropoutMask,f=l(n,c,0),m=l(n,c,1),g=l(n,c,2),y=l(n,c,3),A=3,[x,b,v,C]=Kt(this.kernel.read(),i,A),[T,E,R,z]=this.useBias?Kt(this.bias.read(),i):[null,null,null,null];d=this.inputConv(d,x,T,this.padding),u=this.inputConv(u,b,E,this.padding),p=this.inputConv(p,v,R,this.padding),h=this.inputConv(h,C,z,this.padding);let[M,I,D,O]=Kt(this.recurrentKernel.read(),i,A);f=this.recurrentConv(f,M),m=this.recurrentConv(m,I),g=this.recurrentConv(g,D),y=this.recurrentConv(y,O);let j=this.recurrentActivation.apply(ue(d,f)),X=this.recurrentActivation.apply(ue(u,m)),_=ue(L(X,s),L(j,this.activation.apply(ue(p,g)))),K=L(this.recurrentActivation.apply(ue(h,y)),this.activation.apply(_));return[K,K,_]})}getConfig(){let{units:e,...t}=super.getConfig(),r={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return{...t,...r}}inputConv(e,t,r,a){let n=Os(e,t,this.strides,a||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return r?fn(n,r,this.dataFormat):n}recurrentConv(e,t){return Os(e,t,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}};Gm.className="ConvLSTM2DCell";de.registerClass(Gm);var TA=class extends K7{constructor(e){let t=new Gm(e);super({...e,cell:t})}static fromConfig(e,t){return new e(t)}};TA.className="ConvLSTM2D";de.registerClass(TA);var jm=class extends nt{constructor(e){super(e);this.rate=Math.max(Math.min(e.rate,1),0),this.noiseShape=e.noiseShape,this.seed=e.seed,this.supportsMasking=!0}getNoiseShape(e){if(this.noiseShape==null)return this.noiseShape;let t=e.shape,r=[];for(let a=0;a<this.noiseShape.length;++a)r.push(this.noiseShape[a]==null?t[a]:this.noiseShape[a]);return r}call(e,t){return q(()=>{this.invokeCallHook(e,t);let r=Ve(e);if(0<this.rate&&this.rate<1){let a=t.training==null?!1:t.training,n=this.getNoiseShape(r);return Ah(()=>r7(r,this.rate,n,this.seed),()=>r,a)}return e})}getConfig(){let e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}};jm.className="Dropout";de.registerClass(jm);var CA=class extends jm{constructor(e){super(e);this.inputSpec=[{ndim:3}]}getNoiseShape(e){let t=e.shape;return[t[0],1,t[2]]}};CA.className="SpatialDropout1D";de.registerClass(CA);var NA=class extends nt{constructor(e){super(e);if(this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.batchInputShape==null&&e.inputShape==null&&e.inputDim!=null){let t=null;e.batchSize!=null&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,pr(this.units,"units"),this.activation=Ws(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=Ft(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=Ft(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=ar(e.kernelConstraint),this.biasConstraint=ar(e.biasConstraint),this.kernelRegularizer=Mt(e.kernelRegularizer),this.biasRegularizer=Mt(e.biasRegularizer),this.activityRegularizer=Mt(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=mt(e);let t=e[e.length-1];this.kernel==null&&(this.kernel=this.addWeight("kernel",[t,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:{[-1]:t}}],this.built=!0}computeOutputShape(e){e=mt(e);let t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return q(()=>{this.invokeCallHook(e,t);let r=Ve(e),a=Xk(this.activation.getClassName()),n;return a!=null?n=Sn(r,this.kernel.read(),a,this.bias?this.bias.read():null):(n=Sn(r,this.kernel.read()),this.bias!=null&&(n=fn(n,this.bias.read())),this.activation!=null&&(n=this.activation.apply(n))),n})}getConfig(){let e={units:this.units,activation:Bs(this.activation),useBias:this.useBias,kernelInitializer:Pt(this.kernelInitializer),biasInitializer:Pt(this.biasInitializer),kernelRegularizer:xt(this.kernelRegularizer),biasRegularizer:xt(this.biasRegularizer),activityRegularizer:xt(this.activityRegularizer),kernelConstraint:rr(this.kernelConstraint),biasConstraint:rr(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}};NA.className="Dense";de.registerClass(NA);var EA=class extends nt{constructor(e){e=e||{};super(e);this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=mt(e);for(let t of e.slice(1))if(t==null)throw new H(`The shape of the input to "Flatten" is not fully defined (got ${e.slice(1)}). Make sure to pass a complete "input_shape" or "batch_input_shape" argument to the first layer in your model.`);return[e[0],Ns(e,1)]}call(e,t){return q(()=>{this.invokeCallHook(e,t);let r=Ve(e);if(this.dataFormat==="channelsFirst"&&r.rank>1){let a=[0];for(let n=2;n<r.rank;++n)a.push(n);a.push(1),r=rt(r,a)}return nW(r)})}getConfig(){let e={};this.dataFormat!=null&&(e.dataFormat=this.dataFormat);let t=super.getConfig();return Object.assign(e,t),e}};EA.className="Flatten";de.registerClass(EA);var RA=class extends nt{constructor(e){super(e);this.supportsMasking=!0,this.activation=Ws(e.activation)}call(e,t){return q(()=>{this.invokeCallHook(e,t);let r=Ve(e);return this.activation.apply(r)})}getConfig(){let e={activation:Bs(this.activation)},t=super.getConfig();return Object.assign(e,t),e}};RA.className="Activation";de.registerClass(RA);var FA=class extends nt{constructor(e){super(e);this.n=e.n,this.inputSpec=[{ndim:2}]}computeOutputShape(e){return[e[0],this.n,e[1]]}call(e,t){return q(()=>(e=Ve(e),rW(e,this.n)))}getConfig(){let e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}};FA.className="RepeatVector";de.registerClass(FA);var MA=class extends nt{constructor(e){super(e);this.targetShape=e.targetShape;for(let t=0;t<this.targetShape.length;++t)this.isUnknown(this.targetShape[t])&&(this.targetShape[t]=null)}isUnknown(e){return e<0||e==null}fixUnknownDimension(e,t){let r="Total size of new array must be unchanged.",a=t.slice(),n=1,s=null;for(let o=0;o<a.length;++o){let l=a[o];if(this.isUnknown(l))if(s===null)s=o;else throw new H("Can only specifiy one unknown dimension.");else n*=l}let i=Ns(e);if(s!==null){if(n===0||i%n!==0)throw new H(r);a[s]=i/n}else if(i!==n)throw new H(r);return a}computeOutputShape(e){let t=!1;for(let r=0;r<e.length;++r)if(this.isUnknown(e[r])){t=!0;break}return t?e.slice(0,1).concat(this.targetShape):e.slice(0,1).concat(this.fixUnknownDimension(e.slice(1),this.targetShape))}call(e,t){return q(()=>{this.invokeCallHook(e,t);let r=Ve(e),a=r.shape,n=a.slice(0,1).concat(this.fixUnknownDimension(a.slice(1),this.targetShape));return U(r,n)})}getConfig(){let e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}};MA.className="Reshape";de.registerClass(MA);var $A=class extends nt{constructor(e){super(e);if(e.dims==null)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);let t=dn(1,e.dims.length+1);if(!w.arraysEqual(e.dims.slice().sort(),t))throw new Error("Invalid permutation `dims`: "+JSON.stringify(e.dims)+" `dims` must contain consecutive integers starting from 1.");this.dims=e.dims,this.dimsIncludingBatch=[0].concat(this.dims),this.inputSpec=[new qt({ndim:this.dims.length+1})]}computeOutputShape(e){e=mt(e);let t=e.slice();return this.dims.forEach((r,a)=>{t[a+1]=e[r]}),t}call(e,t){return rt(Ve(e),this.dimsIncludingBatch)}getConfig(){let e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}};$A.className="Permute";de.registerClass($A);var PA=class extends nt{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null?this.maskValue=e.maskValue==null?0:e.maskValue:this.maskValue=0}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){let r=Ve(e),a=-1;return rf(mu(r,this.maskValue),a)}call(e,t){return q(()=>{this.invokeCallHook(e,t);let r=Ve(e),a=-1,n=!0,s=rf(mu(r,this.maskValue),a,n);return L(r,me(s,r.dtype))})}};PA.className="Masking";de.registerClass(PA);var OA=class extends nt{constructor(e){super(e);if(this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",e.batchInputShape==null&&e.inputShape==null){let t=null;e.batchSize!=null&&(t=e.batchSize),e.inputLength==null?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(It(e.inputLength))}this.inputDim=e.inputDim,pr(this.inputDim,"inputDim"),this.outputDim=e.outputDim,pr(this.outputDim,"outputDim"),this.embeddingsInitializer=Ft(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=Mt(e.embeddingsRegularizer),this.activityRegularizer=Mt(e.activityRegularizer),this.embeddingsConstraint=ar(e.embeddingsConstraint),this.maskZero=e.maskZero,this.supportsMasking=e.maskZero,this.inputLength=e.inputLength}build(e){this.embeddings=this.addWeight("embeddings",[this.inputDim,this.outputDim],this.dtype,this.embeddingsInitializer,this.embeddingsRegularizer,!0,this.embeddingsConstraint),this.built=!0}warnOnIncompatibleInputShape(e){}computeMask(e,t){return q(()=>this.maskZero?(e=Ve(e),mu(e,at(e))):null)}computeOutputShape(e){if(e=mt(e),this.inputLength==null)return[...e,this.outputDim];let t=It(this.inputLength);if(t.length!==e.length-1)throw new H(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let r=0;for(let a=0;a<t.length;++a){let n=t[a],s=e[a+1];if(n!=null&&s!=null&&n!==s)throw new H(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);n==null&&(t[r]=s),r++}}return[e[0],...t,this.outputDim]}call(e,t){return q(()=>{this.invokeCallHook(e,t);let r=Ve(e);r.dtype!=="int32"&&(r=Sm(r,"int32"));let a=t7(this.embeddings.read(),U(r,[r.size]));return U(a,mt(this.computeOutputShape(r.shape)))})}getConfig(){let e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Pt(this.embeddingsInitializer),embeddingsRegularizer:xt(this.embeddingsRegularizer),activityRegularizer:xt(this.activityRegularizer),embeddingsConstraint:rr(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}};OA.className="Embedding";de.registerClass(OA);var Il=class extends nt{constructor(e){super(e||{});this.supportsMasking=!0}mergeFunction(e){throw new Be}computeElementwiseOpOutputShape(e,t){if(e==null||t==null)return null;if(e.length<t.length)return this.computeElementwiseOpOutputShape(t,e);if(t.length===0)return e;let r=e.slice(0,e.length-t.length);for(let a=0;a<t.length;++a){let n=e[e.length-t.length+a],s=t[a];if(n==null||s==null||n<0||s<0)r.push(null);else if(n===1)r.push(s);else if(s===1)r.push(n);else{if(n!==s)throw new H("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));r.push(n)}}return r}build(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[mt(e)]),e=e,e.length<2)throw new H(`A merge layer should be called on an Array of at least 2 inputs. Got ${e.length} input(s).`);let t=[];for(let n of e)n!=null&&n[0]!==null&&t.push(n[0]);if(t=Cs(t),t.length>1)throw new H(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let r=e[0]==null?null:e[0].slice(1);for(let n=1;n<e.length;++n){let s=e[n]==null?null:e[n].slice(1);r=this.computeElementwiseOpOutputShape(r,s)}let a=e.map(n=>n.length);e.indexOf(null)===-1&&Cs(a).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return q(()=>{if(e=e,this.reshapeRequired){let r=[],a=e.map(n=>n.rank);if(a.indexOf(null)===-1){let n=Ls(a);for(let s of e){let i=s.rank;for(let o=0;o<n-i;++o)s=gh(s,1);r.push(s)}return this.mergeFunction(r)}else{let n=!1;for(let o of e){let l=o.rank;if(l==null){let d=o.shape,u=d[0],p=d.slice(1).concat([u]),h=U(o,[u].concat(Ns(d.slice(1))));h=rt(h,[1,0]),h=U(h,p),r.push(h),n=!0}else if(l>1){let d=dn(1,l).concat([0]);r.push(rt(o,d)),n=!0}else r.push(o)}let s=this.mergeFunction(r),i=s.rank;if(n){if(i==null){let o=s.shape,l=o.length,d=o[l-1],u=[d].concat(o.slice(0,o.length-1));s=U(rt(U(s,[-1,d]),[1,0]),u)}else if(i>1){let o=[i-1].concat(dn(0,i-1));s=rt(s,o)}}return s}}else return this.mergeFunction(e)})}computeOutputShape(e){e=e;let t;e[0]==null?t=null:t=e[0].slice(1);for(let a=1;a<e.length;++a){let n=e[a]==null?null:e[a].slice(1);t=this.computeElementwiseOpOutputShape(t,n)}let r=[];for(let a of e)a!=null&&a[0]!==null&&r.push(a[0]);return r=Cs(r),r.length===1?t=r.concat(t):t=[null].concat(t),t}computeMask(e,t){return q(()=>{if(t==null)return null;if(!Array.isArray(t))throw new H("`mask` should be an Array");if(!Array.isArray(e))throw new H("`inputs` should be an Array");if(t.length!==e.length)throw new H(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every(a=>a==null))return null;t=t.map(a=>a==null?a:Ht(a,0));let r=t[0];for(let a=1;a<t.length-1;++a)r=ln(r,t[a]);return r})}},zA=class extends Il{constructor(e){super(e)}mergeFunction(e){return q(()=>{let t=e[0].clone();for(let r=1;r<e.length;++r)t=ue(t,e[r]);return t})}};zA.className="Add";de.registerClass(zA);var DA=class extends Il{constructor(e){super(e)}mergeFunction(e){return q(()=>{let t=e[0].clone();for(let r=1;r<e.length;++r)t=L(t,e[r]);return t})}};DA.className="Multiply";de.registerClass(DA);var _A=class extends Il{constructor(e){super(e)}mergeFunction(e){return q(()=>{let t=e[0].clone();for(let r=1;r<e.length;++r)t=ue(t,e[r]);return L(1/e.length,t)})}};_A.className="Average";de.registerClass(_A);var LA=class extends Il{constructor(e){super(e)}mergeFunction(e){return q(()=>{let t=e[0];for(let r=1;r<e.length;++r)t=Zn(t,e[r]);return t})}};LA.className="Maximum";de.registerClass(LA);var BA=class extends Il{constructor(e){super(e)}mergeFunction(e){return q(()=>{let t=e[0];for(let r=1;r<e.length;++r)t=ph(t,e[r]);return t})}};BA.className="Minimum";de.registerClass(BA);var WA=class extends Il{constructor(e){super(e);this.DEFAULT_AXIS=-1,e==null&&(e={}),this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){if(!(Array.isArray(e)&&Array.isArray(e[0]))||e.length===1)throw new H("A `Concatenate` layer should be called on a list of at least 2 inputs");e=e;let t=!0;for(let a of e)if(a!=null){t=!1;break}if(t)return;let r=[];for(let a=0;a<e.length;++a){let n=e[a].slice();n.splice(this.axis,1);let s=!1;for(let i of r)if(w.arraysEqual(i,n)){s=!0;break}s||r.push(n)}if(r.length>1)throw new H("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return q(()=>G2(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new H("A `Concatenate` layer should be called on a list of inputs.");let t=e,r=t[0].slice(),a=this.axis<0?r.length+this.axis:this.axis;for(let n of t.slice(1)){if(r[a]==null||n[a]==null){r[a]=null;break}r[a]+=n[a]}return r}computeMask(e,t){if(t==null)return null;if(!Array.isArray(t))throw new H("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new H("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new H(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return q(()=>{let r=!0;if(t.forEach(s=>{if(s!=null){r=!1;return}}),r)return null;let a=[];for(let s=0;s<e.length;++s)t[s]==null?a.push(me(Ra(e[s]),"bool")):t[s].rank<e[s].rank?a.push(Ht(t[s],-1)):a.push(t[s]);let n=kt(a,this.axis);return t2(n,-1,!1)})}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};WA.className="Concatenate";de.registerClass(WA);function np(e,t){for(;e<0;)e+=t;return e}function LV(e,t,r){if(e.shape.length>3||t.shape.length>3)throw new Be("batchDot is not implemented for tensors of 4D or higher rank yet");if(w.assert(e.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`),w.assert(e.shape.length>=2,()=>`batchDot requires the rank of y to be >= 2, but got ${t.shape.length}`),typeof r=="number"&&(r=[r,r]),e.dtype==="complex64"||t.dtype==="complex64")throw new Be("batchDot is not implemented for complex64-type Tensors yet.");let a=e.shape.length,n=t.shape.length;r==null&&(r=[a-1,n-2]);let s=r;return q(()=>{let i;if(a>n){i=a-n;let l=[];for(let d=0;d<i;++d)l.push(1);t=U(t,t.shape.concat(l))}else if(n>a){i=n-a;let l=[];for(let d=0;d<i;++d)l.push(1);e=U(e,e.shape.concat(l))}else i=0;let o;if(e.shape.length===2&&t.shape.length===2)s[0]===s[1]?o=ke(L(e,t),s[0]):o=ke(L(rt(e,[1,0]),t),s[1]);else{let l=s[0]!==e.shape.length-1,d=s[1]===t.shape.length-1;o=Ke(e,t,l,d)}if(i>0){let l;a>n?l=a+n-3:l=a-1;let d=[];for(let u=l;u<l+i;++u)d.push(u);o=Ye(o,d)}return o.shape.length===1&&(o=Ht(o,1)),o})}var VA=class extends Il{constructor(e){super(e);this.axes=e.axes,this.normalize=e.normalize==null?!1:e.normalize,this.supportsMasking=!0,this.reshapeRequired=!1}build(e){w.assert(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");let t=e[0],r=e[1];if(t.length>3||r.length>3)throw new Be("Dot layer does not support tensors of 4D or higher rank yet.");let a=this.interpretAxes(t,r);if(t[a[0]]!==r[a[1]])throw new H(`Dimension incompatibility: ${t[a[0]]} !== ${r[a[1]]}`)}mergeFunction(e){if(e.length!==2)throw new H(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t=e[0],r=e[1],a;return Array.isArray(this.axes)?a=this.axes.map((n,s)=>np(n,e[s].shape.length)):a=[np(this.axes,t.shape.length),np(this.axes,r.shape.length)],this.normalize&&(t=of(t,a[0]),r=of(r,a[1])),LV(t,r,a)}interpretAxes(e,t){let r;return Array.isArray(this.axes)?r=this.axes:r=[np(this.axes,e.length),np(this.axes,t.length)],r}computeOutputShape(e){w.assert(Array.isArray(e)&&e.length===2&&Array.isArray(e[0])&&Array.isArray(e[1]),()=>"A `Dot` layer should be called on a list of exactly 2 inputs.");let t=e[0].slice(),r=e[1].slice();if(t.length>3||r.length>3)throw new Be("Dot layer does not support tensors of 4D or higher rank yet.");let a=this.interpretAxes(t,r);t.splice(a[0],1),r.splice(a[1],1),r.splice(0,1);let n=t.concat(r);return n.length===1&&n.push(1),n}computeMask(e,t){return null}getConfig(){let e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}};VA.className="Dot";de.registerClass(VA);var UA=class extends nt{constructor(e){super(e);this.supportsMasking=!0,this.stddev=e.stddev}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={stddev:this.stddev};return Object.assign(t,e),t}call(e,t){return q(()=>{this.invokeCallHook(e,t);let r=Ve(e);return Ah(()=>ue(Tm(r.shape,0,this.stddev),r),()=>r,t.training||!1)})}};UA.className="GaussianNoise";de.registerClass(UA);var GA=class extends nt{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return q(()=>{this.invokeCallHook(e,t);let r=Ve(e);return this.rate>0&&this.rate<1?Ah(()=>{let a=Math.sqrt(this.rate/(1-this.rate));return L(r,Tm(r.shape,1,a))},()=>r,t.training||!1):r})}};GA.className="GaussianDropout";de.registerClass(GA);var jA=class extends nt{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||Ve(e).shape}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={rate:this.rate};return Object.assign(t,e),t}call(e,t){return q(()=>{if(this.rate<1&&this.rate>0){let r=this._getNoiseShape(e);return Ah(()=>{let a=Ve(e),n=1.6732632423543772,s=1.0507009873554805,i=-n*s,o=xl(nd(r),this.rate);o=Sm(o,"float32");let l=((1-this.rate)*(1+this.rate*i**2))**-.5,d=-l*i*this.rate,u=ue(L(a,o),L(ue(o,-1),i));return ue(L(u,l),d)},()=>Ve(e),t.training||!1)}return e})}};jA.className="AlphaDropout";de.registerClass(jA);function Pp(e,t,r,a,n,s=.001){let i;if(e.rank===2)i=Ww(e,t,r,a,n,s);else if(e.rank===3)i=Vw(e,t,r,a,n,s);else if(e.rank===4)i=Uw(e,t,r,a,n,s);else throw new Be(`batchNormalization is not implemented for array of rank ${e.rank} yet`);return i}function BV(e,t,r,a,n=.001){return q(()=>{let s=lm(e,a),i=s.mean,o=s.variance;return[Pp(e,i,o,r,t,n),i,o]})}function WV(e,t,r,a,n=.001){return q(()=>{let s=lm(e,a),i=s.mean,o=s.variance,l=[];for(let c of dn(0,e.rank))a.indexOf(c)!==-1?l.push(1):l.push(e.shape[c]);let d=U(i,l),u=U(o,l),p=t==null?null:U(t,l),h=r==null?null:U(r,l);return[Pp(e,d,u,h,p,n),i,o]})}function VV(e,t,r,a,n=.001){return w.arraysEqual(a.slice().sort(),dn(0,e.rank-1))?BV(e,t,r,a,n):WV(e,t,r,a,n)}var HA=class extends nt{constructor(e){e==null&&(e={});super(e);this.supportsMasking=!0,this.axis=e.axis==null?-1:e.axis,this.momentum=e.momentum==null?.99:e.momentum,this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=Ft(e.betaInitializer||"zeros"),this.gammaInitializer=Ft(e.gammaInitializer||"ones"),this.movingMeanInitializer=Ft(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=Ft(e.movingVarianceInitializer||"ones"),this.betaConstraint=ar(e.betaConstraint),this.gammaConstraint=ar(e.gammaConstraint),this.betaRegularizer=Mt(e.betaRegularizer),this.gammaRegularizer=Mt(e.gammaRegularizer)}build(e){e=mt(e);let t=this.axis>=0?this.axis:this.axis+e.length,r=e[t];if(r==null)throw new H(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new qt({ndim:e.length,axes:{[t]:r}})];let a=[r];this.scale&&(this.gamma=this.addWeight("gamma",a,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",a,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",a,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",a,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return q(()=>{let r=t.training==null?!1:t.training,a=Ve(e),n=a.shape,s=n.length,i=dn(0,s),o=this.axis>=0?this.axis:this.axis+s;i.splice(o,1);let l=ko(1,s);l[o]=n[o];let d=i.slice();d.sort();let u=!w.arraysEqual(d,dn(0,s).slice(0,s-1)),p=()=>{if(u){let g=U(this.movingMean.read(),l),y=U(this.movingVariance.read(),l),A=this.center?U(this.beta.read(),l):null,x=this.scale?U(this.gamma.read(),l):null;return Pp(a,g,y,A,x,this.epsilon)}else return Pp(a,this.movingMean.read(),this.movingVariance.read(),this.beta==null?null:this.beta.read(),this.gamma==null?null:this.gamma.read(),this.epsilon)};if(!r)return p();let[h,c,f]=VV(a,this.gamma.read(),this.beta.read(),i,this.epsilon),m=(g,y,A)=>{q(()=>{let x=1-A,b=g.read(),v=L(he(b,y),x);g.write(he(b,v))})};return m(this.movingMean,c,this.momentum),m(this.movingVariance,f,this.momentum),h})}getConfig(){let e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Pt(this.betaInitializer),gammaInitializer:Pt(this.gammaInitializer),movingMeanInitializer:Pt(this.movingMeanInitializer),movingVarianceInitializer:Pt(this.movingVarianceInitializer),betaRegularizer:xt(this.betaRegularizer),gammaRegularizer:xt(this.gammaRegularizer),betaConstraint:rr(this.betaConstraint),gammaConstraint:rr(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}};HA.className="BatchNormalization";de.registerClass(HA);var qA=class extends nt{constructor(e){e==null&&(e={});super(e);if(this.axis=e.axis==null?-1:e.axis,typeof this.axis=="number"){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else if(Array.isArray(this.axis)){for(let t of this.axis)if(!Number.isInteger(t))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}else throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=Ft(e.betaInitializer||"zeros"),this.gammaInitializer=Ft(e.gammaInitializer||"ones"),this.betaRegularizer=Mt(e.betaRegularizer),this.gammaRegularizer=Mt(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=mt(e);let t=e.length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let n=0;n<this.axis.length;++n)this.axis[n]<0&&(this.axis[n]+=t);for(let n of this.axis)if(n<0||n>=t)throw new Error(`Invalid axis: ${n}`);if(this.axis.length!==Cs(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);let r=this.axis.map(n=>e[n]),a=!0;this.scale?this.gamma=this.addWeight("gamma",r,"float32",this.gammaInitializer,this.gammaRegularizer,a):this.gamma=null,this.center?this.beta=this.addWeight("beta",r,"float32",this.betaInitializer,this.betaRegularizer,a):this.beta=null,this.built=!0}call(e,t){let r=Ve(e),a=r.shape,n=a.length;return q(()=>{let{mean:s,variance:i}=lm(r,this.axis,!0),o=ko(1,n);for(let c of this.axis)o[c]=a[c];let l=c=>c!=null&&c.shape.length!==n?U(c,o):c,d=l(this.gamma.read()),u=l(this.beta.read()),p=[],h=[];for(let c=0;c<n;++c)this.axis.indexOf(c)!==-1?(p.push(a[c]),h.push(1)):(p.push(1),h.push(a[c]));return s=Wa(s,p),i=Wa(i,p),d=Wa(d,h),u=Wa(u,h),Pp(r,s,i,u,d,this.epsilon)})}getConfig(){let e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Pt(this.betaInitializer),gammaInitializer:Pt(this.gammaInitializer),betaRegularizer:xt(this.betaRegularizer),gammaRegularizer:xt(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}};qA.className="LayerNormalization";de.registerClass(qA);function UV(e,t,r){return q(()=>{if(e.rank!==4)throw new H(`temporalPadding expects input tensor to be 4-D, but received a ${e.rank}-D tensor.`);if(t==null&&(t=[[1,1],[1,1]]),t.length!==2||t[0].length!==2||t[1].length!==2)throw new H("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(r==null&&(r=un()),r!=="channelsLast"&&r!=="channelsFirst")throw new H(`Unknown data format: ${r}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let a;return r==="channelsFirst"?a=[[0,0],[0,0],t[0],t[1]]:a=[[0,0],t[0],t[1],[0,0]],ja(e,a)})}var KA=class extends nt{constructor(e){e==null&&(e={});super(e);if(this.dataFormat=e.dataFormat==null?un():e.dataFormat,e.padding==null)this.padding=[[1,1],[1,1]];else if(typeof e.padding=="number")this.padding=[[e.padding,e.padding],[e.padding,e.padding]];else{if(e.padding=e.padding,e.padding.length!==2)throw new H(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,r;if(typeof e.padding[0]=="number")t=[e.padding[0],e.padding[0]],r=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,e.padding[0].length!==2)throw new H(`ZeroPadding2D expects height padding to be a length-2 array, but received a length-${e.padding[0].length} array.`);if(t=e.padding[0],e.padding[1].length!==2)throw new H(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);r=e.padding[1]}this.padding=[t,r]}this.inputSpec=[new qt({ndim:4})]}computeOutputShape(e){e=mt(e);let t,r;return this.dataFormat==="channelsFirst"?(e[2]!=null&&e[2]>=0?t=e[2]+this.padding[0][0]+this.padding[0][1]:t=null,e[3]!=null&&e[3]>=0?r=e[3]+this.padding[1][0]+this.padding[1][1]:r=null,[e[0],e[1],t,r]):(e[1]!=null&&e[1]>=0?t=e[1]+this.padding[0][0]+this.padding[0][1]:t=null,e[2]!=null&&e[2]>=0?r=e[2]+this.padding[1][0]+this.padding[1][1]:r=null,[e[0],t,r,e[3]])}call(e,t){return q(()=>UV(Ve(e),this.padding,this.dataFormat))}getConfig(){let e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};KA.className="ZeroPadding2D";de.registerClass(KA);function Hm(e,t,r,a,n,s){return q(()=>{Ut(n),Yk(s),Pa(a),r==null&&(r=[1,1]),a==null&&(a="valid"),n==null&&(n=un()),s==null&&(s="max"),e=fA(e,n);let i,o=a==="same"?"same":"valid";return s==="max"?i=om(e,t,r,o):i=Qf(e,t,r,o),n==="channelsFirst"&&(i=rt(i,[0,3,1,2])),i})}function X7(e,t,r,a,n,s){return q(()=>{Ut(n),Yk(s),Pa(a),r==null&&(r=[1,1,1]),a==null&&(a="valid"),n==null&&(n=un()),s==null&&(s="max"),e=B7(e,n);let i,o=a==="same"?"same":"valid";return s==="max"?i=y2(e,t,r,o):i=a2(e,t,r,o),n==="channelsFirst"&&(i=rt(i,[0,4,1,2,3])),i})}var Z7=class extends nt{constructor(e){e.poolSize==null&&(e.poolSize=2);super(e);if(typeof e.poolSize=="number")this.poolSize=[e.poolSize];else if(Array.isArray(e.poolSize)&&e.poolSize.length===1&&typeof e.poolSize[0]=="number")this.poolSize=e.poolSize;else throw new H(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(pr(this.poolSize,"poolSize"),e.strides==null)this.strides=this.poolSize;else if(typeof e.strides=="number")this.strides=[e.strides];else if(Array.isArray(e.strides)&&e.strides.length===1&&typeof e.strides[0]=="number")this.strides=e.strides;else throw new H(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);pr(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,Pa(this.padding),this.inputSpec=[new qt({ndim:3})]}computeOutputShape(e){e=mt(e);let t=sn(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return q(()=>{this.invokeCallHook(e,t),e=gh(Ve(e),2);let r=this.poolingFunction(Ve(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return Ye(r,[2])})}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}},XA=class extends Z7{constructor(e){super(e)}poolingFunction(e,t,r,a,n){return Ut(n),Pa(a),Hm(e,t,r,a,n,"max")}};XA.className="MaxPooling1D";de.registerClass(XA);var ZA=class extends Z7{constructor(e){super(e)}poolingFunction(e,t,r,a,n){return Ut(n),Pa(a),Hm(e,t,r,a,n,"avg")}};ZA.className="AveragePooling1D";de.registerClass(ZA);var Y7=class extends nt{constructor(e){e.poolSize==null&&(e.poolSize=[2,2]);super(e);if(this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==2)throw new H(`If the strides property of a 2D pooling layer is an Array, it is expected to have a length of 2, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides];pr(this.poolSize,"poolSize"),pr(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Ut(this.dataFormat),Pa(this.padding),this.inputSpec=[new qt({ndim:4})]}computeOutputShape(e){e=mt(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],r=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=sn(t,this.poolSize[0],this.padding,this.strides[0]),r=sn(r,this.poolSize[1],this.padding,this.strides[1]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,r]:[e[0],t,r,e[3]]}call(e,t){return q(()=>(this.invokeCallHook(e,t),this.poolingFunction(Ve(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},YA=class extends Y7{constructor(e){super(e)}poolingFunction(e,t,r,a,n){return Ut(n),Pa(a),Hm(e,t,r,a,n,"max")}};YA.className="MaxPooling2D";de.registerClass(YA);var JA=class extends Y7{constructor(e){super(e)}poolingFunction(e,t,r,a,n){return Ut(n),Pa(a),Hm(e,t,r,a,n,"avg")}};JA.className="AveragePooling2D";de.registerClass(JA);var J7=class extends nt{constructor(e){e.poolSize==null&&(e.poolSize=[2,2,2]);super(e);if(this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==3)throw new H(`If the strides property of a 3D pooling layer is an Array, it is expected to have a length of 3, but received length ${e.strides.length}.`);this.strides=e.strides}else this.strides=[e.strides,e.strides,e.strides];pr(this.poolSize,"poolSize"),pr(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Ut(this.dataFormat),Pa(this.padding),this.inputSpec=[new qt({ndim:5})]}computeOutputShape(e){e=mt(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],r=this.dataFormat==="channelsFirst"?e[3]:e[2],a=this.dataFormat==="channelsFirst"?e[4]:e[3];return t=sn(t,this.poolSize[0],this.padding,this.strides[0]),r=sn(r,this.poolSize[1],this.padding,this.strides[1]),a=sn(a,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,r,a]:[e[0],t,r,a,e[4]]}call(e,t){return q(()=>(this.invokeCallHook(e,t),this.poolingFunction(Ve(e),this.poolSize,this.strides,this.padding,this.dataFormat)))}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},QA=class extends J7{constructor(e){super(e)}poolingFunction(e,t,r,a,n){return Ut(n),Pa(a),X7(e,t,r,a,n,"max")}};QA.className="MaxPooling3D";de.registerClass(QA);var ex=class extends J7{constructor(e){super(e)}poolingFunction(e,t,r,a,n){return Ut(n),Pa(a),X7(e,t,r,a,n,"avg")}};ex.className="AveragePooling3D";de.registerClass(ex);var Q7=class extends nt{constructor(e){super(e);this.inputSpec=[new qt({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Be}},tx=class extends Q7{constructor(e){super(e||{})}call(e,t){return q(()=>{let r=Ve(e);return Wt(r,1)})}};tx.className="GlobalAveragePooling1D";de.registerClass(tx);var rx=class extends Q7{constructor(e){super(e||{})}call(e,t){return q(()=>{let r=Ve(e);return hr(r,1)})}};rx.className="GlobalMaxPooling1D";de.registerClass(rx);var e4=class extends nt{constructor(e){super(e);this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Ut(this.dataFormat),this.inputSpec=[new qt({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Be}getConfig(){let e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},ax=class extends e4{call(e,t){return q(()=>{let r=Ve(e);return this.dataFormat==="channelsLast"?Wt(r,[1,2]):Wt(r,[2,3])})}};ax.className="GlobalAveragePooling2D";de.registerClass(ax);var nx=class extends e4{call(e,t){return q(()=>{let r=Ve(e);return this.dataFormat==="channelsLast"?hr(r,[1,2]):hr(r,[2,3])})}};nx.className="GlobalMaxPooling2D";de.registerClass(nx);var t4=class extends nt{constructor(e){super(e);this.layer=e.layer}build(e){this.built=!0}get trainable(){return this.layer!=null?this.layer.trainable:!1}set trainable(e){this.layer!=null&&(this.layer.trainable=e)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(e){this.layer.setWeights(e)}getConfig(){let e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.layer!=null&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,r={}){let a=t.layer,n=nn(a,r);delete t.layer;let s={layer:n};return Object.assign(s,t),new e(s)}},sx=class extends t4{constructor(e){super(e);this.supportsMasking=!0}build(e){if(e=mt(e),e.length<3)throw new H(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];let t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){e=mt(e);let t=[e[0]].concat(e.slice(2)),r=this.layer.computeOutputShape(t),a=e[1];return[r[0],a].concat(r.slice(1))}call(e,t){return q(()=>(e=Ve(e),H7((r,a)=>[Ve(this.layer.call(r,t)),[]],e,[],!1,null,null,!1,!0)[1]))}};sx.className="TimeDistributed";de.registerClass(sx);function GV(e){wl(YB,"BidirectionalMergeMode",e)}var jV="concat",ix=class extends t4{constructor(e){super(e);let t=e.layer.getConfig(),r={};r.className=e.layer.getClassName(),r.config=t,this.forwardLayer=nn(r),t.goBackwards=t.goBackwards!==!0;let a={};if(a.className=e.layer.getClassName(),a.config=t,this.backwardLayer=nn(a),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?jV:e.mergeMode,GV(this.mergeMode),e.weights)throw new Be("weights support is not implemented for Bidirectional layer yet.");this._stateful=e.layer.stateful,this.returnSequences=e.layer.returnSequences,this.returnState=e.layer.returnState,this.supportsMasking=!0,this._trainable=!0,this.inputSpec=e.layer.inputSpec,this.numConstants=null}get trainable(){return this._trainable}set trainable(e){this._trainable=e,this.forwardLayer!=null&&(this.forwardLayer.trainable=e),this.backwardLayer!=null&&(this.backwardLayer.trainable=e)}getWeights(){return this.forwardLayer.getWeights().concat(this.backwardLayer.getWeights())}setWeights(e){let t=e.length,r=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,r)),this.backwardLayer.setWeights(e.slice(r))}computeOutputShape(e){let t=this.forwardLayer.computeOutputShape(e);Array.isArray(t)&&Array.isArray(t[0])||(t=[t]),t=t;let r,a,n;return this.returnState&&(n=t.slice(1)),r=t[0],r=r,this.mergeMode==="concat"?(r[r.length-1]*=2,a=[r]):this.mergeMode==null?a=[r,r.slice()]:a=[r],this.returnState?this.mergeMode==null?a.concat(n).concat(n.slice()):[r].concat(n).concat(n.slice()):ea(a)}apply(e,t){let r=t==null?null:t.initialState,a=t==null?null:t.constants;t==null&&(t={});let n=j7(e,r,a,this.numConstants);if(e=n.inputs,r=n.initialState,a=n.constants,Array.isArray(e)&&(r=e.slice(1),e=e[0]),(r==null||r.length===0)&&a==null)return super.apply(e,t);let s=[],i=[];if(r!=null){let l=r.length;if(l%2>0)throw new H("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=r,s.push(...r);let d=r.map(u=>new qt({shape:u.shape}));this.forwardLayer.stateSpec=d.slice(0,l/2),this.backwardLayer.stateSpec=d.slice(l/2),i.push(...d)}if(a!=null)throw new Be("Support for constants in Bidirectional layers is not implemented yet.");let o=s[0]instanceof tn;for(let l of s)if(l instanceof tn!==o)throw new H("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(o){let l=[e].concat(s),d=this.inputSpec.concat(i),u=this.inputSpec;this.inputSpec=d;let p=super.apply(l,t);return this.inputSpec=u,p}else return super.apply(e,t)}call(e,t){return q(()=>{let r=t.initialState,a,n;if(r==null)a=this.forwardLayer.call(e,t),n=this.backwardLayer.call(e,t);else{let o=r.slice(0,r.length/2),l=r.slice(r.length/2);a=this.forwardLayer.call(e,Object.assign(t,{initialState:o})),n=this.backwardLayer.call(e,Object.assign(t,{initialState:l}))}let s;this.returnState&&(Array.isArray(a)&&(s=a.slice(1).concat(n.slice(1))),a=a[0],n=n[0]),this.returnSequences&&(n=Fa(n,1));let i;return this.mergeMode==="concat"?i=G2([a,n]):this.mergeMode==="sum"?i=ue(a,n):this.mergeMode==="ave"?i=L(.5,ue(a,n)):this.mergeMode==="mul"?i=L(a,n):this.mergeMode==null&&(i=[a,n]),this.returnState?this.mergeMode==null?i.concat(s):[i].concat(s):i})}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){mo(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),mo(this.backwardLayer.name,()=>{this.backwardLayer.build(e)}),this.built=!0}computeMask(e,t){Array.isArray(t)&&(t=t[0]);let r;if(this.returnSequences?this.mergeMode==null?r=[t,t]:r=t:this.mergeMode==null?r=[null,null]:r=null,this.returnState){let a=this.forwardLayer.states.map(n=>null);return Array.isArray(r)?r.concat(a).concat(a):[r].concat(a).concat(a)}else return r}get trainableWeights(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)}get nonTrainableWeights(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.forwardLayer!=null&&this.forwardLayer.setFastWeightInitDuringBuild(e),this.backwardLayer!=null&&this.backwardLayer.setFastWeightInitDuringBuild(e)}getConfig(){let e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){let r=nn(t.layer);if(delete t.layer,t.numConstants!=null)throw new Be("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");let a=t;return a.layer=r,new e(a)}};ix.className="Bidirectional";de.registerClass(ix);function HV(e){return new od(e)}function qV(e){return new pA(e)}function KV(e){return new lA(e)}function XV(e){return new uA(e)}function ZV(e){return new dA(e)}function YV(e){return new cA(e)}function JV(e){return new hA(e)}function QV(e){return new xA(e)}function eU(e){return new Lm(e)}function tU(e){return new gA(e)}function rU(e){return new Bm(e)}function aU(e){return new yA(e)}function nU(e){return new AA(e)}function sU(e){return new bA(e)}function iU(e){return new vA(e)}function oU(e){return new wA(e)}function lU(e){return new RA(e)}function uU(e){return new NA(e)}function dU(e){return new jm(e)}function pU(e){return new CA(e)}function hU(e){return new EA(e)}function cU(e){return new FA(e)}function fU(e){return new MA(e)}function mU(e){return new $A(e)}function gU(e){return new OA(e)}function yU(e){return new zA(e)}function AU(e){return new _A(e)}function xU(e){return new WA(e)}function bU(e){return new LA(e)}function vU(e){return new BA(e)}function wU(e){return new DA(e)}function kU(e){return new VA(e)}function IU(e){return new HA(e)}function SU(e){return new qA(e)}function TU(e){return new KA(e)}function ox(e){return new ZA(e)}function CU(e){return ox(e)}function NU(e){return ox(e)}function lx(e){return new JA(e)}function EU(e){return lx(e)}function RU(e){return lx(e)}function ux(e){return new ex(e)}function FU(e){return ux(e)}function MU(e){return ux(e)}function $U(e){return new tx(e)}function PU(e){return new ax(e)}function r4(e){return new rx(e)}function a4(e){return new nx(e)}function n4(e){return new XA(e)}function s4(e){return new YA(e)}function OU(e){return new QA(e)}function zU(e){return new IA(e)}function DU(e){return new Vm(e)}function _U(e){return new SA(e)}function LU(e){return new wh(e)}function BU(e){return new kA(e)}function WU(e){return new Wm(e)}function VU(e){return new TA(e)}function UU(e){return new Gm(e)}function GU(e){return new Qn(e)}function jU(e){return new Um(e)}function HU(e){return new ix(e)}function qU(e){return new sx(e)}var KU=r4,XU=a4,ZU=n4,YU=s4;function JU(e){return new UA(e)}function QU(e){return new GA(e)}function eG(e){return new jA(e)}function tG(e){return new PA(e)}var i4={};De(i4,{MAPE:()=>hG,MSE:()=>mG,binaryAccuracy:()=>rG,binaryCrossentropy:()=>aG,categoricalAccuracy:()=>sG,categoricalCrossentropy:()=>iG,cosineProximity:()=>uG,mape:()=>cG,meanAbsoluteError:()=>dG,meanAbsolutePercentageError:()=>pG,meanSquaredError:()=>fG,mse:()=>gG,precision:()=>oG,recall:()=>lG,sparseCategoricalAccuracy:()=>nG});function rG(e,t){return tA(e,t)}function aG(e,t){return g7(e,t)}function nG(e,t){return y7(e,t)}function sG(e,t){return rA(e,t)}function iG(e,t){return aA(e,t)}function oG(e,t){return m7(e,t)}function lG(e,t){return HW(e,t)}function uG(e,t){return eA(e,t)}function dG(e,t){return zm(e,t)}function pG(e,t){return ld(e,t)}function hG(e,t){return ld(e,t)}function cG(e,t){return ld(e,t)}function fG(e,t){return kl(e,t)}function mG(e,t){return kl(e,t)}function gG(e,t){return kl(e,t)}var o4={};De(o4,{modelFromJSON:()=>TV});var l4={};De(l4,{l1:()=>AG,l1l2:()=>yG,l2:()=>xG});function yG(e){return new xh(e)}function AG(e){return PV(e)}function xG(e){return OV(e)}var u4=class extends Au{constructor(){super(...arguments);this.model=null}setModel(e){if(!(e instanceof jn))throw new Error("model must be a LayersModel, not some other Container");this.model=e}};function Ec(e,t){return e<t}function N3(e,t){return e>t}var d4=class extends u4{constructor(e){super();if(e==null&&(e={}),e.restoreBestWeights)throw new Be("restoreBestWeights = True is not implemented in EarlyStopping yet.");this.monitor=e.monitor||"val_loss",this.minDelta=Math.abs(e.minDelta||0),this.patience=e.patience||0,this.verbose=e.verbose||0,this.mode=e.mode||"auto",this.baseline=e.baseline,["auto","min","max"].indexOf(this.mode)===-1&&(console.warn(`EarlyStopping mode '${this.mode}' is invalid. Falling back to mode 'auto'.`),this.mode="auto"),this.mode==="min"?this.monitorFunc=Ec:this.mode==="max"?this.monitorFunc=N3:this.monitor.indexOf("acc")!==-1?this.monitorFunc=N3:this.monitorFunc=Ec,this.monitorFunc===Ec&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===Ec?1/0:-1/0}async onEpochEnd(e,t){await ws(t);let r=this.getMonitorValue(t);r!=null&&(this.monitorFunc(r-this.minDelta,this.best)?(this.best=r,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=e,this.model.stopTraining=!0)))}async onTrainEnd(e){this.stoppedEpoch>0&&this.verbose&&console.log(`Epoch ${this.stoppedEpoch}: early stopping.`)}getMonitorValue(e){e==null&&(e={});let t=e[this.monitor];return t==null&&console.warn(`Metric for EarlyStopping ${this.monitor} is not available. Available metrics are: ${Object.keys(e)}`),t}};function bG(e){return new d4(e)}var vG={earlyStopping:bG},wG=Y();wG.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 p4=(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",e))(p4||{}),E3;(e=>{let t;(r=>{r[r.LEGACY=0]="LEGACY",r[r.V1=1]="V1",r[r.V2=2]="V2"})(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))})(E3||(E3={}));var dx={};function kG(e,t){let r={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};dx[e]=r}function h4(e){return dx[e]}function IG(e){delete dx[e]}function k(e,t,r,a,n){let s=t.inputParams[e];if(s&&s.inputIndexStart!==void 0){let o=s.inputIndexStart,l=s.inputIndexEnd===0?void 0:s.inputIndexEnd===void 0?o+1:s.inputIndexEnd;if(s.type==="tensor")return Mr(t.inputNames[s.inputIndexStart],r,a,n);if(s.type==="tensors")return t.inputNames.slice(o,l).map(p=>Mr(p,r,a,n));let d=Mr(t.inputNames.slice(o)[0],r,a,n),u=d.dataSync();return s.type==="number"?u[0]:w.toNestedArray(d.shape,u)}let i=t.attrParams[e];return i&&i.value}function Mr(e,t,r,a){let[n,s]=la(e);if(a!=null){let o=a.getHashTableHandleByName(n);if(o!=null)return o}let i=r.currentContextIds.find(o=>!!t[hf(n,o)]);return i!==void 0?t[hf(n,i)][s]:void 0}function SG(e,t,r){return t[hf(e,r.currentContextId)]}function In(e,t){let[r,a,n]=la(e);return[hf(r,t&&t.currentContextId),a,n]}function hf(e,t){return t?`${e}-${t}`:e}function la(e){let t=e.split(":");if(t.length===1)return[e,0,void 0];let r=t[0],a=t.length===3?t[1]:void 0,n=Number(t[t.length-1]);return[r,n,a]}function _c(e,t,r){let a=k("pad",e,t,r);if(a==="explicit"){a=k("explicitPaddings",e,t,r);let n=[[0,0],[0,0],[0,0],[0,0]];for(let s=0;s<4;s++)n[s][0]=a[s*2],n[s][1]=a[s*2+1];return n}return a}function Vn(e){return e.kept?e:Pr(e)}var c4={};De(c4,{json:()=>TG});var TG=[{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}]}],f4={};De(f4,{json:()=>CG});var CG=[{tfOpName:"Abs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atan2",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"y",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ceil",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ClipByValue",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"clipValueMin",type:"number"},{start:2,name:"clipValueMax",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Complex",category:"basic_math",inputs:[{start:0,name:"real",type:"tensor"},{start:1,name:"imag",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ComplexAbs",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cos",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Cosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Elu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Exp",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Floor",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Imag",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Neg",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Real",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"Tout",name:"outputType",type:"dtype",notSupported:!0}]},{tfOpName:"Prelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"alpha",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Relu6",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Selu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sigmoid",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sin",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Rsqrt",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Square",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Tanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Sign",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Round",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Expm1",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Log1p",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Reciprocal",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Softplus",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Asinh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Acosh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Atanh",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Erf",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Prod",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axes",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"LeakyRelu",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"alpha",name:"alpha",type:"number",defaultValue:.2},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"IsNan",category:"basic_math",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],m4={};De(m4,{json:()=>NG});var NG=[{tfOpName:"EmptyTensorList",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"maxNumElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"LoopCond",category:"control",inputs:[{start:0,name:"pred",type:"tensor"}]},{tfOpName:"Switch",category:"control",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"pred",type:"tensor"}]},{tfOpName:"Merge",category:"control",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"Enter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"frame_name",name:"frameName",type:"string"},{tfName:"is_constant",name:"isConstant",type:"bool"}]},{tfOpName:"Exit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"NextIteration",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayV3",category:"control",inputs:[{start:0,name:"size",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"dynamic_size",name:"dynamicSize",type:"bool"},{tfName:"clear_after_read",name:"clearAfterRead",type:"bool"},{tfName:"identical_element_shapes",name:"identicalElementShapes",type:"bool"},{tfName:"tensor_array_name",name:"name",type:"string"}]},{tfOpName:"TensorArrayWriteV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayReadV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"TensorArrayGatherV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape",name:"elementShape",type:"shape"}]},{tfOpName:"TensorArrayScatterV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"tensor",type:"tensor"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArrayConcatV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"element_shape_except0",name:"elementShapeExcept0",type:"shape",notSupported:!0}]},{tfOpName:"TensorArraySplitV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"tensor",type:"tensor"},{start:2,name:"lengths",type:"number[]"},{start:3,name:"flowIn",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"TensorArraySizeV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"},{start:1,name:"flowIn",type:"number"}]},{tfOpName:"TensorArrayCloseV3",category:"control",inputs:[{start:0,name:"tensorArrayId",type:"tensor"}]},{tfOpName:"StatelessIf",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"If",category:"control",inputs:[{start:0,name:"cond",type:"tensor"},{start:1,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"then_branch",name:"thenBranch",type:"func"},{tfName:"else_branch",name:"elseBranch",type:"func"}]},{tfOpName:"StatelessWhile",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"While",category:"control",inputs:[{start:0,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"cond",name:"cond",type:"func"},{tfName:"body",name:"body",type:"func"}]},{tfOpName:"TensorListScatter",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListScatterV2",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"},{start:3,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGather",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"indices",type:"number[]"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListGetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListSetItem",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"index",type:"number"},{start:2,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListReserve",category:"control",inputs:[{start:0,name:"elementShape",type:"shape"},{start:1,name:"numElements",type:"number"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListFromTensor",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListStack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"},{tfName:"num_elements",name:"numElements",type:"dtype"}]},{tfOpName:"TensorListSplit",category:"control",inputs:[{start:0,name:"tensor",type:"tensor"},{start:1,name:"elementShape",type:"shape"},{start:2,name:"lengths",type:"number[]"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListConcat",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}],attrs:[{tfName:"element_shape",name:"elementShape",type:"shape"},{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPopBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"elementShape",type:"shape"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]},{tfOpName:"TensorListPushBack",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"tensor",type:"tensor"}],attrs:[{tfName:"element_dtype",name:"elementDType",type:"dtype"}]}],g4={};De(g4,{json:()=>EG});var EG=[{tfOpName:"AvgPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[],notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPoolWithArgmax",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"include_batch_in_index",name:"includeBatchInIndex",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AvgPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MaxPool3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"ksize",name:"kernelSize",type:"number[]"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Conv1D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"stride",name:"stride",type:"number"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NWC"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"dilation",name:"dilation",type:"number",defaultValue:1}]},{tfOpName:"Conv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"useCudnnOnGpu",name:"useCudnnOnGpu",type:"bool"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"_FusedConv2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"use_cudnn_on_gpu",name:"useCudnnOnGpu",type:"bool",defaultValue:!0},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"leakyrelu_alpha",name:"leakyreluAlpha",type:"number"}]},{tfOpName:"Conv2DBackpropInput",category:"convolution",inputs:[{start:2,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:0,name:"outputShape",type:"number[]"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]",notSupported:!0}]},{tfOpName:"DepthwiseConv2d",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"DepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"input",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"FusedDepthwiseConv2dNative",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]",defaultValue:[1,1,1,1]},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"explicit_paddings",name:"explicitPaddings",type:"number[]",defaultValue:[]}]},{tfOpName:"Conv3D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"padding",name:"pad",type:"string"},{tfName:"data_format",name:"dataFormat",type:"string",defaultValue:"NHWC"},{tfName:"dilations",name:"dilations",type:"number[]"}]},{tfOpName:"Dilation2D",category:"convolution",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"filter",type:"tensor"}],attrs:[{tfName:"strides",name:"strides",type:"number[]"},{tfName:"rates",name:"dilations",type:"number[]"},{tfName:"padding",name:"pad",type:"string"}]}],y4={};De(y4,{json:()=>RG});var RG=[{tfOpName:"Fill",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"},{start:1,name:"value",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"LinSpace",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"num",type:"number"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"OneHot",category:"creation",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"depth",type:"number"},{start:2,name:"onValue",type:"number",defaultValue:1},{start:3,name:"offValue",type:"number",defaultValue:0}],attrs:[{tfName:"axis",name:"axis",type:"number",notSupported:!0},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Ones",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"OnesLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"RandomUniform",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"minval",name:"minval",type:"number",defaultValue:0},{tfName:"maxval",name:"maxval",type:"number",defaultValue:1},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"seed",name:"seed",type:"number",defaultValue:0},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Range",category:"creation",inputs:[{start:0,name:"start",type:"number"},{start:1,name:"stop",type:"number"},{start:2,name:"step",type:"number",defaultValue:0}],attrs:[{tfName:"Tidx",name:"dtype",type:"dtype"}]},{tfOpName:"TruncatedNormal",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"means",name:"mean",type:"number",defaultValue:0},{tfName:"stddev",name:"stdDev",type:"number",defaultValue:1},{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number",defaultValue:0,notSupported:!0},{tfName:"dtype",name:"dtype",type:"dtype"},{tfName:"T",name:"T",type:"number",notSupported:!0}]},{tfOpName:"Zeros",category:"creation",inputs:[{start:0,name:"shape",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"ZerosLike",category:"creation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype"}]},{tfOpName:"Multinomial",category:"creation",inputs:[{start:0,name:"logits",type:"tensor"},{start:1,name:"numSamples",type:"number"}],attrs:[{tfName:"seed",name:"seed",type:"number"},{tfName:"seed2",name:"seed2",type:"number"},{tfName:"T",name:"dtype",type:"dtype"},{tfName:"output_dtype",name:"output_dtype",type:"dtype"}]}],A4={};De(A4,{json:()=>FG});var FG=[{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}]}],x4={};De(x4,{json:()=>MG});var MG=[{tfOpName:"TopKV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"k",type:"number"}],attrs:[{tfName:"sorted",name:"sorted",type:"bool"}]},{tfOpName:"Unique",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"UniqueV2",category:"evaluation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]}],b4={};De(b4,{json:()=>$G});var $G=[{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"}]}],v4={};De(v4,{json:()=>PG});var PG=[{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"}]}],w4={};De(w4,{json:()=>OG});var OG=[{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"}]}],k4={};De(k4,{json:()=>zG});var zG=[{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}]}],I4={};De(I4,{json:()=>DG});var DG=[{tfOpName:"_FusedMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"},{start:2,end:0,name:"args",type:"tensors"}],attrs:[{tfName:"num_args",name:"numArgs",type:"number"},{tfName:"fused_ops",name:"fusedOps",type:"string[]",defaultValue:[]},{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:1e-4},{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"MatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"transpose_a",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"transpose_b",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMul",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"BatchMatMulV2",category:"matrices",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"adj_x",name:"transposeA",type:"bool",defaultValue:!1},{tfName:"adj_y",name:"transposeB",type:"bool",defaultValue:!1},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Transpose",category:"matrices",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"perm",type:"number[]"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Einsum",category:"matrices",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}],attrs:[{tfName:"equation",name:"equation",type:"string"},{tfName:"N",name:"n",type:"number",defaultValue:2},{tfName:"T",name:"dtype",type:"dtype"}]}],S4={};De(S4,{json:()=>_G});var _G=[{tfOpName:"FusedBatchNorm",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV2",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"FusedBatchNormV3",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"scale",type:"tensor"},{start:2,name:"offset",type:"tensor"},{start:3,name:"mean",type:"tensor"},{start:4,name:"variance",type:"tensor"}],attrs:[{tfName:"epsilon",name:"epsilon",type:"number",defaultValue:.001},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"LRN",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"depth_radius",name:"radius",type:"number",defaultValue:5},{tfName:"bias",name:"bias",type:"number",defaultValue:1},{tfName:"alpha",name:"alpha",type:"number",defaultValue:1},{tfName:"beta",name:"beta",type:"number",defaultValue:.5}]},{tfOpName:"Softmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"LogSoftmax",category:"normalization",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"SparseToDense",category:"normalization",inputs:[{start:0,name:"sparseIndices",type:"tensor"},{start:1,name:"outputShape",type:"number[]"},{start:2,name:"sparseValues",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"validate_indices",name:"validateIndices",type:"bool",defaultValue:!0,notSupported:!0}]}],T4={};De(T4,{json:()=>LG});var LG=[{tfOpName:"Bincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}]},{tfOpName:"DenseBincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}],attrs:[{tfName:"binary_output",name:"binaryOutput",type:"bool"}]},{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Cumsum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]}],C4={};De(C4,{json:()=>BG});var BG=[{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}]}],N4={};De(N4,{json:()=>WG});var WG=[{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"}]}],E4={};De(E4,{json:()=>VG});var VG=[{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}]}],R4={};De(R4,{json:()=>UG});var UG=[{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"}]}],F4={};De(F4,{json:()=>GG});var GG=[{tfOpName:"Cast",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"SrcT",name:"sdtype",type:"dtype",notSupported:!0},{tfName:"DstT",name:"dtype",type:"dtype"}]},{tfOpName:"ExpandDims",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"MirrorPad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"mode",name:"mode",type:"string"}]},{tfOpName:"Pad",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"}],attrs:[{tfName:"constant_value",name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"PadV2",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"padding",type:"number[]"},{start:2,name:"constantValue",type:"number",defaultValue:0}]},{tfOpName:"Reshape",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}]},{tfOpName:"Squeeze",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"axis",tfDeprecatedName:"squeeze_dims",name:"axis",type:"number[]"}]},{tfOpName:"SpaceToBatchND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"paddings",type:"number[]"}]},{tfOpName:"BatchToSpaceND",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"blockShape",type:"number[]"},{start:2,name:"crops",type:"number[]"}]},{tfOpName:"DepthToSpace",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"block_size",name:"blockSize",type:"number"},{tfName:"data_format",name:"dataFormat",type:"string"}]},{tfOpName:"BroadcastTo",category:"transformation",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"shape",type:"number[]"}],attrs:[]},{tfOpName:"BroadcastArgs",category:"transformation",inputs:[{start:0,name:"s0",type:"tensor"},{start:1,name:"s1",type:"tensor"}],attrs:[]}],R3=class{static get Instance(){return this._instance||(this._instance=new this)}constructor(){let e=[c4,f4,m4,g4,y4,A4,x4,b4,v4,w4,k4,I4,S4,T4,C4,N4,E4,R4,F4],t=[].concat(...e.map(r=>r.json));this.opMappers=t.reduce((r,a)=>(r[a.tfOpName]=a,r),{})}transformGraph(e,t={}){let r=e.node,a=[],n=[],s=[],i=r.reduce((f,m)=>(f[m.name]=this.mapNode(m),m.op.startsWith("Placeholder")?a.push(f[m.name]):m.op==="Const"?n.push(f[m.name]):(m.input==null||m.input.length===0)&&s.push(f[m.name]),f),{}),o=[],l=[],d={},u={};t!=null&&(d=this.mapSignatureEntries(t.inputs),u=this.mapSignatureEntries(t.outputs));let p=Object.keys(i);p.forEach(f=>{let m=i[f];m.inputNames.forEach((g,y)=>{let[A,,x]=In(g),b=i[A];if(b.outputs!=null){let v=b.outputs.indexOf(x);if(v!==-1){let C=`${A}:${v}`;m.inputNames[y]=C}}m.inputs.push(b),b.children.push(m)})}),Object.keys(u).length===0?p.forEach(f=>{let m=i[f];m.children.length===0&&l.push(m)}):Object.keys(u).forEach(f=>{let[m]=In(f),g=i[m];g!=null&&(g.signatureKey=u[f],l.push(g))}),Object.keys(d).length>0?Object.keys(d).forEach(f=>{let[m]=In(f),g=i[m];g&&(g.signatureKey=d[f],o.push(g))}):o=a;let h={};e.library!=null&&e.library.function!=null&&(h=e.library.function.reduce((f,m)=>(f[m.signature.name]=this.mapFunction(m),f),{}));let c={nodes:i,inputs:o,outputs:l,weights:n,placeholders:a,signature:t,functions:h};return s.length>0&&(c.initNodes=s),c}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,r)=>(t[e[r].name]=r,t),{})}mapNode(e){let t=h4(e.op)||this.opMappers[e.op]||{};e.attr==null&&(e.attr={});let r={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map(a=>a.startsWith("^")?a.substr(1):a),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return t.inputs!=null&&(r.inputParams=t.inputs.reduce((a,n)=>(a[n.name]={type:n.type,inputIndexStart:n.start,inputIndexEnd:n.end},a),{})),t.attrs!=null&&(r.attrParams=t.attrs.reduce((a,n)=>{let s=n.type,i;switch(n.type){case"string":i=ay(e.attr,n.tfName,n.defaultValue),i===void 0&&!!n.tfDeprecatedName&&(i=ay(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"string[]":i=dy(e.attr,n.tfName,n.defaultValue),i===void 0&&!!n.tfDeprecatedName&&(i=dy(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number":i=sy(e.attr,n.tfName,n.defaultValue||0),i===void 0&&!!n.tfDeprecatedName&&(i=sy(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"number[]":i=uy(e.attr,n.tfName,n.defaultValue),i===void 0&&!!n.tfDeprecatedName&&(i=uy(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool":i=ny(e.attr,n.tfName,n.defaultValue),i===void 0&&!!n.tfDeprecatedName&&(i=ny(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"bool[]":i=hy(e.attr,n.tfName,n.defaultValue),i===void 0&&!!n.tfDeprecatedName&&(i=hy(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape":i=ly(e.attr,n.tfName,n.defaultValue),i===void 0&&!!n.tfDeprecatedName&&(i=ly(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"shape[]":i=py(e.attr,n.tfName,n.defaultValue),i===void 0&&!!n.tfDeprecatedName&&(i=py(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype":i=iy(e.attr,n.tfName,n.defaultValue),i===void 0&&!!n.tfDeprecatedName&&(i=iy(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"dtype[]":i=oy(e.attr,n.tfName,n.defaultValue),i===void 0&&!!n.tfDeprecatedName&&(i=oy(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"func":i=F3(e.attr,n.tfName,n.defaultValue),i===void 0&&!!n.tfDeprecatedName&&(i=F3(e.attr,n.tfDeprecatedName,n.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${n.type} for op: ${e.op}`)}return a[n.name]={value:i,type:s},a},{})),r}mapFunction(e){let t=e.nodeDef,r=[],a=[],n={};t!=null&&(n=t.reduce((d,u)=>(d[u.name]=this.mapNode(u),u.op==="Const"&&a.push(d[u.name]),d),{}));let s=[],i=[];e.signature.inputArg.forEach(d=>{let[u]=In(d.name),p={name:u,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:px(d.type),type:"dtype"}},children:[]};p.signatureKey=d.name,s.push(p),n[u]=p}),Object.keys(n).forEach(d=>{let u=n[d];u.inputNames.forEach((p,h)=>{let[c,,f]=In(p),m=n[c];if(m.outputs!=null){let g=m.outputs.indexOf(f);if(g!==-1){let y=`${c}:${g}`;u.inputNames[h]=y}}u.inputs.push(m),m.children.push(u)})});let o=e.ret;e.signature.outputArg.forEach(d=>{let[u,p]=In(o[d.name]),h=n[u];h!=null&&(h.defaultOutput=p,i.push(h))});let l=this.mapArgsToSignature(e);return{nodes:n,inputs:s,outputs:i,weights:a,placeholders:r,signature:l}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce((t,r)=>(t[r.name]=this.mapArgToTensorInfo(r),t),{}),outputs:e.signature.outputArg.reduce((t,r)=>(t[r.name]=this.mapArgToTensorInfo(r,e.ret),t),{})}}mapArgToTensorInfo(e,t){let r=e.name;return t!=null&&(r=t[r]),{name:r,dtype:e.type}}};function jG(e){let t=Y().global;if(typeof t.atob!="undefined")return t.atob(e);if(typeof Buffer!="undefined")return new Buffer(e,"base64").toString();throw new Error("Unable to decode base64 in this environment. Missing built-in atob() or Buffer()")}function M4(e,t){let r=Array.isArray(e)?String.fromCharCode.apply(null,e):jG(e);return t?r:r.toLowerCase()}function ay(e,t,r,a=!1){let n=e[t];return n!=null?M4(n.s,a):r}function ny(e,t,r){let a=e[t];return a?a.b:r}function sy(e,t,r){let a=e[t]||{},n=a.i!=null?a.i:a.f!=null?a.f:r;return typeof n=="number"?n:parseInt(n,10)}function px(e){switch(typeof e=="string"&&(e=p4[e]),e){case 1:case 19:return"float32";case 3:case 9:case 6:case 4:return"int32";case 10:return"bool";case 2:return"float32";case 7:return"string";default:return null}}function F3(e,t,r){let a=e[t];return a&&a.func?a.func.name:r}function iy(e,t,r){let a=e[t];return a&&a.type?px(a.type):r}function oy(e,t,r){let a=e[t];return a&&a.list&&a.list.type?a.list.type.map(n=>px(n)):r}function $4(e){if(!e.unknownRank)return e.dim!=null?e.dim.map(t=>typeof t.size=="number"?t.size:parseInt(t.size,10)):[]}function ly(e,t,r){let a=e[t];return a&&a.shape?$4(a.shape):r}function uy(e,t,r){let a=e[t];return a?((a.list.f&&a.list.f.length?a.list.f:a.list.i)||[]).map(n=>typeof n=="number"?n:parseInt(n,10)):r}function dy(e,t,r,a=!1){let n=e[t];return n&&n.list&&n.list.s?n.list.s.map(s=>M4(s,a)):r}function py(e,t,r){let a=e[t];return a&&a.list&&a.list.shape?a.list.shape.map(n=>$4(n)):r}function hy(e,t,r){let a=e[t];return a&&a.list&&a.list.b?a.list.b:r}var HG=class{constructor(e,t,r){this.node=e,this.tensorMap=t,this.context=r,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(a=>this.getInput(a)),e.rawAttrs!=null&&(this.attrs=Object.keys(e.rawAttrs).reduce((a,n)=>(a[n]=this.getAttr(n),a),{}))}getInput(e){return Mr(e,this.tensorMap,this.context)}getAttr(e,t){let r=this.node.rawAttrs[e];if(r.tensor!=null)return Mr(e,this.tensorMap,this.context);if(r.i!=null||r.f!=null)return sy(this.node.rawAttrs,e,t);if(r.s!=null)return ay(this.node.rawAttrs,e,t);if(r.b!=null)return ny(this.node.rawAttrs,e,t);if(r.shape!=null)return ly(this.node.rawAttrs,e,t);if(r.type!=null)return iy(this.node.rawAttrs,e,t);if(r.list!=null){if(r.list.i!=null||r.list.f!=null)return uy(this.node.rawAttrs,e,t);if(r.list.s!=null)return dy(this.node.rawAttrs,e,t);if(r.list.shape!=null)return py(this.node.rawAttrs,e,t);if(r.list.b!=null)return hy(this.node.rawAttrs,e,t);if(r.list.type!=null)return oy(this.node.rawAttrs,e,t)}return t}},qG=(e,t,r)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[ue(k("a",e,t,r),k("b",e,t,r))];case"AddN":return[Jf(k("tensors",e,t,r))];case"FloorMod":case"Mod":return[ad(k("a",e,t,r),k("b",e,t,r))];case"Mul":return[L(k("a",e,t,r),k("b",e,t,r))];case"RealDiv":case"Div":return[pe(k("a",e,t,r),k("b",e,t,r))];case"DivNoNan":return[ek(k("a",e,t,r),k("b",e,t,r))];case"FloorDiv":return[ih(k("a",e,t,r),k("b",e,t,r))];case"Sub":return[he(k("a",e,t,r),k("b",e,t,r))];case"Minimum":return[ph(k("a",e,t,r),k("b",e,t,r))];case"Maximum":return[Zn(k("a",e,t,r),k("b",e,t,r))];case"Pow":return[Ds(k("a",e,t,r),k("b",e,t,r))];case"SquaredDifference":return[E2(k("a",e,t,r),k("b",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},KG=(e,t,r)=>{switch(e.op){case"Abs":case"ComplexAbs":return[Qt(k("x",e,t,r))];case"Acos":return[Rw(k("x",e,t,r))];case"Acosh":return[Fw(k("x",e,t,r))];case"Asin":return[$w(k("x",e,t,r))];case"Asinh":return[Pw(k("x",e,t,r))];case"Atan":return[Ow(k("x",e,t,r))];case"Atan2":return[zw(k("x",e,t,r),k("y",e,t,r))];case"Atanh":return[Dw(k("x",e,t,r))];case"Ceil":return[jw(k("x",e,t,r))];case"Complex":return[$s(k("real",e,t,r),k("imag",e,t,r))];case"Cos":return[tm(k("x",e,t,r))];case"Cosh":return[u2(k("x",e,t,r))];case"Elu":return[uh(k("x",e,t,r))];case"Erf":return[rk(k("x",e,t,r))];case"Exp":return[Na(k("x",e,t,r))];case"Expm1":return[ak(k("x",e,t,r))];case"Floor":return[dh(k("x",e,t,r))];case"Log":return[Ea(k("x",e,t,r))];case"Log1p":return[nm(k("x",e,t,r))];case"Imag":return[rm(k("x",e,t,r))];case"Neg":return[zt(k("x",e,t,r))];case"Reciprocal":return[gk(k("x",e,t,r))];case"Real":return[Rp(k("x",e,t,r))];case"Relu":return[Fn(k("x",e,t,r))];case"Round":return[w2(k("x",e,t,r))];case"Selu":return[I2(k("x",e,t,r))];case"Sigmoid":return[Sr(k("x",e,t,r))];case"Sin":return[S2(k("x",e,t,r))];case"Sign":return[xk(k("x",e,t,r))];case"Sinh":return[T2(k("x",e,t,r))];case"Softplus":return[rd(k("x",e,t,r))];case"Sqrt":return[Tr(k("x",e,t,r))];case"Square":return[At(k("x",e,t,r))];case"Tanh":return[hu(k("x",e,t,r))];case"Tan":return[vk(k("x",e,t,r))];case"ClipByValue":return[pa(k("x",e,t,r),k("clipValueMin",e,t,r),k("clipValueMax",e,t,r))];case"Relu6":return[v2(k("x",e,t,r))];case"Rsqrt":return[k2(Mr(e.inputNames[0],t,r))];case"Prod":return[A2(k("x",e,t,r),k("axes",e,t,r))];case"LeakyRelu":return[am(k("x",e,t,r),k("alpha",e,t,r))];case"Prelu":return[dm(k("x",e,t,r),k("alpha",e,t,r))];case"IsNan":return[nk(Mr(e.inputNames[0],t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function Ba(e,t,r=""){if(!(typeof e=="number"||typeof t=="number")){w.assert(e.length===t.length,()=>r+` Shapes ${e} and ${t} must match`);for(let a=0;a<e.length;a++){let n=e[a],s=t[a];w.assert(n<0||s<0||n===s,()=>r+` Shapes ${e} and ${t} must match`)}}}function M3(e){return!(typeof e=="number"||e.some(t=>t<0))}function sp(e,t,r){let a=cy(e,r),n=!M3(a);if(n&&t.length===0)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${a}`);if(n&&t.forEach(s=>{a=cy(s.shape,a)}),!M3(a))throw new Error(`Non-fully-defined elementShape: ${a}`);return a}function cy(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 r=[];for(let a=0;a<e.length;++a){let n=e[a],s=t[a];if(n>=0&&s>=0&&n!==s)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);r[a]=n>=0?n:s}return r}var XG=class{constructor(e,t,r,a,n,s,i){this.name=e,this.dtype=t,this.maxSize=r,this.elementShape=a,this.identicalElementShapes=n,this.dynamicSize=s,this.clearAfterRead=i,this.tensors=[],this.closed_=!1,this.idTensor=Se(0),dr(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 r=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),Ba(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),r.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(r.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);r.tensor=t,dr(t),r.written=!0,this.tensors[e]=r}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((r,a)=>this.write(r,t[a]))}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 a=0;a<this.size();a++)e.push(a)}if(e.length===0)return pt([],[0].concat(this.elementShape));let r=this.readMany(e);return Ba(this.elementShape,r[0].shape,"TensorArray shape mismatch: "),nr(r,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 pt([],[0].concat(this.elementShape));let t=[];for(let a=0;a<this.size();a++)t.push(a);let r=this.readMany(t);return Ba(this.elementShape,r[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${r[0].shape})`),kt(r,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 r=Math.max(...e);if(!this.dynamicSize&&r>=this.maxSize)throw new Error(`Max index must be < array size (${r} vs. ${this.maxSize})`);this.writeMany(e,ra(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 r=0,a=e.map(o=>(r+=o,r));if(r!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to
|
|
tensor.shape[0], but sum of lengths is
|
|
${r}, 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 n=r===0?0:t.size/r,s=[];q(()=>{t=U(t,[1,r,n]);for(let o=0;o<e.length;++o){let l=o===0?0:a[o-1],d=[0,l,0],u=[1,e[o],n];s[o]=U(Oe(t,d,u),this.elementShape)}return s});let i=[];for(let o=0;o<e.length;o++)i[o]=o;this.writeMany(i,s)}},kh=class{constructor(e,t,r,a=-1){this.tensors=e,this.elementShape=t,this.elementDtype=r,e!=null&&e.forEach(n=>{if(r!==n.dtype)throw new Error(`Invalid data types; op elements ${r}, but list elements ${n.dtype}`);Ba(t,n.shape,"TensorList shape mismatch: "),dr(n)}),this.idTensor=Se(0),this.maxNumElements=a,dr(this.idTensor)}get id(){return this.idTensor.id}copy(){return new kh([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.id))&&t.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,r=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(r!==-1&&this.tensors.length!==r)throw new Error(`Operation expected a list with ${r} elements but got a list with ${this.tensors.length} elements.`);Ba(e,this.elementShape,"TensorList shape mismatch: ");let a=sp(this.elementShape,this.tensors,e);return q(()=>{let n=this.tensors.map(s=>U(s,a));return nr(n,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");let r=sp(this.elementShape,this.tensors,e),a=this.tensors.pop();return Ba(a.shape,e,"TensorList shape mismatch: "),U(a,r)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(Ba(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");dr(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(this.maxNumElements!==-1&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);this.tensors.length=e}getItem(e,t,r){if(r!==this.elementDtype)throw new Error(`Invalid data types; op elements ${r}, but list elements ${this.elementDtype}`);if(e<0||e>this.tensors.length)throw new Error(`Trying to access element ${e} in a list with ${this.tensors.length} elements.`);if(this.tensors[e]==null)throw new Error(`element at index ${e} is null.`);Ba(this.tensors[e].shape,t,"TensorList shape mismatch: ");let a=sp(this.elementShape,this.tensors,t);return U(this.tensors[e],a)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||this.maxNumElements!==-1&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);Ba(this.elementShape,t.shape,"TensorList shape mismatch: "),dr(t),this.tensors[e]=t}gather(e,t,r){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);Ba(this.elementShape,r,"TensorList shape mismatch: "),e=e.slice(0,this.size());let a=sp(this.elementShape,this.tensors,r);return e.length===0?pt([],[0].concat(a)):q(()=>{let n=e.map(s=>U(this.tensors[s],a));return nr(n,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);Ba(this.elementShape,t,"TensorList shape mismatch: ");let r=sp(this.elementShape,this.tensors,t);return this.size()===0?pt([],[0].concat(r)):q(()=>{let a=this.tensors.map(n=>U(n,r));return kt(a,0)})}};function ZG(e,t,r){let a=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!==r)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${r}`);let n=e.shape.slice(1);Ba(n,t,"TensorList shape mismatch: ");let s=ra(e);return new kh(s,t,a)}function YG(e,t,r){return new kh([],e,t,r)}function JG(e,t,r,a){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);let n=Math.max(...t);if(a!=null&&a!==-1&&n>=a)throw new Error(`Max index must be < array size (${n} vs. ${a})`);let s=new kh([],r,e.dtype,a),i=ra(e,0);return t.forEach((o,l)=>{s.setItem(o,i[l])}),s}function QG(e,t,r){let a=0,n=t.map(u=>(a+=u,a));if(a!==e.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: ${e.shape}`);let s=e.shape.slice(1),i=cy(s,r),o=a===0?0:e.size/a,l=q(()=>{let u=[];e=U(e,[1,a,o]);for(let p=0;p<t.length;++p){let h=p===0?0:n[p-1],c=[0,h,0],f=[1,t[p],o];u[p]=U(Oe(e,c,f),i)}return e.dispose(),u}),d=new kh([],r,e.dtype,t.length);for(let u=0;u<l.length;u++)d.setItem(u,l[u]);return d}var ej=async(e,t,r)=>{switch(e.op){case"If":case"StatelessIf":{let a=k("thenBranch",e,t,r),n=k("elseBranch",e,t,r),s=k("cond",e,t,r),i=k("args",e,t,r);return(await s.data())[0]?r.functionMap[a].executeFunctionAsync(i,r.tensorArrayMap,r.tensorListMap):r.functionMap[n].executeFunctionAsync(i,r.tensorArrayMap,r.tensorListMap)}case"While":case"StatelessWhile":{let a=k("body",e,t,r),n=k("cond",e,t,r),s=k("args",e,t,r),i=await r.functionMap[n].executeFunctionAsync(s,r.tensorArrayMap,r.tensorListMap),o=s.map(u=>u.id),l=await i[0].data();i.forEach(u=>{!u.kept&&o.indexOf(u.id)===-1&&u.dispose()});let d=s;for(;l[0];){let u=d;d=await r.functionMap[a].executeFunctionAsync(d,r.tensorArrayMap,r.tensorListMap);let p=d.map(c=>c.id);u.forEach(c=>{!c.kept&&o.indexOf(c.id)===-1&&p.indexOf(c.id)===-1&&c.dispose()});let h=await r.functionMap[n].executeFunctionAsync(d,r.tensorArrayMap,r.tensorListMap);l=await h[0].data(),h.forEach(c=>{!c.kept&&o.indexOf(c.id)===-1&&p.indexOf(c.id)===-1&&c.dispose()})}return d}case"LoopCond":{let a=k("pred",e,t,r);return[Vn(a)]}case"Switch":{let a=k("pred",e,t,r),n=k("data",e,t,r);return n.kept||(n=Vn(n)),(await a.data())[0]?[void 0,n]:[n,void 0]}case"Merge":{let a=e.inputNames.find(n=>Mr(n,t,r)!==void 0);if(a){let n=Mr(a,t,r);return[Vn(n)]}return}case"Enter":{let a=k("frameName",e,t,r),n=k("tensor",e,t,r);return r.enterFrame(a),[Vn(n)]}case"Exit":{let a=k("tensor",e,t,r);return r.exitFrame(),[Vn(a)]}case"NextIteration":{let a=k("tensor",e,t,r);return r.nextIteration(),[Vn(a)]}case"TensorArrayV3":{let a=k("size",e,t,r),n=k("dtype",e,t,r),s=k("elementShape",e,t,r),i=k("dynamicSize",e,t,r),o=k("clearAfterRead",e,t,r),l=k("identicalElementShapes",e,t,r),d=k("name",e,t,r),u=new XG(d,n,a,s,l,i,o);return r.addTensorArray(u),[u.idTensor,Se(1)]}case"TensorArrayWriteV3":{let a=k("tensorArrayId",e,t,r),n=k("index",e,t,r),s=k("tensor",e,t,r),i=r.getTensorArray(a.id);return i.write(n,s),[i.idTensor]}case"TensorArrayReadV3":{let a=k("tensorArrayId",e,t,r),n=k("index",e,t,r);return[r.getTensorArray(a.id).read(n)]}case"TensorArrayGatherV3":{let a=k("tensorArrayId",e,t,r),n=k("indices",e,t,r),s=k("dtype",e,t,r);return[r.getTensorArray(a.id).gather(n,s)]}case"TensorArrayScatterV3":{let a=k("tensorArrayId",e,t,r),n=k("indices",e,t,r),s=k("tensor",e,t,r),i=r.getTensorArray(a.id);return i.scatter(n,s),[i.idTensor]}case"TensorArrayConcatV3":{let a=k("tensorArrayId",e,t,r),n=r.getTensorArray(a.id),s=k("dtype",e,t,r);return[n.concat(s)]}case"TensorArraySplitV3":{let a=k("tensorArrayId",e,t,r),n=k("tensor",e,t,r),s=k("lengths",e,t,r),i=r.getTensorArray(a.id);return i.split(s,n),[i.idTensor]}case"TensorArraySizeV3":{let a=k("tensorArrayId",e,t,r),n=r.getTensorArray(a.id);return[Se(n.size(),"int32")]}case"TensorArrayCloseV3":{let a=k("tensorArrayId",e,t,r),n=r.getTensorArray(a.id);return n.clearAndClose(),[n.idTensor]}case"TensorListSetItem":{let a=k("tensorListId",e,t,r),n=k("index",e,t,r),s=k("tensor",e,t,r),i=r.getTensorList(a.id);return i.setItem(n,s),[i.idTensor]}case"TensorListGetItem":{let a=k("tensorListId",e,t,r),n=k("index",e,t,r),s=k("elementShape",e,t,r),i=k("elementDType",e,t,r);return[r.getTensorList(a.id).getItem(n,s,i)]}case"TensorListScatterV2":case"TensorListScatter":{let a=k("indices",e,t,r),n=k("tensor",e,t,r),s=k("elementShape",e,t,r),i=k("numElements",e,t,r),o=JG(n,a,s,i);return r.addTensorList(o),[o.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let a=k("elementShape",e,t,r),n=k("elementDType",e,t,r),s;e.op==="TensorListReserve"?s="numElements":s="maxNumElements";let i=k(s,e,t,r),o=YG(a,n,i);return r.addTensorList(o),[o.idTensor]}case"TensorListGather":{let a=k("tensorListId",e,t,r),n=k("indices",e,t,r),s=k("elementShape",e,t,r),i=k("elementDType",e,t,r);return[r.getTensorList(a.id).gather(n,i,s)]}case"TensorListStack":{let a=k("tensorListId",e,t,r),n=k("elementShape",e,t,r),s=k("elementDType",e,t,r),i=k("numElements",e,t,r);return[r.getTensorList(a.id).stack(n,s,i)]}case"TensorListFromTensor":{let a=k("tensor",e,t,r),n=k("elementShape",e,t,r),s=k("elementDType",e,t,r),i=ZG(a,n,s);return r.addTensorList(i),[i.idTensor]}case"TensorListConcat":{let a=k("tensorListId",e,t,r),n=r.getTensorList(a.id),s=k("dtype",e,t,r),i=k("elementShape",e,t,r);return[n.concat(s,i)]}case"TensorListPushBack":{let a=k("tensorListId",e,t,r),n=k("tensor",e,t,r),s=r.getTensorList(a.id);return s.pushBack(n),[s.idTensor]}case"TensorListPopBack":{let a=k("tensorListId",e,t,r),n=k("elementShape",e,t,r),s=k("elementDType",e,t,r);return[r.getTensorList(a.id).popBack(n,s)]}case"TensorListSplit":{let a=k("tensor",e,t,r),n=k("elementShape",e,t,r),s=k("lengths",e,t,r),i=QG(a,s,n);return r.addTensorList(i),[i.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};function $3(e,t,r){let[a,n]=k("fusedOps",e,t,r),s=a==="biasadd",i=!s,o=n==="prelu",l=a==="fusedbatchnorm",d=k("numArgs",e,t,r);if(s){if(o&&d!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&s&&d!==1)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(l)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");let u=k("strides",e,t,r),p=_c(e,t,r),h=k("dataFormat",e,t,r).toUpperCase(),c=k("dilations",e,t,r),[f,m]=k("args",e,t,r);i&&(m=f,f=void 0);let g=k("leakyreluAlpha",e,t,r);return{stride:u,pad:p,dataFormat:h,dilations:c,biasArg:f,preluArg:m,activationFunc:n,leakyreluAlpha:g}}var tj=(e,t,r)=>{switch(e.op){case"Conv1D":{let a=k("stride",e,t,r),n=k("pad",e,t,r),s=k("dataFormat",e,t,r).toUpperCase(),i=k("dilation",e,t,r);return[s2(k("x",e,t,r),k("filter",e,t,r),a,n,s,i)]}case"Conv2D":{let a=k("strides",e,t,r),n=_c(e,t,r),s=k("dataFormat",e,t,r).toUpperCase(),i=k("dilations",e,t,r);return[Os(k("x",e,t,r),k("filter",e,t,r),[a[1],a[2]],n,s,[i[1],i[2]])]}case"_FusedConv2D":{let{stride:a,pad:n,dataFormat:s,dilations:i,biasArg:o,preluArg:l,activationFunc:d,leakyreluAlpha:u}=$3(e,t,r);return[_s.conv2d({x:k("x",e,t,r),filter:k("filter",e,t,r),strides:[a[1],a[2]],pad:n,dataFormat:s,dilations:[i[1],i[2]],bias:o,activation:d,preluActivationWeights:l,leakyreluAlpha:u})]}case"FusedDepthwiseConv2dNative":{let{stride:a,pad:n,dataFormat:s,dilations:i,biasArg:o,preluArg:l,activationFunc:d,leakyreluAlpha:u}=$3(e,t,r);return[_s.depthwiseConv2d({x:k("x",e,t,r),filter:k("filter",e,t,r),strides:[a[1],a[2]],pad:n,dataFormat:s,dilations:[i[1],i[2]],bias:o,activation:d,preluActivationWeights:l,leakyreluAlpha:u})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{let a=k("outputShape",e,t,r),n=k("strides",e,t,r),s=_c(e,t,r);return[o2(k("x",e,t,r),k("filter",e,t,r),a,[n[1],n[2]],s)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{let a=k("strides",e,t,r),n=_c(e,t,r),s=k("dilations",e,t,r),i=k("dataFormat",e,t,r).toUpperCase();return[lh(k("input",e,t,r),k("filter",e,t,r),[a[1],a[2]],n,i,[s[1],s[2]])]}case"Conv3D":{let a=k("strides",e,t,r),n=k("pad",e,t,r),s=k("dataFormat",e,t,r).toUpperCase(),i=k("dilations",e,t,r);return[l2(k("x",e,t,r),k("filter",e,t,r),[a[1],a[2],a[3]],n,s,[i[1],i[2],i[3]])]}case"AvgPool":{let a=k("strides",e,t,r),n=k("pad",e,t,r),s=k("kernelSize",e,t,r);return[Qf(k("x",e,t,r),[s[1],s[2]],[a[1],a[2]],n)]}case"MaxPool":{let a=k("strides",e,t,r),n=k("pad",e,t,r),s=k("kernelSize",e,t,r);return[om(k("x",e,t,r),[s[1],s[2]],[a[1],a[2]],n)]}case"MaxPoolWithArgmax":{let a=k("strides",e,t,r),n=k("pad",e,t,r),s=k("kernelSize",e,t,r),i=k("includeBatchInIndex",e,t,r),{result:o,indexes:l}=hk(k("x",e,t,r),[s[1],s[2]],[a[1],a[2]],n,i);return[o,l]}case"AvgPool3D":{let a=k("strides",e,t,r),n=k("pad",e,t,r),s=k("kernelSize",e,t,r);return[a2(k("x",e,t,r),[s[1],s[2],s[3]],[a[1],a[2],a[3]],n)]}case"MaxPool3D":{let a=k("strides",e,t,r),n=k("pad",e,t,r),s=k("kernelSize",e,t,r);return[y2(k("x",e,t,r),[s[1],s[2],s[3]],[a[1],a[2],a[3]],n)]}case"Dilation2D":{let a=k("strides",e,t,r),n=k("pad",e,t,r),s=k("dilations",e,t,r),i=a[1],o=a[2],l=s[1],d=s[2];return[Qw(k("x",e,t,r),k("filter",e,t,r),[i,o],n,[l,d],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},rj=(e,t,r)=>{switch(e.op){case"Fill":{let a=k("shape",e,t,r),n=k("dtype",e,t,r),s=k("value",e,t,r);return[td(a,s,n)]}case"LinSpace":{let a=k("start",e,t,r),n=k("stop",e,t,r),s=k("num",e,t,r);return[sk(a,n,s)]}case"Multinomial":{let a=k("logits",e,t,r),n=k("numSamples",e,t,r),s=k("seed",e,t,r);return[fk(a,n,s)]}case"OneHot":{let a=k("indices",e,t,r),n=k("depth",e,t,r),s=k("onValue",e,t,r),i=k("offValue",e,t,r);return[Ep(a,n,s,i)]}case"Ones":return[da(k("shape",e,t,r),k("dtype",e,t,r))];case"OnesLike":return[Ra(k("x",e,t,r))];case"RandomUniform":return[nd(k("shape",e,t,r),k("minval",e,t,r),k("maxval",e,t,r),k("dtype",e,t,r))];case"Range":{let a=k("start",e,t,r),n=k("stop",e,t,r),s=k("step",e,t,r);return[gu(a,n,s,k("dtype",e,t,r))]}case"TruncatedNormal":{let a=k("shape",e,t,r),n=k("mean",e,t,r),s=k("stdDev",e,t,r),i=k("seed",e,t,r);return[fm(a,n,s,k("dtype",e,t,r),i)]}case"Zeros":return[Vt(k("shape",e,t,r),k("dtype",e,t,r))];case"ZerosLike":return[at(k("x",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function C1(e,t,r){let a=k("boxes",e,t,r),n=k("scores",e,t,r),s=k("maxOutputSize",e,t,r),i=k("iouThreshold",e,t,r),o=k("scoreThreshold",e,t,r),l=k("softNmsSigma",e,t,r);return{boxes:a,scores:n,maxOutputSize:s,iouThreshold:i,scoreThreshold:o,softNmsSigma:l}}var aj=async(e,t,r)=>{switch(e.op){case"NonMaxSuppressionV5":{let{boxes:a,scores:n,maxOutputSize:s,iouThreshold:i,scoreThreshold:o,softNmsSigma:l}=C1(e,t,r),d=await Ie.nonMaxSuppressionWithScoreAsync(a,n,s,i,o,l);return[d.selectedIndices,d.selectedScores]}case"NonMaxSuppressionV4":{let{boxes:a,scores:n,maxOutputSize:s,iouThreshold:i,scoreThreshold:o}=C1(e,t,r),l=k("padToMaxOutputSize",e,t,r),d=await Ie.nonMaxSuppressionPaddedAsync(a,n,s,i,o,l);return[d.selectedIndices,d.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{let{boxes:a,scores:n,maxOutputSize:s,iouThreshold:i,scoreThreshold:o}=C1(e,t,r);return[await Ie.nonMaxSuppressionAsync(a,n,s,i,o)]}case"Where":{let a=me(k("condition",e,t,r),"bool"),n=[await R2(a)];return a.dispose(),n}case"ListDiff":return Ak(k("x",e,t,r),k("y",e,t,r));default:throw TypeError(`Node type ${e.op} is not implemented`)}},nj=(e,t,r)=>{switch(e.op){case"TopKV2":{let a=k("x",e,t,r),n=k("k",e,t,r),s=k("sorted",e,t,r),i=wk(a,n,s);return[i.values,i.indices]}case"Unique":{let a=k("x",e,t,r),n=j1(a);return[n.values,n.indices]}case"UniqueV2":{let a=k("x",e,t,r),n=k("axis",e,t,r),s=j1(a,n);return[s.values,s.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},sj=(e,t,r)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":let a=k("default",e,t,r);return[Mr(e.name,t,r)||a];case"Placeholder":return[Mr(e.name,t,r)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{let d=k("x",e,t,r);return[Vn(d)]}case"IdentityN":return k("x",e,t,r).map(d=>Vn(d));case"Snapshot":let n=k("x",e,t,r);return[Vn(n)];case"Shape":return[St(k("x",e,t,r).shape,"int32")];case"ShapeN":return k("x",e,t,r).map(d=>St(d.shape));case"Size":return[Se(k("x",e,t,r).size,"int32")];case"Rank":return[Se(k("x",e,t,r).rank,"int32")];case"NoOp":return[Se(1)];case"Print":let s=k("x",e,t,r),i=k("data",e,t,r),o=k("message",e,t,r),l=k("summarize",e,t,r);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(o);for(let d=0;d<i.length;d++)console.log(Array.prototype.slice.call(i[d].dataSync()).slice(0,l));return[s];default:throw TypeError(`Node type ${e.op} is not implemented`)}},ij=class{constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=Se(0),this.tensorMap=new Map,dr(this.handle)}get id(){return this.handle.id}clearAndClose(){this.tensorMap.forEach(e=>e.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return Se(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);let r=await e.data();return this.tensorMap.forEach(a=>a.dispose()),this.tensorMap.clear(),q(()=>{let a=ra(t),n=r.length,s=a.length;w.assert(n===s,()=>`The number of elements doesn't match, keys has ${n} elements, the values has ${s} elements.`);for(let i=0;i<n;i++){let o=r[i],l=a[i];dr(l),this.tensorMap.set(o,l)}return this.handle})}async find(e,t){this.checkKeyAndValueTensor(e,t);let r=await e.data();return q(()=>{let a=[];for(let n=0;n<r.length;n++){let s=r[n],i=this.findWithDefault(s,t);a.push(i)}return nr(a)})}findWithDefault(e,t){let r=this.tensorMap.get(e);return r!=null?r: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}`)}},oj=async(e,t,r,a)=>{switch(e.op){case"HashTable":case"HashTableV2":{let n=k("keyDType",e,t,r),s=k("valueDType",e,t,r),i=new ij(n,s);return a.addHashTable(e.name,i),[i.handle]}case"LookupTableImport":case"LookupTableImportV2":{let n=k("tableHandle",e,t,r,a),s=k("keys",e,t,r),i=k("values",e,t,r);return[await a.getHashTableById(n.id).import(s,i)]}case"LookupTableFind":case"LookupTableFindV2":{let n=k("tableHandle",e,t,r,a),s=k("keys",e,t,r),i=k("defaultValue",e,t,r);return[await a.getHashTableById(n.id).find(s,i)]}case"LookupTableSize":case"LookupTableSizeV2":{let n=k("tableHandle",e,t,r,a);return[a.getHashTableById(n.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},lj=(e,t,r)=>{switch(e.op){case"ResizeBilinear":{let a=k("images",e,t,r),n=k("size",e,t,r),s=k("alignCorners",e,t,r),i=k("halfPixelCenters",e,t,r);return[Ie.resizeBilinear(a,[n[0],n[1]],s,i)]}case"ResizeNearestNeighbor":{let a=k("images",e,t,r),n=k("size",e,t,r),s=k("alignCorners",e,t,r),i=k("halfPixelCenters",e,t,r);return[Ie.resizeNearestNeighbor(a,[n[0],n[1]],s,i)]}case"CropAndResize":{let a=k("image",e,t,r),n=k("boxes",e,t,r),s=k("boxInd",e,t,r),i=k("cropSize",e,t,r),o=k("method",e,t,r),l=k("extrapolationValue",e,t,r);return[Ie.cropAndResize(a,n,s,i,o,l)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},uj=(e,t,r)=>{switch(e.op){case"Equal":return[Ca(k("a",e,t,r),k("b",e,t,r))];case"NotEqual":return[mu(k("a",e,t,r),k("b",e,t,r))];case"Greater":return[fa(k("a",e,t,r),k("b",e,t,r))];case"GreaterEqual":return[xl(k("a",e,t,r),k("b",e,t,r))];case"Less":return[h2(k("a",e,t,r),k("b",e,t,r))];case"LessEqual":return[bl(k("a",e,t,r),k("b",e,t,r))];case"LogicalAnd":return[ln(k("a",e,t,r),k("b",e,t,r))];case"LogicalNot":return[im(k("a",e,t,r))];case"LogicalOr":return[g2(k("a",e,t,r),k("b",e,t,r))];case"Select":case"SelectV2":return[zr(k("condition",e,t,r),k("a",e,t,r),k("b",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},dj=(e,t,r)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[Ke(k("a",e,t,r),k("b",e,t,r),k("transposeA",e,t,r),k("transposeB",e,t,r))];case"Einsum":return[tk(k("equation",e,t,r),...k("tensors",e,t,r))];case"Transpose":return[rt(k("x",e,t,r),k("perm",e,t,r))];case"_FusedMatMul":let[a,n]=k("fusedOps",e,t,r),s=a==="biasadd",i=n==="prelu",o=k("numArgs",e,t,r),l=k("leakyreluAlpha",e,t,r);if(s){if(i&&o!==2)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&o!==1)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}let[d,u]=k("args",e,t,r);return[_s.matMul({a:k("a",e,t,r),b:k("b",e,t,r),transposeA:k("transposeA",e,t,r),transposeB:k("transposeB",e,t,r),bias:d,activation:n,preluActivationWeights:u,leakyreluAlpha:l})];default:throw TypeError(`Node type ${e.op} is not implemented`)}},pj=(e,t,r)=>{switch(e.op){case"FusedBatchNorm":case"FusedBatchNormV2":return[cu(k("x",e,t,r),k("mean",e,t,r),k("variance",e,t,r),k("offset",e,t,r),k("scale",e,t,r),k("epsilon",e,t,r))];case"FusedBatchNormV3":return[cu(k("x",e,t,r),k("mean",e,t,r),k("variance",e,t,r),k("offset",e,t,r),k("scale",e,t,r),k("epsilon",e,t,r))];case"LRN":return[ik(k("x",e,t,r),k("radius",e,t,r),k("bias",e,t,r),k("alpha",e,t,r),k("beta",e,t,r))];case"Softmax":return[sd(k("x",e,t,r))];case"LogSoftmax":return[c2(k("x",e,t,r))];case"SparseToDense":return[M2(k("sparseIndices",e,t,r),k("outputShape",e,t,r),k("sparseValues",e,t,r),k("defaultValue",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},hj=(e,t,r)=>{switch(e.op){case"Max":{let i=k("axis",e,t,r),o=k("keepDims",e,t,r);return[hr(k("x",e,t,r),i,o)]}case"Mean":{let i=k("axis",e,t,r),o=k("keepDims",e,t,r);return[Wt(k("x",e,t,r),i,o)]}case"Min":{let i=k("axis",e,t,r),o=k("keepDims",e,t,r);return[zs(k("x",e,t,r),i,o)]}case"Sum":{let i=k("axis",e,t,r),o=k("keepDims",e,t,r);return[ke(k("x",e,t,r),i,o)]}case"All":{let i=k("axis",e,t,r),o=k("keepDims",e,t,r);return[t2(k("x",e,t,r),i,o)]}case"Any":{let i=k("axis",e,t,r),o=k("keepDims",e,t,r);return[rf(k("x",e,t,r),i,o)]}case"ArgMax":{let i=k("axis",e,t,r);return[Ta(k("x",e,t,r),i)]}case"ArgMin":{let i=k("axis",e,t,r);return[Mw(k("x",e,t,r),i)]}case"Prod":{let i=k("axis",e,t,r),o=k("keepDims",e,t,r);return[A2(k("x",e,t,r),i,o)]}case"Cumsum":{let i=k("axis",e,t,r),o=k("exclusive",e,t,r),l=k("reverse",e,t,r);return[d2(k("x",e,t,r),i,o,l)]}case"Bincount":let a=k("x",e,t,r),n=k("weights",e,t,r),s=k("size",e,t,r);return[n2(a,n,s)];case"DenseBincount":{let i=k("x",e,t,r),o=k("weights",e,t,r),l=k("size",e,t,r),d=k("binaryOutput",e,t,r);return[Yw(i,o,l,d)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},cj=(e,t,r)=>{switch(e.op){case"ConcatV2":case"Concat":{let a=k("n",e,t,r),n=k("axis",e,t,r),s=k("tensors",e,t,r);return s=s.slice(0,a),[kt(s,n)]}case"Gather":{let a=k("x",e,t,r),n=k("indices",e,t,r);return[fu(a,me(n,"int32"),0)]}case"GatherV2":{let a=k("axis",e,t,r),n=k("batchDims",e,t,r),s=k("x",e,t,r),i=k("indices",e,t,r);return[fu(s,me(i,"int32"),a,n)]}case"Reverse":{let a=k("dims",e,t,r),n=[];for(let i=0;i<a.length;i++)a[i]&&n.push(i);let s=k("x",e,t,r);return[Fa(s,n)]}case"ReverseV2":{let a=k("axis",e,t,r),n=k("x",e,t,r);return[Fa(n,a)]}case"Slice":{let a=k("begin",e,t,r),n=k("size",e,t,r);return[Oe(k("x",e,t,r),a,n)]}case"StridedSlice":{let a=k("begin",e,t,r),n=k("end",e,t,r),s=k("strides",e,t,r),i=k("beginMask",e,t,r),o=k("endMask",e,t,r),l=k("ellipsisMask",e,t,r),d=k("newAxisMask",e,t,r),u=k("shrinkAxisMask",e,t,r),p=k("x",e,t,r);return[bk(p,a,n,s,i,o,l,d,u)]}case"Pack":return q(()=>{let a=k("axis",e,t,r),n=k("tensors",e,t,r),s=n[0].shape,i=Ye(n[0]).shape,o=n.map(l=>{let d=w.arraysEqual(l.shape,s);if(!d&&!w.arraysEqual(Ye(l).shape,i))throw new Error("the input tensors shape does not match");return d?l:U(l,s)});return[nr(o,a)]});case"Unpack":{let a=k("axis",e,t,r),n=k("tensor",e,t,r);return ra(n,a)}case"Tile":{let a=k("reps",e,t,r);return[Wa(k("x",e,t,r),a)]}case"Split":case"SplitV":{let a=k("axis",e,t,r),n=k("numOrSizeSplits",e,t,r),s=k("x",e,t,r);return Kt(s,n,a)}case"ScatterNd":{let a=k("indices",e,t,r),n=k("values",e,t,r),s=k("shape",e,t,r);return[Ck(a,n,s)]}case"GatherNd":{let a=k("x",e,t,r),n=k("indices",e,t,r);return[Nk(a,n)]}case"SparseToDense":{let a=k("sparseIndices",e,t,r),n=k("outputShape",e,t,r),s=k("sparseValues",e,t,r),i=k("defaultValue",e,t,r);return[M2(a,s,n,s.dtype===i.dtype?i:me(i,s.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},fj=(e,t,r)=>{switch(e.op){case"SparseFillEmptyRows":{let{outputIndices:a,outputValues:n,emptyRowIndicator:s,reverseIndexMap:i}=up.sparseFillEmptyRows(k("indices",e,t,r),k("values",e,t,r),k("denseShape",e,t,r),k("defaultValue",e,t,r));return[a,n,s,i]}case"SparseReshape":{let{outputIndices:a,outputShape:n}=up.sparseReshape(k("inputIndices",e,t,r),k("inputShape",e,t,r),k("newShape",e,t,r));return[a,n]}case"SparseSegmentMean":return[up.sparseSegmentMean(k("data",e,t,r),k("indices",e,t,r),k("segmentIds",e,t,r))];case"SparseSegmentSum":return[up.sparseSegmentSum(k("data",e,t,r),k("indices",e,t,r),k("segmentIds",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},mj=(e,t,r)=>{switch(e.op){case"FFT":return[hm(k("x",e,t,r))];case"IFFT":return[Fp(k("x",e,t,r))];case"RFFT":return[cm(k("x",e,t,r))];case"IRFFT":return[N2(k("x",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},gj=(e,t,r)=>{switch(e.op){case"StringNGrams":{let{nGrams:a,nGramsSplits:n}=Dc.stringNGrams(k("data",e,t,r),k("dataSplits",e,t,r),k("separator",e,t,r),k("nGramWidths",e,t,r),k("leftPad",e,t,r),k("rightPad",e,t,r),k("padWidth",e,t,r),k("preserveShortSequences",e,t,r));return[a,n]}case"StringSplit":{let{indices:a,values:n,shape:s}=Dc.stringSplit(k("input",e,t,r),k("delimiter",e,t,r),k("skipEmpty",e,t,r));return[a,n,s]}case"StringToHashBucketFast":return[Dc.stringToHashBucketFast(k("input",e,t,r),k("numBuckets",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},yj=(e,t,r)=>{switch(e.op){case"Cast":return[me(k("x",e,t,r),k("dtype",e,t,r))];case"ExpandDims":{let a=k("axis",e,t,r);return[Ht(k("x",e,t,r),a)]}case"Squeeze":{let a=k("axis",e,t,r);return[Ye(k("x",e,t,r),a)]}case"Reshape":return[U(k("x",e,t,r),k("shape",e,t,r))];case"MirrorPad":return[ck(k("x",e,t,r),k("padding",e,t,r),k("mode",e,t,r))];case"PadV2":case"Pad":return[ja(k("x",e,t,r),k("padding",e,t,r),k("constantValue",e,t,r))];case"SpaceToBatchND":{let a=k("blockShape",e,t,r),n=k("paddings",e,t,r);return[um(k("x",e,t,r),a,n)]}case"BatchToSpaceND":{let a=k("blockShape",e,t,r),n=k("crops",e,t,r);return[em(k("x",e,t,r),a,n)]}case"DepthToSpace":{let a=k("blockSize",e,t,r),n=k("dataFormat",e,t,r).toUpperCase();return[Jw(k("x",e,t,r),a,n)]}case"BroadcastTo":return[xp(k("x",e,t,r),k("shape",e,t,r))];case"BroadcastArgs":return[Gw(k("s0",e,t,r),k("s1",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function P3(e,t,r,a){let n=((s,i,o)=>{switch(s.category){case"arithmetic":return q(()=>qG(s,i,o));case"basic_math":return q(()=>KG(s,i,o));case"control":return ej(s,i,o);case"convolution":return q(()=>tj(s,i,o));case"creation":return q(()=>rj(s,i,o));case"dynamic":return aj(s,i,o);case"evaluation":return q(()=>nj(s,i,o));case"image":return q(()=>lj(s,i,o));case"graph":return q(()=>sj(s,i,o));case"logical":return q(()=>uj(s,i,o));case"matrices":return q(()=>dj(s,i,o));case"normalization":return q(()=>pj(s,i,o));case"reduction":return q(()=>hj(s,i,o));case"slice_join":return q(()=>cj(s,i,o));case"sparse":return q(()=>fj(s,i,o));case"spectral":return q(()=>mj(s,i,o));case"string":return q(()=>gj(s,i,o));case"transformation":return q(()=>yj(s,i,o));case"hash_table":return oj(s,i,o,a);case"custom":let l=h4(s.op);if(l&&l.customExecutor)return l.customExecutor(new HG(s,i,o));throw TypeError(`Custom op ${s.op} is not registered.`);default:throw TypeError(`Unknown op '${s.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,r);return w.isPromise(n)?n.then(s=>[].concat(s)):[].concat(n)}var O3=class{constructor(e={},t={},r={},a={}){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=r,this.functionMap=a,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 r=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(r))}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 z3(e,t,r,a){let n=new Set,s=[],i=null,o=null,l=new Set,d=Object.keys(e).map(h=>la(h)[0]),u=[];a!=null&&(u=a.map(h=>la(h.name)[0]));let p=[...t];for(;p.length>0;){let h=p.pop();if((P4(h)||wj(h)||kj(h))&&i==null&&(i=h,o=i.children.map(c=>c.name).filter(c=>n.has(c))),n.add(h.name),r[h.name]==null&&d.indexOf(h.name)===-1&&u.indexOf(h.name)===-1){if(h.inputs.length===0){s.push(h.name);continue}h.inputs.forEach(c=>{l.has(c.name)||(l.add(c.name),p.push(c))})}}return{inputs:e,outputs:t,usedNodes:n,missingInputs:s,dynamicNode:i,syncInputs:o}}function Aj(e,t,r){let{usedNodes:a,inputs:n}=r,s=[],i=Object.keys(n).map(u=>la(u)[0]).map(u=>e.nodes[u]),o=e.initNodes;i.forEach(u=>{a.has(u.name)&&s.push(u)}),e.weights.forEach(u=>{a.has(u.name)&&s.push(u)}),o!=null&&o.forEach(u=>{a.has(u.name)&&s.push(u)});let l=new Set,d=[];for(;s.length>0;){let u=s.pop();l.add(u.name),t[u.name]||d.push(u),u.children.forEach(p=>{!l.has(p.name)&&a.has(p.name)&&p.inputs.every(h=>l.has(h.name))&&s.push(p)})}return d}var xj=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],bj=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],vj=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"];function P4(e){return xj.indexOf(e.op)>=0}function wj(e){return bj.indexOf(e.op)>=0}function kj(e){return vj.indexOf(e.op)>=0}var fy=class{constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this._functions={},this._functionExecutorMap={},this.intermediateTensors={},this.keepTensorForDebug=!1,this._outputs=e.outputs,this._inputs=e.inputs,this._initNodes=e.initNodes,this._signature=e.signature,this._functions=e.functions,e.functions!=null&&Object.keys(e.functions).forEach(r=>{this._functionExecutorMap[r]=new fy(e.functions[r],this)})}get weightIds(){return this.parent?this.parent.weightIds:this._weightIds}get functionExecutorMap(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap}get weightMap(){return this.parent?this.parent.weightMap:this._weightMap}set weightMap(e){let t=Object.keys(e).map(r=>e[r].map(a=>a.id));this._weightIds=[].concat(...t),this._weightMap=e}set resourceManager(e){this._resourceManager=e}get inputs(){return this._inputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get outputs(){return this._outputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get inputNodes(){return this._inputs.map(e=>e.signatureKey||e.name)}get outputNodes(){return this._outputs.map(e=>{let t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t})}get functions(){return Object.keys(this._functions).reduce((e,t)=>(e[t]=this._functions[t].signature,e),{})}getCompilationKey(e,t){let r=e.map(n=>n.name).sort(),a=t.map(n=>n.name).sort();return r.join(this.SEPERATOR)+"--"+a.join(this.SEPERATOR)}compile(e,t){let r=z3(e,t,this.weightMap,this._initNodes),{missingInputs:a,dynamicNode:n,syncInputs:s}=r;if(n!=null)throw new Error(`This execution contains the node '${n.name}', which has the dynamic op '${n.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${s}]`);if(a.length>0){let i=t.map(l=>l.name),o=Object.keys(e);throw new Error(`Cannot compute the outputs [${i}] from the provided inputs [${o}]. Missing the following inputs: [${a}]`)}return Aj(this.graph,this.weightMap,r)}execute(e,t){e=this.mapInputs(e);let r=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);let a=r.map(u=>this.graph.nodes[la(u)[0]]),n=t.map(u=>la(u)[0]),s=n.map(u=>this.graph.nodes[u]);this.resetIntermediateTensors(),s.length===0&&(s=this._outputs);let i=this.getCompilationKey(a,s),o=this.compiledMap.get(i);o==null&&(o=this.compile(e,s),this.compiledMap.set(i,o));let l={},d={};return q(()=>{let u=new O3(this.weightMap,l,d,this.functionExecutorMap),p={...this.weightMap};Object.keys(e).forEach(f=>{let[m,g]=la(f),y=[];y[g]=e[f],p[m]=y});let h=this.getFrozenTensorIds(p),c={};for(let f=0;f<o.length;f++){let m=o[f];if(!p[m.name]){let g=P3(m,p,u,this._resourceManager);if(w.isPromise(g))throw new Error(`The execution of the op '${m.op}' returned a promise. Please use model.executeAsync() instead.`);p[m.name]=g,this.checkTensorForDisposal(m.name,m,p,u,h,n,c)}}return this.parent==null&&u.dispose(h),t.map(f=>Mr(f,p,u))})}getFrozenTensorIds(e){let t=[].concat.apply([],Object.keys(e).map(r=>e[r]).map(r=>r.map(a=>a.id)));return new Set(t)}checkTensorForDisposal(e,t,r,a,n,s,i){t.category==="control"||s.indexOf(e)!==-1||(r[e].forEach(o=>{o!=null&&(i[o.id]=(i[o.id]||0)+t.children.length)}),t.inputs.forEach(o=>{if(o.category!=="control"){let l=SG(o.name,r,a);l!=null&&l.forEach(d=>{if(d&&!d.kept&&!n.has(d.id)){let u=i[d.id];if(u===1){if(!this.keepTensorForDebug)d.dispose();else{let[p,h]=In(t.name,a);this.intermediateTensors[p]?this.intermediateTensors[p][h]=d:(this.intermediateTensors[p]=[],this.intermediateTensors[p][h]=d)}delete i[d.id]}else u!=null&&i[d.id]--}})}}))}async executeAsync(e,t){return this._executeAsync(e,t)}disposeIntermediateTensors(){!this.intermediateTensors||(Object.keys(this.intermediateTensors).forEach(e=>this.intermediateTensors[e].forEach(t=>t.dispose())),this.disposeTensorsMap())}disposeTensorsMap(){!this.tensorsMap||Object.keys(this.tensorsMap).forEach(e=>{this.tensorsMap[e].forEach(t=>{t&&!t.kept&&!t.isDisposed&&!this.keepIds.has(t.id)&&t.dispose()})})}getIntermediateTensors(){return this.tensorsMap}resetIntermediateTensors(){for(let e in this.intermediateTensors)this.intermediateTensors[e].forEach(t=>t.dispose()),delete this.intermediateTensors[e]}async _executeAsync(e,t,r=!1,a={},n={}){r||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));try{this.keepTensorForDebug=Y().getBool("KEEP_INTERMEDIATE_TENSORS")}catch(d){console.warn(d.message)}this.resetIntermediateTensors();let s=new O3(this.weightMap,a,n,this.functionExecutorMap);this.tensorsMap=await this.executeWithControlFlow(e,s,t,r);let i=t.map(d=>Mr(d,this.tensorsMap,s)),o=i.map(d=>d.id),l=Object.keys(e).map(d=>e[d].id);return this.keepIds=new Set([...o,...l,...this.weightIds]),this.keepTensorForDebug||this.disposeTensorsMap(),this.parent==null&&s.dispose(this.keepIds),i}async executeFunctionAsync(e,t,r){let a=e.reduce((n,s,i)=>(n[this.inputs[i].name]=s,n),{});return this._executeAsync(a,this.outputNodes,!0,t,r)}async executeWithControlFlow(e,t,r,a){let n=Object.keys(e),s=n.map(A=>this.graph.nodes[la(A)[0]]),i=r.map(A=>la(A)[0]),o=i.map(A=>this.graph.nodes[A]);o.length===0&&(o=this._outputs);let{usedNodes:l,missingInputs:d,dynamicNode:u,syncInputs:p}=z3(e,o,this.weightMap,this._initNodes),h=[...s,...this.graph.weights,...this._initNodes||[]].map(A=>({node:A,contexts:t.currentContext})),c={...this.weightMap};Object.keys(e).forEach(A=>{let[x,b]=la(A),v=[];v[b]=e[A],c[x]=v});let f={},m=this.getFrozenTensorIds(c),g={};for(;h.length>0;){let A=this.processStack(s,h,t,c,g,m,i,f,l);await Promise.all(A)}u==null&&!a&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");let y=o.filter(A=>!P4(A)&&!Mr(A.name,c,t)).map(A=>A.name);if(y.length>0){let A="";throw u!=null&&(A=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${p}]`),new Error(`Cannot compute the outputs [${y}] from the provided inputs [${n}]. Consider providing the following inputs: [${d}]. ${A}`)}return c}processStack(e,t,r,a,n,s,i,o,l){let d=[];for(;t.length>0;){let u=t.pop();r.currentContext=u.contexts;let p="";if(u.node.op==="Enter"&&k("isConstant",u.node,a,r)&&([p]=In(u.node.name,r)),a[u.node.name]==null){let h=P3(u.node,a,r,this._resourceManager);p||([p]=In(u.node.name,r));let c=r.currentContext;w.isPromise(h)?d.push(h.then(f=>(a[p]=f,r.currentContext=c,this.checkTensorForDisposal(p,u.node,a,r,s,i,o),this.processChildNodes(u.node,t,r,a,n,l),f))):(a[p]=h,this.checkTensorForDisposal(p,u.node,a,r,s,i,o),this.processChildNodes(u.node,t,r,a,n,l))}else this.processChildNodes(u.node,t,r,a,n,l)}return d}processChildNodes(e,t,r,a,n,s){e.children.forEach(i=>{let[o]=In(i.name,r);n[o]||!s.has(i.name)||(i.op==="Merge"?i.inputNames.some(l=>!!Mr(l,a,r))&&(n[o]=!0,t.push({contexts:r.currentContext,node:i})):i.inputNames.every(l=>!!Mr(l,a,r))&&(n[o]=!0,t.push({contexts:r.currentContext,node:i})))})}dispose(){Object.keys(this.weightMap).forEach(e=>this.weightMap[e].forEach(t=>t.dispose()))}checkInputShapeAndType(e){Object.keys(e).forEach(t=>{let r=e[t],[a]=la(t),n=this.graph.nodes[a];if(n.attrParams.shape&&n.attrParams.shape.value){let s=n.attrParams.shape.value,i=s.length===r.shape.length&&r.shape.every((o,l)=>s[l]===-1||s[l]===o);w.assert(i,()=>`The shape of dict['${n.name}'] provided in model.execute(dict) must be [${s}], but was [${r.shape}]`)}n.attrParams.dtype&&n.attrParams.dtype.value&&w.assert(r.dtype===n.attrParams.dtype.value,()=>`The dtype of dict['${n.name}'] provided in model.execute(dict) must be ${n.attrParams.dtype.value}, but was ${r.dtype}`)})}mapInputs(e){let t={};for(let r in e)if(this._signature!=null&&this._signature.inputs!=null&&this._signature.inputs[r]!=null){let a=this._signature.inputs[r];t[a.name]=e[r]}else t[r]=e[r];return t}checkInputs(e){let t=Object.keys(e).filter(r=>{let[a]=la(r);return this.graph.nodes[a]==null});if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map(t=>this._signature!=null&&this._signature.outputs!=null&&this._signature.outputs[t]!=null?this._signature.outputs[t].name:t,{})}checkOutputs(e){e.forEach(t=>{let[r]=la(t);if(!this.graph.nodes[r])throw new Error(`The output '${t}' is not found in the graph`)})}},Ij=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]}},Sj="?tfjs-format=file",Tj="model.json",qm=class{constructor(e,t={}){this.modelUrl=e,this.loadOptions=t,this.version="n/a",t==null&&(this.loadOptions={}),this.resourceManager=new Ij}get modelVersion(){return this.version}get inputNodes(){return this.executor.inputNodes}get outputNodes(){return this.executor.outputNodes}get inputs(){return this.executor.inputs}get outputs(){return this.executor.outputs}get weights(){return this.executor.weightMap}get metadata(){return this.artifacts.userDefinedMetadata}get modelSignature(){return this.signature}findIOHandler(){let e=this.modelUrl;if(e.load!=null)this.handler=e;else if(this.loadOptions.requestInit!=null)this.handler=Ir.browserHTTPRequest(e,this.loadOptions);else{let t=Ir.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(Ir.browserHTTPRequest(e,this.loadOptions));else if(t.length>1)throw new Error(`Found more than one (${t.length}) load handlers for URL '${[e]}'`);this.handler=t[0]}}async load(){if(this.findIOHandler(),this.handler.load==null)throw new Error("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let e=await this.handler.load();return this.loadSync(e)}loadSync(e){this.artifacts=e;let t=this.artifacts.modelTopology,r;this.artifacts.userDefinedMetadata!=null&&this.artifacts.userDefinedMetadata.signature!=null?r=this.artifacts.userDefinedMetadata.signature:r=this.artifacts.signature,this.signature=r,this.version=`${t.versions.producer}.${t.versions.minConsumer}`;let a=Ir.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new fy(R3.Instance.transformGraph(t,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(a),this.executor.resourceManager=this.resourceManager,e.modelInitializer!=null&&e.modelInitializer.node!=null){let n=R3.Instance.transformGraph(e.modelInitializer);this.initializer=new fy(n),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializer.executeAsync({},[])}return!0}async save(e,t){if(typeof e=="string"){let r=Ir.getSaveHandlers(e);if(r.length===0)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(r.length>1)throw new Error(`Found more than one (${r.length}) save handlers for URL '${e}'`);e=r[0]}if(e.save==null)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return e.save(this.artifacts)}predict(e,t){return this.execute(e,this.outputNodes)}normalizeInputs(e){if(!(e instanceof et)&&!Array.isArray(e))return e;if(e=Array.isArray(e)?e:[e],e.length!==this.inputNodes.length)throw new Error(`Input tensor count mismatch,the graph model has ${this.inputNodes.length} placeholders, while there are ${e.length} input tensors.`);return this.inputNodes.reduce((t,r,a)=>(t[r]=e[a],t),{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}execute(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let r=this.executor.execute(e,t);return r.length>1?r:r[0]}async executeAsync(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let r=await this.executor.executeAsync(e,t);return r.length>1?r:r[0]}getIntermediateTensors(){return this.executor.getIntermediateTensors()}disposeIntermediateTensors(){this.executor.disposeIntermediateTensors()}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce((t,r)=>(t[r]=[e[r]],t),{})}dispose(){this.executor.dispose(),this.initializer&&this.initializer.dispose(),this.resourceManager.dispose()}};async function Cj(e,t={}){if(e==null)throw new Error("modelUrl in loadGraphModel() cannot be null. Please provide a url or an IOHandler that loads the model");t==null&&(t={}),t.fromTFHub&&e.load==null&&(e.endsWith("/")||(e=e+"/"),e=`${e}${Tj}${Sj}`);let r=new qm(e,t);return await r.load(),r}var Nj="0.0.0",O4={};De(O4,{CSVDataset:()=>q4,Dataset:()=>ud,FileDataSource:()=>e6,TextLineDataset:()=>H4,URLDataSource:()=>t6,array:()=>Yj,csv:()=>lH,func:()=>uH,generator:()=>dH,microphone:()=>hH,version_data:()=>cH,webcam:()=>pH,zip:()=>Jj});var Ej=Eo(kf()),Rj=Eo(kf());function Fj(e,t){return cf(e,t)}function cf(e,t,r=new Map,a=new Set){if(e==null)return null;if(typeof Blob=="function"&&e instanceof Blob)return e.slice();if(a.has(e))throw new Error("Circular references are not supported.");if(r.has(e))return r.get(e);let n=t(e);if(n.recurse&&n.value!==null)throw new Error("A deep map function may not return both a value and recurse=true.");if(n.recurse)if(xu(e)){let s=Array.isArray(e)?[]:{};a.add(e);for(let i in e){let o=e[i],l=cf(o,t,r,a);s[i]=l}return a.delete(e),e.__proto__&&(s.__proto__=e.__proto__),s}else throw new Error(`Can't recurse into non-iterable type: ${e}`);else return r.set(e,n.value),n.value}function Mj(e,t=D4){return z4(e,t)}function z4(e,t,r=new Set){let a=e[0];if(r.has(a))throw new Error("Circular references are not supported.");let n=t(e);if(n.recurse&&n.value!==null)throw new Error("A deep zip function may not return both a value and recurse=true.");if(n.recurse)if(xu(a)){let s=Array.isArray(a)?[]:{};r.add(a);for(let i in a){let o=e.map(d=>d[i]),l=z4(o,t,r);s[i]=l}return r.delete(a),s}else throw new Error(`Can't recurse into non-iterable type: ${a}`);else return n.value}function D4(e){return e===null?null:xu(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function _4(e,t){let r=new Map;cf(e,t,r);for(let a of Array.from(r.keys())){let n=r.get(a);if(w.isPromise(n)){let s=await n;r.set(a,s)}}return cf(e,t,r)}function xu(e){let t=!1;if(Y().get("IS_BROWSER"))t=e instanceof TextDecoder;else{let{StringDecoder:r}=wv();t=e instanceof r}return e!=null&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||typeof e=="object"&&!(e instanceof et)&&!(e instanceof Promise)&&!t)}function $j(e){return e==null||Pj(e)||Array.isArray(e)||typeof e=="object"&&e instanceof et||w.isTypedArray(e)}function Pj(e){return e===null||typeof e!="object"&&typeof e!="function"}function Oj(e){return Fj(e,zj)}function zj(e){return e instanceof et?{value:e.clone(),recurse:!1}:xu(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}var L4=class{constructor(e){if(this.capacity=e,this.begin=0,this.end=0,e==null)throw new RangeError("Can't create a ring buffer of unknown capacity.");if(e<1)throw new RangeError("Can't create ring buffer of capacity < 1.");this.data=new Array(e),this.doubledCapacity=2*e}wrap(e){for(;e<0;)e+=this.doubledCapacity;return e%this.doubledCapacity}get(e){if(e<0)throw new RangeError("Can't get item at a negative index.");return this.data[e%this.capacity]}set(e,t){if(e<0)throw new RangeError("Can't set item at a negative index.");this.data[e%this.capacity]=t}length(){let e=this.end-this.begin;return e<0&&(e=this.doubledCapacity+e),e}isFull(){return this.length()===this.capacity}isEmpty(){return this.length()===0}push(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.set(this.end,e),this.end=this.wrap(this.end+1)}pushAll(e){for(let t of e)this.push(t)}pop(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");this.end=this.wrap(this.end-1);let e=this.get(this.end);return this.set(this.end,void 0),e}unshift(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.begin=this.wrap(this.begin-1),this.set(this.begin,e)}shift(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");let e=this.get(this.begin);return this.set(this.begin,void 0),this.begin=this.wrap(this.begin+1),e}shuffleExcise(e){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");let t=this.wrap(this.begin+e),r=this.get(t);return this.set(t,this.pop()),r}},B4=class extends L4{constructor(){super(B4.INITIAL_CAPACITY)}isFull(){return!1}push(e){super.isFull()&&this.expand(),super.push(e)}unshift(e){super.isFull()&&this.expand(),super.unshift(e)}expand(){let e=this.capacity*2,t=new Array(e),r=this.length();for(let a=0;a<r;a++)t[a]=this.get(this.wrap(this.begin+a));this.data=t,this.capacity=e,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=r}},W4=B4;W4.INITIAL_CAPACITY=32;function V4(e){return new Lj(e)}function hx(e){return new Bj(e)}function Dj(e,t){return new U4(e,t)}function _j(e,t=G4.FAIL){return new Xj(e,t)}var fr=class{async toArray(){let e=[],t=await this.next();for(;!t.done;)e.push(t.value),t=await this.next();return e}async toArrayForTest(){let e=this.prefetch(100),t=[],r=await e.next();for(;!r.done;)t.push(r.value),r=await e.next();return t}async resolveFully(){let e=await this.next();for(;!e.done;)e=await this.next()}async resolveWhile(e){let t=await this.next(),r=e(t.value);for(;!t.done&&r;)t=await this.next(),r=e(t.value)}handleErrors(e){return new qj(this,e)}filter(e){return new jj(this,e)}map(e){return new Hj(this,e)}mapAsync(e){return new D3(this,e)}serialMapAsync(e){return new D3(this,e).serial()}flatmap(e){return new Kj(this,e)}async forEachAsync(e){return this.map(e).resolveFully()}async serialForEach(e){return this.serialMapAsync(e).resolveWhile(t=>t===!0)}rowMajorBatch(e,t=!0){return new Gj(this,e,t)}columnMajorBatch(e,t=!0,r=D4){return this.rowMajorBatch(e,t).map(a=>Mj(a,r))}concatenate(e,t){return new U4(V4([this,e]),t)}take(e){return e<0||e==null?this:new Uj(this,e)}skip(e){return e<0||e==null?this:new Vj(this,e)}prefetch(e){return new j4(this,e)}shuffle(e,t){return new Zj(this,e,t)}serial(){return new Wj(this)}},Lj=class extends fr{constructor(e){super();this.items=e,this.trav=0}summary(){return`Array of ${this.items.length} items`}async next(){if(this.trav>=this.items.length)return{value:null,done:!0};let e=this.items[this.trav];return this.trav++,{value:Oj(e),done:!1}}},Bj=class extends fr{constructor(e){super();this.nextFn=e}summary(){return"Function call"}async next(){try{return this.nextFn()}catch(e){throw e.message=`Error thrown while iterating through a dataset: ${e.message}`,e}}},Wj=class extends fr{constructor(e){super();this.upstream=e,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Serial`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){return this.upstream.next()}},Vj=class extends fr{constructor(e,t){super();this.upstream=e,this.maxCount=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Skip`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.count++<this.maxCount;){let e=await this.upstream.next();if(e.done)return e;re(e.value)}return this.upstream.next()}},Uj=class extends fr{constructor(e,t){super();this.upstream=e,this.maxCount=t,this.count=0}summary(){return`${this.upstream.summary()} -> Take`}async next(){return this.count++>=this.maxCount?{value:null,done:!0}:this.upstream.next()}},Gj=class extends fr{constructor(e,t,r=!0){super();this.upstream=e,this.batchSize=t,this.enableSmallLastBatch=r,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> RowMajorBatch`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){let e=[];for(;e.length<this.batchSize;){let t=await this.upstream.next();if(t.done)return this.enableSmallLastBatch&&e.length>0?{value:e,done:!1}:{value:null,done:!0};e.push(t.value)}return{value:e,done:!1}}},jj=class extends fr{constructor(e,t){super();this.upstream=e,this.predicate=t,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> Filter`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;){let e=await this.upstream.next();if(e.done||this.predicate(e.value))return e;re(e.value)}}},Hj=class extends fr{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Map`}async next(){let e=await this.upstream.next();if(e.done)return{value:null,done:!0};let t=rn.getTensorsInContainer(e.value),r=this.transform(e.value),a=rn.getTensorsInContainer(r);for(let n of t)rn.isTensorInList(n,a)||n.dispose();return{value:r,done:!1}}},qj=class extends fr{constructor(e,t){super();this.upstream=e,this.handler=t,this.count=0,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> handleErrors`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;;)try{return await this.upstream.next()}catch(e){if(!this.handler(e))return{value:null,done:!0}}}},D3=class extends fr{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> AsyncMap`}async next(){let e=await this.upstream.next();if(e.done)return{value:null,done:!0};let t=rn.getTensorsInContainer(e.value),r=await this.transform(e.value),a=rn.getTensorsInContainer(r);for(let n of t)rn.isTensorInList(n,a)||n.dispose();return{value:r,done:!1}}},cx=class extends fr{constructor(){super();this.outputQueue=new W4,this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){for(;this.outputQueue.length()===0;)if(!await this.pump())return{value:null,done:!0};return{value:this.outputQueue.shift(),done:!1}}},Kj=class extends cx{constructor(e,t){super();this.upstream=e,this.transform=t}summary(){return`${this.upstream.summary()} -> Flatmap`}async pump(){let e=await this.upstream.next();if(e.done)return!1;let t=rn.getTensorsInContainer(e.value),r=this.transform(e.value),a=rn.getTensorsInContainer(r);this.outputQueue.pushAll(r);for(let n of t)rn.isTensorInList(n,a)||n.dispose();return!0}},U4=class extends fr{constructor(e,t){super();this.baseErrorHandler=t,this.lastRead=null,this.iterator=null,this.moreIterators=e}summary(){return"TODO: fill in upstream of chained summaries -> Chained"}async next(){return this.lastRead=this.readFromChain(this.lastRead),this.lastRead}async readFromChain(e){if(await e,this.iterator==null){let r=await this.moreIterators.next();if(r.done)return{value:null,done:!0};this.iterator=r.value,this.baseErrorHandler!=null&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler))}let t=await this.iterator.next();return t.done?(this.iterator=null,this.readFromChain(e)):t}},G4=(e=>(e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST",e))(G4||{}),Xj=class extends fr{constructor(e,t=0){super();this.iterators=e,this.mismatchMode=t,this.count=0,this.currentPromise=null}summary(){return"{TODO: fill in upstream of zip summaries} -> Zip"}async nextState(e){await e;let t=0,r=0;function a(s){return s instanceof fr?{value:s.next().then(i=>(t++,i.done&&r++,i.value)),recurse:!1}:{value:null,recurse:!0}}let n=await _4(this.iterators,a);if(t===r)return{value:null,done:!0};if(r>0)switch(this.mismatchMode){case 0:throw new Error(`Zipped streams should have the same length. Mismatched at element ${this.count}.`);case 1:return{value:null,done:!0};case 2:default:}return this.count++,{value:n,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}},j4=class extends fr{constructor(e,t){super();this.upstream=e,this.bufferSize=t,this.buffer=new L4(t)}summary(){return`${this.upstream.summary()} -> Prefetch`}refill(){for(;!this.buffer.isFull();){let e=this.upstream.next();this.buffer.push(e)}}next(){return this.refill(),this.buffer.shift()}},Zj=class extends j4{constructor(e,t,r){super(e,t);this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=Rj.alea(r||w.now().toString()),this.lastRead=Promise.resolve({value:null,done:!1})}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}randomInt(e){return Math.floor(this.random()*e)}chooseIndex(){return this.randomInt(this.buffer.length())}async serialNext(){for(this.upstreamExhausted||this.refill();!this.buffer.isEmpty();){let e=this.chooseIndex(),t=await this.buffer.shuffleExcise(e);if(t.done)this.upstreamExhausted=!0;else return this.refill(),t}return{value:null,done:!0}}},ud=class{constructor(){this.size=null}batch(e,t=!0){let r=this;w.assert(e>0,()=>`batchSize needs to be positive, but it is
|
|
${e}`);let a;return this.size===1/0||this.size==null?a=this.size:t?a=Math.ceil(this.size/e):a=Math.floor(this.size/e),oa(async()=>(await r.iterator()).columnMajorBatch(e,t,Qj),a)}concatenate(e){let t=this,r;return this.size===1/0||e.size===1/0?r=1/0:this.size!=null&&e.size!=null?r=this.size+e.size:r=null,oa(async()=>(await t.iterator()).concatenate(await e.iterator()),r)}filter(e){let t=this,r;return this.size===1/0?r=1/0:r=null,oa(async()=>(await t.iterator()).filter(a=>q(()=>e(a))),r)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){let t=this;return oa(async()=>(await t.iterator()).map(r=>q(()=>e(r))),this.size)}mapAsync(e){let t=this;return oa(async()=>(await t.iterator()).mapAsync(e),this.size)}prefetch(e){if(e==null)throw new RangeError("`Dataset.prefetch()` requires bufferSize to be specified.");let t=this;return oa(async()=>(await t.iterator()).prefetch(e),this.size)}repeat(e){let t=this,r;return this.size!=null&&e>0?r=this.size*e:e===0?r=0:this.size!=null&&(e===void 0||e<0)?r=1/0:r=null,oa(async()=>{let a=hx(async()=>({value:await t.iterator(),done:!1}));return Dj(a.take(e))},r)}skip(e){let t=this,r;return this.size!=null&&e>=0&&this.size>=e?r=this.size-e:this.size!=null&&(this.size<e||e===void 0||e<0)?r=0:r=null,oa(async()=>(await t.iterator()).skip(e),r)}shuffle(e,t,r=!0){if(e==null||e<0)throw this.size==null?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);let a=this,n=Ej.alea(t||w.now().toString());return oa(async()=>{let s=n.int32();return r&&(s+=n.int32()),(await a.iterator()).shuffle(e,s.toString())},this.size)}take(e){let t=this,r;return this.size!=null&&this.size>e?r=e:this.size!=null&&this.size<=e?r=this.size:r=null,oa(async()=>(await t.iterator()).take(e),r)}async toArray(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArray()}async toArrayForTest(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArrayForTest()}};ud.MAX_BUFFER_SIZE=1e4;function oa(e,t=null){return new class extends ud{constructor(){super(...arguments);this.size=t}async iterator(){return e()}}}function Yj(e){return oa(async()=>V4(e),e.length)}function Jj(e){if(!xu(e))throw new Error("The argument to zip() must be an object or array.");let t;if(Array.isArray(e))for(let r=0;r<e.length;r++)t=t==null?e[r].size:Math.min(t,e[r].size);else if(e instanceof Object)for(let r in e)t=t==null?e[r].size:Math.min(t,e[r].size);return oa(async()=>{let r=await _4(e,a=>{if(a instanceof ud)return{value:a.iterator(),recurse:!1};if(xu(a))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return _j(r,1)},t)}function Qj(e){if(e===null)return null;let t=e[0];return $j(t)?{value:eH(e),recurse:!1}:{value:null,recurse:!0}}function eH(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof et?nr(e):pt(e)}var H4=class extends ud{constructor(e){super();this.input=e}async iterator(){return(await this.input.iterator()).decodeUTF8().split(`
|
|
`).map(e=>(e.endsWith("\r")&&(e=e.slice(0,-1)),e))}},Rc='"',ip=Symbol("out"),_3=Symbol("field"),Fc=Symbol("quote"),N1=Symbol("quoteafterquote"),L3=Symbol("quoteinquote"),q4=class extends ud{constructor(e,t){super();this.input=e,this.hasHeader=!0,this.fullColumnNames=null,this.columnNamesValidated=!1,this.columnConfigs=null,this.configuredColumnsOnly=!1,this.delimiter=",",this.delimWhitespace=!1,this.base=new H4(e),t||(t={}),this.hasHeader=t.hasHeader!==!1,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(w.assert(t.delimiter==null,()=>"Delimiter should not be provided when delimWhitespace is true."),this.delimWhitespace=!0,this.delimiter=" "):this.delimiter=t.delimiter?t.delimiter:","}async columnNames(){return this.columnNamesValidated||await this.setColumnNames(),this.configuredColumnsOnly?Object.keys(this.columnConfigs):this.fullColumnNames}async setColumnNames(){let e=await this.maybeReadHeaderLine();if(!this.fullColumnNames&&!e)throw new Error("Column names must be provided if there is no header line.");this.fullColumnNames&&e&&w.assert(e.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);let t=this.fullColumnNames.reduce((a,n)=>(a[n]=a[n]+1||1,a),{}),r=Object.keys(t).filter(a=>t[a]>1);if(w.assert(r.length===0,()=>"Duplicate column names found: "+r.toString()),this.columnConfigs){for(let a of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(a)===-1)throw new Error('The key "'+a+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){let e=await(await this.base.iterator()).next();if(e.done)throw new Error("No data was found for CSV parsing.");let t=e.value;return this.parseRow(t,!1)}else return null}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(t=>this.makeDataElement(t))}makeDataElement(e){let t=this.parseRow(e),r={},a={};for(let n=0;n<this.fullColumnNames.length;n++){let s=this.fullColumnNames[n],i=this.columnConfigs?this.columnConfigs[s]:null;if(!(this.configuredColumnsOnly&&!i)){let o=t[n],l=null;if(o==="")if(i&&i.default!==void 0)l=i.default;else{if(i&&(i.required||i.isLabel))throw new Error(`Required column ${s} is empty in this line: ${e}`);l=void 0}else{let d=Number(o);if(isNaN(d))i&&i.dtype==="bool"?l=this.getBoolean(o):l=o;else if(!i||!i.dtype)l=d;else switch(i.dtype){case"float32":l=d;break;case"int32":l=Math.floor(d);break;case"bool":l=this.getBoolean(o);break;default:l=d}}i&&i.isLabel?a[s]=l:r[s]=l}}return Object.keys(a).length===0?r:{xs:r,ys:a}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){let r=[],a=0,n=e.length,s=ip;for(let i=0;i<n;i++)switch(s){case ip:switch(e.charAt(i)){case Rc:a=i+1,s=Fc;break;case this.delimiter:if(a=i+1,this.delimiter===" "&&this.delimWhitespace)break;r.push(""),s=ip;break;default:s=_3,a=i;break}break;case _3:switch(e.charAt(i)){case this.delimiter:r.push(e.substring(a,i)),s=ip,a=i+1;break;default:}break;case Fc:switch(e.charAt(i)){case Rc:s=N1;break;default:}break;case N1:switch(e.charAt(i)){case this.delimiter:r.push(e.substring(a,i-1)),s=ip,a=i+1;break;case Rc:s=Fc;break;default:s=L3;break}break;case L3:switch(e.charAt(i)){case Rc:s=Fc;break;default:}break;default:}if(s===N1?r.push(e.substring(a,n-1)):r.push(e.substring(a)),t&&r.length!==this.fullColumnNames.length)throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${r}`);return r}},K4=class extends fr{constructor(e){super();this.microphoneConfig=e,this.isClosed=!1,this.fftSize=e.fftSize||1024;let t=Math.log2(this.fftSize);if(this.fftSize<0||t<4||t>14||!Number.isInteger(t))throw new Error(`Invalid fftSize: it must be a power of 2 between 2 to 4 and 2 to 14, but got ${this.fftSize}`);if(this.numFrames=e.numFramesPerSpectrogram||43,this.sampleRateHz=e.sampleRateHz,this.columnTruncateLength=e.columnTruncateLength||this.fftSize,this.audioTrackConstraints=e.audioTrackConstraints,this.smoothingTimeConstant=e.smoothingTimeConstant||0,this.includeSpectrogram=e.includeSpectrogram!==!1,this.includeWaveform=e.includeWaveform===!0,!this.includeSpectrogram&&!this.includeWaveform)throw new Error("Both includeSpectrogram and includeWaveform are false. At least one type of data should be returned.")}summary(){return"microphone"}static async create(e={}){if(Y().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");let t=new K4(e);return await t.start(),t}async start(){try{this.stream=await navigator.mediaDevices.getUserMedia({audio:this.audioTrackConstraints==null?!0:this.audioTrackConstraints,video:!1})}catch(r){throw new Error(`Error thrown while initializing video stream: ${r.message}`)}if(!this.stream)throw new Error("Could not obtain audio from microphone.");let e=window.AudioContext||window.webkitAudioContext;if(this.audioContext=new e,!this.sampleRateHz)this.sampleRateHz=this.audioContext.sampleRate;else if(this.audioContext.sampleRate!==this.sampleRateHz)throw new Error(`Mismatch in sampling rate: Expected: ${this.sampleRateHz}; Actual: ${this.audioContext.sampleRate}`);let t=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=this.fftSize*2,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,t.connect(this.analyser),this.freqData=new Float32Array(this.fftSize),this.timeData=new Float32Array(this.fftSize)}async next(){if(this.isClosed)return{value:null,done:!0};let e,t,r=await this.getAudioData();if(this.includeSpectrogram){let a=this.flattenQueue(r.freqDataQueue);e=this.getTensorFromAudioDataArray(a,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){let a=this.flattenQueue(r.timeDataQueue);t=this.getTensorFromAudioDataArray(a,[this.numFrames*this.fftSize,1])}return{value:{spectrogram:e,waveform:t},done:!1}}async capture(){return(await this.next()).value}async getAudioData(){let e=[],t=[],r=0;return new Promise(a=>{let n=setInterval(()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-1/0&&a({freqDataQueue:e,timeDataQueue:t}),e.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),t.push(this.timeData.slice())),++r===this.numFrames&&(clearInterval(n),a({freqDataQueue:e,timeDataQueue:t}))},this.fftSize/this.sampleRateHz*1e3)})}stop(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),this.stream!=null&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())}toArray(){throw new Error("Can not convert infinite audio stream to array.")}getSampleRate(){return this.sampleRateHz}flattenQueue(e){let t=e[0].length,r=new Float32Array(e.length*t);return e.forEach((a,n)=>r.set(a,n*t)),r}getTensorFromAudioDataArray(e,t){let r=new Float32Array(w.sizeFromShape(t));return r.set(e,r.length-e.length),pt(r,t)}},X4=class extends fr{constructor(e,t){super();if(this.webcamVideoElement=e,this.webcamConfig=t,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=St([0],"int32"),this.webcamConfig.centerCrop){let r=this.webcamConfig.resizeWidth*1/this.webcamVideoElement.width,a=this.webcamConfig.resizeHeight*1/this.webcamVideoElement.height,n=(1-r)/2,s=(1-a)/2,i=n+r,o=a+s;this.cropBox=an([s,n,o,i],[1,4])}else this.cropBox=an([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(Y().get("IS_NODE"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=document.createElement("video"),!t.resizeWidth||!t.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");e.width=t.resizeWidth,e.height=t.resizeHeight}let r=new X4(e,t);return await r.start(),r}async start(){this.webcamConfig.facingMode&&w.assert(this.webcamConfig.facingMode==="user"||this.webcamConfig.facingMode==="environment",()=>`Invalid webcam facing mode: ${this.webcamConfig.facingMode}. Please provide 'user' or 'environment'`);try{this.stream=await navigator.mediaDevices.getUserMedia({video:{deviceId:this.webcamConfig.deviceId,facingMode:this.webcamConfig.facingMode?this.webcamConfig.facingMode:"user",width:this.webcamVideoElement.width,height:this.webcamVideoElement.height}})}catch(e){throw e.message=`Error thrown while initializing video stream: ${e.message}`,e}if(!this.stream)throw new Error("Could not obtain video from webcam.");try{this.webcamVideoElement.srcObject=this.stream}catch(e){console.log(e),this.webcamVideoElement.src=window.URL.createObjectURL(this.stream)}return this.webcamVideoElement.play(),this.isClosed=!1,new Promise(e=>{this.webcamVideoElement.onloadedmetadata=()=>{e()}})}async next(){if(this.isClosed)return{value:null,done:!0};let e;try{e=$a.fromPixels(this.webcamVideoElement)}catch(t){throw new Error(`Error thrown converting video to pixels: ${JSON.stringify(t)}`)}if(this.resize)try{return{value:this.cropAndResizeFrame(e),done:!1}}catch(t){throw new Error(`Error thrown cropping the video: ${t.message}`)}finally{e.dispose()}else return{value:e,done:!1}}needToResize(){return!!(this.webcamConfig.resizeWidth&&this.webcamConfig.resizeHeight&&(this.webcamVideoElement.width!==this.webcamConfig.resizeWidth||this.webcamVideoElement.height!==this.webcamConfig.resizeHeight))}cropAndResizeFrame(e){return q(()=>{let t=Ht(me(e,"float32"),0),r;r=Ie.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");let a=r.shape;return U(r,a.slice(1))})}async capture(){return(await this.next()).value}stop(){this.stream.getTracks().forEach(e=>e.stop());try{this.webcamVideoElement.srcObject=null}catch(e){console.log(e),this.webcamVideoElement.src=null}this.isClosed=!0}toArray(){throw new Error("Can not convert infinite video stream to array.")}},Z4=class{},Y4=class extends fr{split(e){return new tH(this,e)}},tH=class extends Y4{constructor(e,t){super();this.upstream=e,this.impl=new rH(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},rH=class extends cx{constructor(e,t){super();this.upstream=e,this.separator=t,this.carryover=""}summary(){return`${this.upstream.summary()} -> Split('${this.separator}')`}async pump(){let e=await this.upstream.next();if(e.done)return this.carryover===""?!1:(this.outputQueue.push(this.carryover),this.carryover="",!0);let t=e.value.split(this.separator);t[0]=this.carryover+t[0];for(let r of t.slice(0,-1))this.outputQueue.push(r);return this.carryover=t[t.length-1],!0}},aH=class extends fr{decodeUTF8(){return new nH(this)}},nH=class extends Y4{constructor(e){super();this.upstream=e,this.impl=new sH(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},sH=class extends cx{constructor(e){super();if(this.upstream=e,Y().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{let{StringDecoder:t}=wv();this.decoder=new t("utf8")}}summary(){return`${this.upstream.summary()} -> Utf8`}async pump(){let e=await this.upstream.next(),t;if(e.done)return!1;t=e.value;let r;return Y().get("IS_BROWSER")?r=this.decoder.decode(t,{stream:!0}):r=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(r),!0}},J4=class extends aH{constructor(e,t={}){super();this.file=e,this.options=t,w.assert(e instanceof Uint8Array||(Y().get("IS_BROWSER")?e instanceof File||e instanceof Blob:!1),()=>"FileChunkIterator only supports File, Blob and Uint8Array right now."),this.offset=t.offset||0,this.chunkSize=t.chunkSize||1024*1024}summary(){return`FileChunks ${this.file}`}async next(){return this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size)?{value:null,done:!0}:{value:await new Promise((e,t)=>{let r=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)e(new Uint8Array(this.file.slice(this.offset,r)));else{let a=new FileReader;a.onload=s=>{let i=a.result;if(i instanceof ArrayBuffer&&(i=new Uint8Array(i)),!(i instanceof Uint8Array))return t(new TypeError("FileReader returned unknown type."));e(i)},a.onabort=s=>t(new Error("Aborted")),a.onerror=s=>t(new Error(s.type));let n=this.file.slice(this.offset,r);a.readAsArrayBuffer(n)}this.offset=r}),done:!1}}};async function iH(e,t={},r){let a,n;typeof e=="string"?a=e:(a=e.url,n=oH(e));let s=await(r||w.fetch)(a,n);if(s.ok){let i=new Uint8Array(await s.arrayBuffer());return new J4(i,t)}else throw new Error(s.statusText)}var oH=e=>({method:e.method,headers:e.headers,body:e.body,mode:e.mode,credentials:e.credentials,cache:e.cache,redirect:e.redirect,referrer:e.referrer,integrity:e.integrity});function Q4(e){return typeof e=="string"&&e.substr(0,7)==="file://"}var e6=class extends Z4{constructor(e,t={}){super();this.input=e,this.options=t}async iterator(){if(Q4(this.input)&&Y().get("IS_NODE")){let e=Hc();this.input=e.readFileSync(this.input.substr(7))}return new J4(this.input,this.options)}},t6=class extends Z4{constructor(e,t={}){super();this.url=e,this.fileOptions=t}async iterator(){return Q4(this.url)?new e6(this.url,this.fileOptions).iterator():iH(this.url,this.fileOptions)}};function lH(e,t={}){return new q4(new t6(e),t)}function uH(e){let t=hx(e);return oa(async()=>t)}function dH(e){return oa(async()=>{let t=await e();return hx(()=>t.next())})}async function pH(e,t){return X4.create(e,t)}async function hH(e){return K4.create(e)}var cH="0.0.0";function Ne(e,t){Array.isArray(e)||(e=[e]),e.forEach(r=>{r!=null&&w.assert(r.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the CPU backend.`)})}var fH=Ha.whereImpl,r6=class extends Iu{constructor(){super();this.blockSize=48,this.firstUse=!0,this.data=new Dp(this,kr())}nextDataId(){return r6.nextDataId++}write(e,t,r){this.firstUse&&(this.firstUse=!1,Y().get("IS_NODE")&&N.warn(`
|
|
============================
|
|
Hi there \u{1F44B}. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details.
|
|
============================`));let a={id:this.nextDataId()};return this.data.set(a,{values:e,dtype:r,refCount:1}),a}makeTensorInfo(e,t,r){let a;if(t==="string"&&r!=null&&r.length>0&&w.isString(r[0])){let n=r.map(s=>w.encodeString(s));a=this.write(n,e,t)}else a=this.write(r,e,t);return{dataId:a,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){let t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){let t=this.data.get(e);t.refCount--}}move(e,t,r,a,n){this.data.set(e,{values:t,dtype:a,refCount:n})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){let{dtype:t,complexTensorInfos:r}=this.data.get(e);if(t==="complex64"){let a=this.readSync(r.real.dataId),n=this.readSync(r.imag.dataId);return N.mergeRealAndImagArrays(a,n)}return this.data.get(e).values}bufferSync(e){let t=this.readSync(e.dataId),r=t;if(e.dtype==="string")try{r=t.map(a=>w.decodeString(a))}catch(a){throw new Error("Failed to decode encoded string bytes into utf-8")}return Le(e.shape,e.dtype,r)}makeOutput(e,t,r){let a=this.write(e,t,r);return kr().makeTensorFromDataId(a,t,r,this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;let{complexTensorInfos:r}=this.data.get(e);r!=null&&(this.disposeData(r.real.dataId,!0),this.disposeData(r.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){let t=w.now();return e(),{kernelMs:w.now()-t}}memory(){return{unreliable:!0,reasons:["The reported memory is an upper bound. Due to automatic garbage collection, the true allocated memory may be less."]}}where(e){Ne([e],"where");let t=this.readSync(e.dataId);return fH(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}},fx=r6;fx.nextDataId=0;var Km={};De(Km,{addImpl:()=>n6,bincountImpl:()=>gx,bincountReduceImpl:()=>s6,ceilImpl:()=>i6,concatImpl:()=>yx,equalImpl:()=>o6,expImpl:()=>u6,expm1Impl:()=>p6,floorImpl:()=>h6,gatherNdImpl:()=>c6,gatherV2Impl:()=>f6,greaterEqualImpl:()=>g6,greaterImpl:()=>m6,lessEqualImpl:()=>A6,lessImpl:()=>y6,linSpaceImpl:()=>x6,logImpl:()=>b6,maxImpl:()=>v6,maximumImpl:()=>w6,minimumImpl:()=>k6,multiplyImpl:()=>Ax,negImpl:()=>I6,notEqualImpl:()=>S6,prodImpl:()=>T6,rangeImpl:()=>bx,rsqrtImpl:()=>C6,sigmoidImpl:()=>rq,simpleAbsImpl:()=>a6,sliceImpl:()=>mf,sparseFillEmptyRowsImpl:()=>E6,sparseReshapeImpl:()=>R6,sparseSegmentReductionImpl:()=>vx,sqrtImpl:()=>sq,squaredDifferenceImpl:()=>F6,stridedSliceImpl:()=>M6,stringNGramsImpl:()=>$6,stringSplitImpl:()=>P6,stringToHashBucketFastImpl:()=>O6,subImpl:()=>z6,tileImpl:()=>D6,topKImpl:()=>L6,transposeImpl:()=>xx,uniqueImpl:()=>B6});function a6(e){let t=new Float32Array(e.length);for(let r=0;r<e.length;++r)t[r]=Math.abs(e[r]);return t}var mH=e=>{let{x:t}=e.inputs,r=e.backend;Ne(t,"abs");let a=new Float32Array(w.sizeFromShape(t.shape)),n=r.data.get(t.dataId).values;return a=a6(n),r.makeOutput(a,t.shape,t.dtype)},gH={kernelName:Fo,backendName:"cpu",kernelFunc:mH};function Zt(e){return(t,r,a,n,s)=>{let i=N.assertAndGetBroadcastShape(t,r),o=i.length,l=w.computeStrides(i),d=w.sizeFromShape(i),u=w.getTypedArrayFromDType(s,d),p=t.length,h=r.length,c=w.computeStrides(t),f=w.computeStrides(r),m=N.getBroadcastDims(t,i),g=N.getBroadcastDims(r,i);if(m.length+g.length===0)for(let y=0;y<u.length;++y)u[y]=e(a[y%a.length],n[y%n.length]);else for(let y=0;y<u.length;++y){let A=w.indexToLoc(y,o,l),x=A.slice(-p);m.forEach(T=>x[T]=0);let b=w.locToIndex(x,p,c),v=A.slice(-h);g.forEach(T=>v[T]=0);let C=w.locToIndex(v,h,f);u[y]=e(a[b],n[C])}return[u,i]}}function ua(e){let{inputs:t,backend:r}=e,{real:a,imag:n}=t,s=r.data.get(a.dataId).values,i=r.data.get(n.dataId).values,o=r.makeTensorInfo(a.shape,"complex64"),l=r.data.get(o.dataId);return l.complexTensorInfos={real:r.makeTensorInfo(a.shape,"float32",s),imag:r.makeTensorInfo(n.shape,"float32",i)},o}var yH={kernelName:Lp,backendName:"cpu",kernelFunc:ua};function ff(e,t,r="float32"){if(r==="complex64"){let n=ff(e,t,"float32"),s=ff(e,t,"float32");return ua({inputs:{real:n,imag:s},backend:e})}let a=w.makeZerosTypedArray(w.sizeFromShape(t),r);return e.makeTensorInfo(t,r,a)}function En(e){let{inputs:t,backend:r}=e,{x:a}=t;return r.incRef(a.dataId),{dataId:a.dataId,shape:a.shape,dtype:a.dtype}}var AH={kernelName:ui,backendName:"cpu",kernelFunc:En};function Io(e){let{inputs:t,backend:r}=e,{input:a}=t,n=r.data.get(a.dataId).complexTensorInfos.real,s=r.data.get(n.dataId).values;return r.makeTensorInfo(n.shape,n.dtype,s)}var xH={kernelName:Kp,backendName:"cpu",kernelFunc:Io};function Us(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{dtype:s}=a;if(s==="complex64"){if(n.dtype==="complex64")return En({inputs:{x:n},backend:r});let i=ff(r,n.shape,n.dtype),o=Us({inputs:{x:n},backend:r,attrs:{dtype:"float32"}}),l=ua({inputs:{real:o,imag:i},backend:r});return r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(o),l}if(n.dtype==="complex64"){let i=Io({inputs:{input:n},backend:r}),o=Us({inputs:{x:i},backend:r,attrs:{dtype:s}});return r.disposeIntermediateTensorInfo(i),o}if(!w.hasEncodingLoss(n.dtype,s)){let i=En({inputs:{x:n},backend:r});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(s==="int32"){let i=r.data.get(n.dataId).values,o=Int32Array.from(i);return r.makeTensorInfo(n.shape,"int32",o)}if(s==="bool"){let i=r.data.get(n.dataId).values,o=w.toTypedArray([0],n.dtype),[l,d]=Zt((u,p)=>u!==p?1:0)(n.shape,[],i,o,"bool");return r.makeTensorInfo(d,"bool",l)}throw new Error(`Error in Cast: failed to cast ${n.dtype} to ${s}`)}var bH={kernelName:Xs,backendName:"cpu",kernelFunc:Us};function mr(e,t,r,a){return r==null?({inputs:n,backend:s})=>{let{a:i,b:o}=n,l=s;Ne([i,o],e);let d=l.data.get(i.dataId).values,u=l.data.get(o.dataId).values,p=i.dtype==="string"?N.fromUint8ToStringArray(d):d,h=i.dtype==="string"?N.fromUint8ToStringArray(u):u,c=a||i.dtype,[f,m]=t(i.shape,o.shape,p,h,c);return l.makeTensorInfo(m,c,f)}:({inputs:n,backend:s})=>{let{a:i,b:o}=n,l=s;if(i.dtype==="complex64"||o.dtype==="complex64"){let d=Us({inputs:{x:i},backend:l,attrs:{dtype:"complex64"}}),u=l.data.get(d.dataId),p=u.complexTensorInfos.real,h=u.complexTensorInfos.imag,c=l.data.get(p.dataId).values,f=l.data.get(h.dataId).values,m=Us({inputs:{x:o},backend:l,attrs:{dtype:"complex64"}}),g=l.data.get(m.dataId),y=g.complexTensorInfos.real,A=g.complexTensorInfos.imag,x=l.data.get(y.dataId).values,b=l.data.get(A.dataId).values,[v,C,T]=r(i.shape,o.shape,c,f,x,b),E=l.makeTensorInfo(T,"float32",v),R=l.makeTensorInfo(T,"float32",C),z=ua({inputs:{real:E,imag:R},backend:l});return l.disposeIntermediateTensorInfo(d),l.disposeIntermediateTensorInfo(m),l.disposeIntermediateTensorInfo(E),l.disposeIntermediateTensorInfo(R),z}else{let d=l.data.get(i.dataId).values,u=l.data.get(o.dataId).values,p=a||i.dtype,[h,c]=t(i.shape,o.shape,d,u,p);return l.makeTensorInfo(c,p,h)}}}function mx(e){return(t,r,a,n,s,i)=>{let o=N.assertAndGetBroadcastShape(t,r),l=w.sizeFromShape(o),d=o.length,u=w.computeStrides(o),p=w.getTypedArrayFromDType("float32",l),h=w.getTypedArrayFromDType("float32",l),c=N.getBroadcastDims(t,o),f=N.getBroadcastDims(r,o),m=N.mergeRealAndImagArrays(a,n),g=N.mergeRealAndImagArrays(s,i),y=t.length,A=w.computeStrides(t),x=r.length,b=w.computeStrides(r);if(c.length+f.length===0)for(let v=0;v<p.length;v++){let C=v%m.length,T=v%g.length,E=e(m[C*2],m[C*2+1],g[T*2],g[T*2+1]);p[v]=E.real,h[v]=E.imag}else for(let v=0;v<p.length;v++){let C=w.indexToLoc(v,d,u),T=C.slice(-y);c.forEach(I=>T[I]=0);let E=w.locToIndex(T,y,A),R=C.slice(-x);f.forEach(I=>R[I]=0);let z=w.locToIndex(R,x,b),M=e(m[E*2],m[E*2+1],g[z*2],g[z*2+1]);p[v]=M.real,h[v]=M.imag}return[p,h,o]}}var n6=Zt((e,t)=>e+t),vH=mx((e,t,r,a)=>({real:e+r,imag:t+a})),Ih=mr(qn,n6,vH),wH={kernelName:qn,backendName:"cpu",kernelFunc:Ih};function gx(e,t,r,a,n){let s=w.sizeFromShape(a),i=w.makeZerosTypedArray(n,r);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>=n||(s>0?i[l]+=t[o]:i[l]+=1)}return i}function s6(e,t,r,a=!1){let n=e.shape[0],s=e.shape[1],i=Le([n,r],t.dtype);for(let o=0;o<n;o++)for(let l=0;l<s;l++){let d=e.get(o,l);if(d<0)throw new Error("Input x must be non-negative!");d>=r||(a?i.set(1,o,d):t.size>0?i.set(i.get(o,d)+t.get(o,l),o,d):i.set(i.get(o,d)+1,o,d))}return i}function Li(e){return(t,r,a)=>{let n=w.getTypedArrayFromDType(r,t.length);for(let s=0;s<t.length;++s)n[s]=e(t[s],a);return n}}function gt(e,t,r){return({inputs:a,attrs:n,backend:s})=>{let{x:i}=a;if(Ne(i,e),i.dtype==="string"||r==="string")throw new Error("unaryKernelFunc does not support string input/output");let o=s,l=o.data.get(i.dataId).values,d=w.sizeFromShape(i.shape),u=r||i.dtype,p=w.getArrayFromDType(u,d);for(let h=0;h<d;++h)p[h]=t(l[h],n);return o.makeTensorInfo(i.shape,u,p)}}function dd(e,t,r){return({inputs:a,attrs:n,backend:s})=>{let{x:i}=a;if(Ne(i,e),i.dtype==="string"||r==="string")throw new Error("unaryKernelFunc does not support string input/output");let o=s,l=o.data.get(i.dataId).values,d=r||i.dtype,u=t(l,d,n);return o.makeTensorInfo(i.shape,d,u)}}var i6=Li(e=>Math.ceil(e)),kH=dd(Zs,i6),IH={kernelName:Zs,backendName:"cpu",kernelFunc:kH};function yx(e,t,r,a){let n=w.getArrayFromDType(r,w.sizeFromShape(t));if(a&&r!=="string"){let s=0;e.forEach(i=>{let o=w.sizeFromShape(i.shape);n.set(i.vals,s),s+=o})}else{let s=0;e.forEach(i=>{let o=r==="string"?N.fromUint8ToStringArray(i.vals):i.vals,l=0;for(let d=0;d<i.shape[0];++d){let u=d*t[1]+s;for(let p=0;p<i.shape[1];++p)n[u+p]=o[l++]}s+=i.shape[1]})}return n}var o6=Zt((e,t)=>e===t?1:0),l6=mr(Do,o6,null,"bool"),SH={kernelName:Do,backendName:"cpu",kernelFunc:l6},u6=Li(e=>Math.exp(e)),d6=dd(ni,u6,"float32"),TH={kernelName:ni,backendName:"cpu",kernelFunc:d6},p6=Li(e=>Math.expm1(e)),CH=dd(Lo,p6),NH={kernelName:Lo,backendName:"cpu",kernelFunc:CH},h6=Li(e=>Math.floor(e)),EH=dd(si,h6),RH={kernelName:si,backendName:"cpu",kernelFunc:EH};function c6(e,t,r,a,n,s,i,o,l){let d=Le([a,s],r);for(let u=0;u<a;u++){let p=[],h=0;for(let c=0;c<n;c++){let f=e[u*n+c];h+=f*i[c],p.push(f)}if(h<0||h>=l/s)throw new Error(`Invalid indices: ${p} does not index into ${o}`);for(let c=0;c<s;c++)d.values[u*s+c]=t.get(...t.indexToLoc(h*s+c))}return d}function f6(e,t,r){let a=Le(r,e.dtype);for(let n=0;n<a.size;++n){let s=a.indexToLoc(n).slice(),i=s[0],o=s[2],l=t.locToIndex([i,o]);s[2]=t.values[l];let d=e.locToIndex(s);0<=d&&d<e.values.length&&(a.values[n]=e.values[d])}return a}var m6=Zt((e,t)=>e>t?1:0),FH=mr(Uo,m6,null,"bool"),MH={kernelName:Uo,backendName:"cpu",kernelFunc:FH},g6=Zt((e,t)=>e>=t?1:0),$H=mr(li,g6,null,"bool"),PH={kernelName:li,backendName:"cpu",kernelFunc:$H},y6=Zt((e,t)=>e<t?1:0),OH=mr(Go,y6,null,"bool"),zH={kernelName:Go,backendName:"cpu",kernelFunc:OH},A6=Zt((e,t)=>e<=t?1:0),DH=mr(jo,A6,null,"bool"),_H={kernelName:jo,backendName:"cpu",kernelFunc:DH};function x6(e,t,r){let a=(t-e)/(r-1),n=w.makeZerosTypedArray(r,"float32");n[0]=e;for(let s=1;s<n.length;s++)n[s]=n[s-1]+a;return n}var b6=Li(e=>Math.log(e)),LH=dd(pi,b6),BH={kernelName:pi,backendName:"cpu",kernelFunc:LH};function v6(e,t,r,a){let n=w.getTypedArrayFromDType(a,w.sizeFromShape(r));for(let s=0;s<n.length;++s){let i=s*t,o=e[i];for(let l=0;l<t;++l){let d=e[i+l];(Number.isNaN(d)||d>o)&&(o=d)}n[s]=o}return n}var w6=Zt((e,t)=>Math.max(e,t)),WH=mr(ci,w6),VH={kernelName:ci,backendName:"cpu",kernelFunc:WH},k6=Zt((e,t)=>Math.min(e,t)),UH=mr(yi,k6),GH={kernelName:yi,backendName:"cpu",kernelFunc:UH},Ax=Zt((e,t)=>e*t),jH=mx((e,t,r,a)=>({real:e*r-t*a,imag:e*a+t*r})),Xm=mr(xi,Ax,jH),HH={kernelName:xi,backendName:"cpu",kernelFunc:Xm};function I6(e,t,r){let a=w.createScalarValue(-1,r);return Ax([],t,a,e,r)}function qH(e){let{inputs:t,backend:r}=e,{x:a}=t;Ne(a,"neg");let n=r.data.get(a.dataId).values,[s,i]=I6(n,a.shape,a.dtype);return r.makeTensorInfo(i,a.dtype,s)}var KH={kernelName:qo,backendName:"cpu",kernelFunc:qH},S6=Zt((e,t)=>e!==t?1:0),XH=mr(Ko,S6,null,"bool"),ZH={kernelName:Ko,backendName:"cpu",kernelFunc:XH};function xx(e,t,r,a,n){let s=t.length,i=w.sizeFromShape(t),o=w.computeStrides(t),l=w.computeStrides(n),d=w.getTypedArrayFromDType(r,w.sizeFromShape(n));for(let u=0;u<i;++u){let p=w.indexToLoc(u,s,o),h=new Array(p.length);for(let f=0;f<h.length;f++)h[f]=p[a[f]];let c=w.locToIndex(h,s,l);d[c]=e[u]}return d}function Ma(e){let{inputs:t,attrs:r,backend:a}=e,{x:n}=t,{perm:s}=r;Ne(n,"transpose");let i=n.shape.length,o=new Array(i);for(let u=0;u<o.length;u++)o[u]=n.shape[s[u]];let l=a.data.get(n.dataId).values,d=xx(l,n.shape,n.dtype,s,o);return{dataId:a.write(d,o,n.dtype),shape:o,dtype:n.dtype}}var YH={kernelName:Oi,backendName:"cpu",kernelFunc:Ma};function T6(e,t,r,a){let[n,s]=N.computeOutAndReduceShapes(e,a),i=Or(t,"int32"),o=w.makeZerosTypedArray(w.sizeFromShape(n),i),l=w.sizeFromShape(s);for(let d=0;d<o.length;++d){let u=d*l,p=1;for(let h=0;h<l;++h)p*=r[u+h];o[d]=p}return{outVals:o,outShape:n,outDtype:i}}function JH(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{axis:s,keepDims:i}=a;Ne(n,"prod");let o=n.shape.length,l=w.parseAxisParam(s,n.shape),d=N.getAxesPermutation(l,o),u=l,p=n,h=[];d!=null&&(p=Ma({inputs:{x:n},backend:r,attrs:{perm:d}}),h.push(p),u=N.getInnerMostAxes(u.length,o));let c=r.data.get(p.dataId).values,{outVals:f,outShape:m,outDtype:g}=T6(p.shape,p.dtype,c,u),y=m;return i&&(y=N.expandShapeToKeepDim(m,l)),h.forEach(A=>r.disposeIntermediateTensorInfo(A)),r.makeTensorInfo(y,g,f)}var QH={kernelName:el,backendName:"cpu",kernelFunc:JH};function bx(e,t,r,a){let n=e===t,s=e<t&&r<0,i=t<e&&r>1;if(n||s||i)return w.makeZerosTypedArray(0,a);let o=Math.abs(Math.ceil((t-e)/r)),l=w.makeZerosTypedArray(o,a);t<e&&r===1&&(r=-1),l[0]=e;for(let d=1;d<l.length;d++)l[d]=l[d-1]+r;return l}var C6=Li(e=>1/Math.sqrt(e)),eq=dd(Ti,C6),tq={kernelName:Ti,backendName:"cpu",kernelFunc:eq},rq=Li(e=>1/(1+Math.exp(-e))),N6=gt(Ni,e=>1/(1+Math.exp(-e))),aq={kernelName:Ni,backendName:"cpu",kernelFunc:N6};function mf(e,t,r,a,n){let s=Ot.isSliceContinous(a,t,r),i=w.sizeFromShape(r),o=w.computeStrides(a);if(s){let p=Ot.computeFlatOffset(t,o);return n==="string"?e.slice(p,p+i):e.subarray(p,p+i)}let l=n==="string"?N.fromUint8ToStringArray(e):e,d=Le(a,n,l),u=Le(r,n);for(let p=0;p<u.size;++p){let h=u.indexToLoc(p),c=h.map((f,m)=>f+t[m]);u.set(d.get(...c),...h)}return n==="string"?N.fromStringArrayToUint8(u.values):u.values}function So(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{begin:s,size:i}=a;Ne(n,"slice");let[o,l]=Ot.parseSliceParams(n,s,i);Ot.assertParamsValid(n,o,l);let d=r.data.get(n.dataId).values,u=mf(d,o,l,n.shape,n.dtype);return r.makeTensorInfo(l,n.dtype,u)}var nq={kernelName:il,backendName:"cpu",kernelFunc:So};function E6(e,t,r,a,n,s,i){let o=t[0],l=s[0],d=new Array(l),u=new Array(o),p=t[1];if(l===0){if(o!==0)throw new Error(N.getSparseFillEmptyRowsIndicesDenseShapeMismatch(o));let g=w.getArrayFromDType(r,0),y=w.getArrayFromDType(n,0);return[g,[0,p],y,d,u]}let h=!0,c=0,f=new Array(l).fill(0);for(let g=0;g<o;++g){let y=e[g*p];if(y<0)throw new Error(N.getSparseFillEmptyRowsNegativeIndexErrorMessage(g,y));if(y>=l)throw new Error(N.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(g,y,l));++f[y],h=h&&y>=c,c=y}let m=!0;for(let g=0;g<l;++g){let y=f[g]===0;d[g]=y,m=m&&!y,f[g]=Math.max(f[g],1),g>0&&(f[g]+=f[g-1])}if(m&&h){let g=e,y=a;for(let A=0;A<o;++A)u[A]=A;return[g,[o,p],y,d,u]}else{let g=f[l-1],y=w.getArrayFromDType(r,g*p),A=w.getArrayFromDType(n,g),x=new Array(l).fill(0);for(let b=0;b<o;++b){let v=e[b*p],C=x[v],T=(v===0?0:f[v-1])+C;x[v]++;for(let E=0;E<p;++E)y[T*p+E]=e[b*p+E];A[T]=a[b],u[b]=T}for(let b=0;b<l;++b)if(x[b]===0){let v=b===0?0:f[b-1];y[v*p+0]=b;for(let C=1;C<p;++C)y[v*p+C]=0;A[v]=i}return[y,[g,p],A,d,u]}}function R6(e,t,r,a,n){let s=w.sizeFromShape(a),i=t[0],o=n.length,l=[],d=1,u=-1;for(let m=0;m<o;++m){let g=n[m];if(g===-1){if(u!==-1)throw new Error(N.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(u,m));u=m,l.push(1)}else{if(g<0)throw new Error(N.getSparseReshapeNegativeOutputDimErrorMessage(m,g));d*=g,l.push(g)}}if(u!==-1){if(d<=0)throw new Error(N.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage());let m=Math.trunc(s/d);if(d*m!==s)throw new Error(N.getSparseReshapeInputOutputMultipleErrorMessage(a,l));l[u]=m}if(w.sizeFromShape(l)!==s)throw new Error(N.getSparseReshapeInputOutputMismatchErrorMessage(a,l));let p=a.length,h=[];if(p>0){h[p-1]=1;for(let m=p-2;m>=0;--m)h[m]=h[m+1]*a[m+1]}let c=[];if(o>0){c[o-1]=1;for(let m=o-2;m>=0;--m)c[m]=c[m+1]*l[m+1]}let f=w.getArrayFromDType(r,i*o);for(let m=0;m<i;++m){let g=0;for(let y=0;y<p;++y)g+=e[m*p+y]*h[y];for(let y=0;y<o;++y)f[m*o+y]=Math.trunc(g/c[y]),g%=c[y]}return[f,[i,o],l]}function vx(e,t,r,a,n,s=!1,i=0){let o=a.length,l=[t[0],e.length/t[0]],d=l[1],u=o>0?n[o-1]+1:0;if(u<0)throw new Error(N.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let p=t.slice();p[0]=u;let h=p.reduce((A,x)=>A*x,1),c=w.getArrayFromDType(r,h);if(o===0)return u>0&&c.fill(i),[c,p];if(u<=0)throw new Error(N.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let f=0,m=1,g=0,y=n[f];for(;;){let A=0;if(m<o){if(A=n[m],y===A){++m;continue}if(y>=A)throw new Error(N.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage())}if(y<0||y>=u)throw new Error(N.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(y,u));y>g&&c.fill(i,g*d,y*d);for(let x=f;x<m;++x){let b=a[x];if(b<0||b>=l[0])throw new Error(N.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(x,a[x],l[0]));for(let v=0;v<d;v++)c[y*d+v]+=e[b*d+v]}if(s)for(let x=0;x<d;x++)c[y*d+x]/=m-f;if(f=m,++m,g=y+1,y=A,m>o)break}return g<u&&c.fill(i,g*d,u*d),[c,p]}var sq=Li(e=>Math.sqrt(e)),iq=gt(Ei,e=>Math.sqrt(e)),oq={kernelName:Ei,backendName:"cpu",kernelFunc:iq},F6=Zt((e,t)=>{let r=e-t;return r*r}),lq=mr(Mi,F6),uq={kernelName:Mi,backendName:"cpu",kernelFunc:lq};function M6(e,t,r,a){let n=Le(e,t.dtype);for(let s=0;s<n.size;s++){let i=n.indexToLoc(s),o=new Array(i.length);for(let l=0;l<o.length;l++)o[l]=i[l]*r[l]+a[l];n.set(t.get(...o),...i)}return n}var dq=class{constructor(e,t,r,a,n,s){this.separator=w.encodeString(e),this.nGramWidths=t,this.leftPad=w.encodeString(r),this.rightPad=w.encodeString(a),this.padWidth=n,this.preserveShort=s}getPadWidth(e){return Math.min(this.padWidth<0?e-1:this.padWidth,e-1)}getNumNGrams(e,t){let r=this.getPadWidth(t);return Math.max(0,e+2*r-t+1)}createNGrams(e,t,r,a,n,s){for(let i=0;i<n;++i){let o=this.getPadWidth(s),l=Math.max(0,o-i),d=Math.max(0,o-(n-(i+1))),u=s-(l+d),p=t+(l>0?0:i-o),h=0;h+=l*this.leftPad.length;for(let g=0;g<u;++g)h+=e[p+g].length;h+=d*this.rightPad.length,h+=(l+d+u-1)*this.separator.length,r[a+i]=new Uint8Array(h);let c=r[a+i],f=0,m=g=>g.forEach(y=>c[f++]=y);for(let g=0;g<l;++g)m(this.leftPad),m(this.separator);for(let g=0;g<u-1;++g)m(e[p+g]),m(this.separator);if(u>0){m(e[p+u-1]);for(let g=0;g<d;++g)m(this.separator),m(this.rightPad)}else{for(let g=0;g<d-1;++g)m(this.rightPad),m(this.separator);m(this.rightPad)}}}compute(e,t){let r=e.length,a=t.length;if(a>0){let o=t[0];if(o!==0)throw new Error(`First split value must be 0, got ${o}`);for(let l=1;l<a;++l){let d=t[l]>=o;if(d=d&&t[l]<=r,!d)throw new Error(`Invalid split value ${t[l]}, must be in [${o}, ${r}]`);o=t[l]}if(o!==r)throw new Error(`Last split value must be data size. Expected ${r}, got ${o}`)}let n=a-1,s=w.getArrayFromDType("int32",a);if(r===0||a===0){let o=new Array(r);for(let l=0;l<=n;++l)s[l]=0;return[o,s]}s[0]=0;for(let o=1;o<=n;++o){let l=t[o]-t[o-1],d=0;this.nGramWidths.forEach(u=>{d+=this.getNumNGrams(l,u)}),this.preserveShort&&l>0&&d===0&&(d=1),s[o]=s[o-1]+d}let i=new Array(s[n]);for(let o=0;o<n;++o){let l=t[o],d=s[o];if(this.nGramWidths.forEach(u=>{let p=t[o+1]-t[o],h=this.getNumNGrams(p,u);this.createNGrams(e,l,i,d,h,u),d+=h}),this.preserveShort&&d===s[o]){let u=t[o+1]-t[o];if(u===0)continue;let p=u+2*this.padWidth,h=1;this.createNGrams(e,l,i,d,h,p)}}return[i,s]}};function $6(e,t,r,a,n,s,i,o){return new dq(r,a,n,s,i,o).compute(e,t)}function pq(e,t,r,a){if(!e.length)return;if(t.length===0){for(let s=0;s<e.length;++s)a.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);(!r||o.length!==0)&&a.push(o),e=e.subarray(i+1),i=e.indexOf(s)}(!r||e.length!==0)&&a.push(e);return}let n=0;for(let s=0;s<e.length+1;s++)if(s===e.length||t.indexOf(e[s])!==-1){let i=e.subarray(n,s);(!r||i.length!==0)&&a.push(i),n=s+1}}function P6(e,t,r){let a=e.length,n=[],s=0,i=0,o=new Array(a);for(let h=0;h<a;++h){let c=n.length;pq(e[h],t,r,n);let f=n.length-c;o[h]=f,s+=f,i=Math.max(i,f)}let l=w.getArrayFromDType("int32",s*2),d=new Array(s),u=[a,i],p=0;for(let h=0;h<a;++h)for(let c=0;c<o[h];++c)l[p*2]=h,l[p*2+1]=c,d[p]=n[p],++p;return[l,d,u]}function O6(e,t){let r=w.getArrayFromDType("int32",e.length);for(let a=0;a<e.length;++a)r[a]=w.fingerPrint64(e[a]).modulo(t).getLowBitsUnsigned();return r}var z6=Zt((e,t)=>e-t),hq=mx((e,t,r,a)=>({real:e-r,imag:t-a})),wx=mr($i,z6,hq),cq={kernelName:$i,backendName:"cpu",kernelFunc:wx};function D6(e,t){let r=new Array(e.rank);for(let n=0;n<r.length;n++)r[n]=e.shape[n]*t[n];let a=Le(r,e.dtype);for(let n=0;n<a.values.length;++n){let s=a.indexToLoc(n),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);a.values[n]=e.values[o]}return a}var hp=(e,t)=>{let r=t.value-e.value;return r===0?e.index-t.index:r};function _6(e,t,r=0,a=e.length-1){for(;a>r;){if(a-r>600){let o=a-r+1,l=t-r+1,d=Math.log(o),u=.5*Math.exp(2*d/3),p=.5*Math.sqrt(d*u*(o-u)/o)*Math.sign(l-o/2),h=Math.max(r,Math.floor(t-l*u/o+p)),c=Math.min(a,Math.floor(t+(o-l)*u/o+p));_6(e,t,h,c)}let n=e[t],s=r,i=a;for(w.swap(e,r,t),hp(e[a],n)>0&&w.swap(e,r,a);s<i;){for(w.swap(e,s,i),s++,i--;hp(e[s],n)<0;)s=s+1;for(;hp(e[i],n)>0;)i=i-1}hp(e[r],n)===0?w.swap(e,r,i):(i=i+1,w.swap(e,i,a)),i<=t&&(r=i+1),t<=i&&(a=i-1)}}function L6(e,t,r,a,n){let s=t[t.length-1],[i,o]=[e.length/s,s],l=w.getTypedArrayFromDType(r,i*a),d=w.getTypedArrayFromDType("int32",i*a);for(let p=0;p<i;p++){let h=p*o,c=e.subarray(h,h+o),f=new Array(c.length);c.forEach((A,x)=>f[x]={value:A,index:x}),a<f.length&&(_6(f,a),f=f.slice(0,a)),n&&f.sort(hp);let m=p*a,g=l.subarray(m,m+a),y=d.subarray(m,m+a);for(let A=0;A<a;A++)g[A]=f[A].value,y[A]=f[A].index}let u=t.slice();return u[u.length-1]=a,[Le(u,r,l),Le(u,"int32",d)]}function B6(e,t,r,a){let n=w.parseAxisParam(t,r)[0],s=[1,r[0],1];for(let f=0;f<n;f++)s[0]*=r[f];s[1]=r[n];for(let f=n+1;f<r.length;f++)s[2]*=r[f];let i={},o=new Int32Array(r[n]),l=new tr(s,a,e),d=[],u=s[0]===1&&s[2]===1;for(let f=0;f<r[n];f++){let m;if(u)m=e[f].toString();else{let g=[];for(let y=0;y<s[0];y++)for(let A=0;A<s[2];A++)g.push(l.get(y,f,A));m=g.join(",")}if(i[m]!==void 0)o[f]=i[m];else{let g=Object.keys(i).length;i[m]=g,o[f]=g,d.push(f)}}let p=s.slice();p[1]=Object.keys(i).length;let h=new tr(p,a);d.forEach((f,m)=>{for(let g=0;g<s[0];g++)for(let y=0;y<s[2];y++)h.set(l.get(g,f,y),g,m,y)});let c=r.slice();return c[n]=p[1],{outputValues:h.values,outputShape:c,indices:o}}var fq="0.0.0";Al("cpu",()=>new fx,1);var W6=gt(ai,e=>e>=0?e:Math.exp(e)-1),mq={kernelName:ai,backendName:"cpu",kernelFunc:W6};function V6(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{alpha:s}=a;Ne([n],"leakyRelu");let i=w.sizeFromShape(n.shape),o=r.data.get(n.dataId).values,l=w.getTypedArrayFromDType("float32",i);for(let d=0;d<o.length;d++)l[d]=o[d]<0?s*o[d]:o[d];return r.makeTensorInfo(n.shape,"float32",l)}var gq={kernelName:di,backendName:"cpu",kernelFunc:V6},yq=Zt((e,t)=>e<0?t*e:e);function U6(e){let{inputs:t,backend:r}=e,{x:a,alpha:n}=t;Ne([a,n],"prelu");let s=r.data.get(a.dataId).values,i=r.data.get(n.dataId).values,[o,l]=yq(a.shape,n.shape,s,i,"float32");return r.makeTensorInfo(l,"float32",o)}var Aq={kernelName:wi,backendName:"cpu",kernelFunc:U6},G6=gt(ki,e=>Math.max(0,e)),xq={kernelName:ki,backendName:"cpu",kernelFunc:G6},j6=gt(Si,e=>Math.min(Math.max(0,e),6)),bq={kernelName:Si,backendName:"cpu",kernelFunc:j6};function kx(e,t,r,a,n){if(r==="linear")return En({inputs:{x:t},backend:e});if(r==="relu")return G6({inputs:{x:t},backend:e});if(r==="elu")return W6({inputs:{x:t},backend:e});if(r==="relu6")return j6({inputs:{x:t},backend:e});if(r==="prelu")return U6({inputs:{x:t,alpha:a},backend:e});if(r==="leakyrelu")return V6({inputs:{x:t},backend:e,attrs:{alpha:n}});if(r==="sigmoid")return N6({inputs:{x:t},backend:e});throw new Error(`Activation ${r} has not been implemented for the CPU backend.`)}function $t(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{shape:s}=a,i=w.sizeFromShape(n.shape),o=w.inferFromImplicitShape(s,i),l=w.sizeFromShape(o);w.assert(i===l,()=>`The new shape (${o}) has ${l} elements and the old shape (${n.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`),r.incRef(n.dataId);let d=r.data.get(n.dataId);if(d.complexTensorInfos!=null){let u=d.complexTensorInfos.real,p=d.complexTensorInfos.imag;u.shape=o,p.shape=o}return{dataId:n.dataId,shape:o,dtype:n.dtype}}var vq={kernelName:tl,backendName:"cpu",kernelFunc:$t};function H6(e){let{inputs:t,backend:r,attrs:a}=e,{a:n,b:s}=t,{transposeA:i,transposeB:o}=a;Ne([n,s],"matMul");let l=n.shape.length,d=s.shape.length,u=i?n.shape[l-2]:n.shape[l-1],p=o?s.shape[d-1]:s.shape[d-2],h=i?n.shape[l-1]:n.shape[l-2],c=o?s.shape[d-2]:s.shape[d-1],f=n.shape.slice(0,-2),m=s.shape.slice(0,-2),g=w.sizeFromShape(f),y=w.sizeFromShape(m),A=yl.assertAndGetBroadcastShape(n.shape.slice(0,-2),s.shape.slice(0,-2)).concat([h,c]);w.assert(u===p,()=>`Error in matMul: inner shapes (${u}) and (${p}) of Tensors with shapes ${n.shape} and ${s.shape} and transposeA=${i} and transposeB=${o} must match.`);let x=i?[g,u,h]:[g,h,u],b=o?[y,c,p]:[y,p,c],v=$t({inputs:{x:n},backend:r,attrs:{shape:x}}),C=$t({inputs:{x:s},backend:r,attrs:{shape:b}}),T=i?v.shape[1]:v.shape[2],E=i?v.shape[2]:v.shape[1],R=o?C.shape[1]:C.shape[2],z=Math.max(g,y),M=r.data.get(v.dataId).values,I=r.data.get(C.dataId).values,D=w.computeStrides(v.shape),O=w.computeStrides(C.shape),[j,X,_]=i?[D[0],1,D[1]]:[D[0],D[1],1],[K,W,ee]=o?[1,O[1],O[0]]:[O[1],1,O[0]],Q=E*R,ne=Le([z,E,R],v.dtype),Z=ne.values,ae=r.blockSize;for(let ie=0;ie<z;ie++)for(let xe=0;xe<E;xe+=ae)for(let be=0;be<R;be+=ae)for(let Te=0;Te<T;Te+=ae){let Re=Math.min(xe+ae,E),$e=Math.min(be+ae,R),_e=Math.min(Te+ae,T);for(let qe=xe;qe<Re;qe++)for(let Ze=be;Ze<$e;Ze++){let st=0;for(let ht=Te;ht<_e;ht++){let ct=Math.min(ie,g-1)*j,yt=Math.min(ie,y-1)*ee,Et=M[ct+qe*X+ht*_],Hr=I[ht*K+Ze*W+yt];st+=Et*Hr}Z[ie*Q+(qe*R+Ze)]+=st}}return r.disposeIntermediateTensorInfo(v),r.disposeIntermediateTensorInfo(C),r.makeTensorInfo(A,ne.dtype,ne.values)}var wq={kernelName:Ks,backendName:"cpu",kernelFunc:H6};function kq(e){let{inputs:t,backend:r,attrs:a}=e,{a:n,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:d,activation:u,leakyreluAlpha:p}=a,h,c,f,m=[];h=H6({inputs:{a:n,b:s},attrs:{transposeA:l,transposeB:d},backend:r}),i&&(c=Ih({inputs:{a:h,b:i},backend:r}),m.push(h),h=c),u&&(f=kx(r,h,u,o,p),m.push(h),h=f);for(let g of m)r.disposeIntermediateTensorInfo(g);return h}var Iq={kernelName:Rs,backendName:"cpu",kernelFunc:kq},Sq=gt(Tu,e=>Math.acos(e)),Tq={kernelName:Tu,backendName:"cpu",kernelFunc:Sq},Cq=gt(Cu,e=>Math.acosh(e)),Nq={kernelName:Cu,backendName:"cpu",kernelFunc:Cq};function Eq(e){let{inputs:t,backend:r}=e,a=t;Ne(t,"addN");let n=a.map(o=>r.data.get(o.dataId).values),s=Le(a[0].shape,a[0].dtype),i=s.values;for(let o=0;o<a.length;o++){let l=n[o];for(let d=0;d<i.length;d++)i[d]+=l[d]}return r.makeTensorInfo(s.shape,s.dtype,s.values)}var Rq={kernelName:js,backendName:"cpu",kernelFunc:Eq};function Fq(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{axis:s,keepDims:i}=a;Ne(n,"all");let o=w.parseAxisParam(s,n.shape),l=o,d=N.getAxesPermutation(l,n.shape.length),u=n;d!=null&&(u=Ma({inputs:{x:n},backend:r,attrs:{perm:d}}),l=N.getInnerMostAxes(l.length,n.shape.length)),N.assertAxesAreInnerMostDims("all",l,u.shape.length);let[p,h]=N.computeOutAndReduceShapes(u.shape,l),c=w.sizeFromShape(h),f=w.makeZerosTypedArray(w.sizeFromShape(p),u.dtype),m=r.data.get(u.dataId).values;for(let y=0;y<f.length;++y){let A=y*c,x=m[A];for(let b=0;b<c;++b){let v=m[A+b];x=x&&v}f[y]=x}d!=null&&r.disposeIntermediateTensorInfo(u);let g=r.makeTensorInfo(p,u.dtype,f);if(i){let y=N.expandShapeToKeepDim(p,o),A=$t({inputs:{x:g},backend:r,attrs:{shape:y}});return r.disposeIntermediateTensorInfo(g),A}return g}var Mq={kernelName:Nu,backendName:"cpu",kernelFunc:Fq};function $q(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{axis:s,keepDims:i}=a;Ne(n,"any");let o=w.parseAxisParam(s,n.shape),l=o,d=N.getAxesPermutation(l,n.shape.length),u=n;d!=null&&(u=Ma({inputs:{x:n},backend:r,attrs:{perm:d}}),l=N.getInnerMostAxes(l.length,n.shape.length)),N.assertAxesAreInnerMostDims("any",l,u.shape.length);let[p,h]=N.computeOutAndReduceShapes(u.shape,l),c=w.sizeFromShape(h),f=w.makeZerosTypedArray(w.sizeFromShape(p),u.dtype),m=r.data.get(u.dataId).values;for(let y=0;y<f.length;++y){let A=y*c,x=m[A];for(let b=0;b<c;++b){let v=m[A+b];x=x||v}f[y]=x}d!=null&&r.disposeIntermediateTensorInfo(u);let g=r.makeTensorInfo(p,u.dtype,f);if(i){let y=N.expandShapeToKeepDim(p,o),A=$t({inputs:{x:g},backend:r,attrs:{shape:y}});return r.disposeIntermediateTensorInfo(g),A}return g}var Pq={kernelName:Eu,backendName:"cpu",kernelFunc:$q};function Oq(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{axis:s}=a;Ne(n,"argMax");let i=w.parseAxisParam(s,n.shape),o=N.getAxesPermutation(i,n.shape.length),l=n,d=[];o!=null&&(l=Ma({inputs:{x:n},backend:r,attrs:{perm:o}}),d.push(l),i=N.getInnerMostAxes(i.length,l.shape.length)),i=[i[0]],N.assertAxesAreInnerMostDims("argMax",i,l.shape.length);let[u,p]=N.computeOutAndReduceShapes(l.shape,i),h=w.sizeFromShape(u),c=w.makeZerosTypedArray(h,"int32"),f=w.sizeFromShape(p),m=r.data.get(l.dataId).values;for(let g=0;g<c.length;++g){let y=g*f,A=m[y],x=0;for(let b=0;b<f;++b){let v=m[y+b];v>A&&(A=v,x=b)}c[g]=x}return d.forEach(g=>r.disposeIntermediateTensorInfo(g)),r.makeTensorInfo(u,"int32",c)}var zq={kernelName:Hs,backendName:"cpu",kernelFunc:Oq};function Dq(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{axis:s}=a;Ne(n,"argMin");let i=w.parseAxisParam(s,n.shape),o=N.getAxesPermutation(i,n.shape.length),l=n,d=[];o!=null&&(l=Ma({inputs:{x:n},backend:r,attrs:{perm:o}}),d.push(l),i=N.getInnerMostAxes(i.length,l.shape.length)),i=[i[0]],N.assertAxesAreInnerMostDims("argMin",i,l.shape.length);let[u,p]=N.computeOutAndReduceShapes(l.shape,i),h=w.sizeFromShape(u),c=w.makeZerosTypedArray(h,"int32"),f=w.sizeFromShape(p),m=r.data.get(l.dataId).values;for(let g=0;g<c.length;++g){let y=g*f,A=m[y],x=0;for(let b=0;b<f;++b){let v=m[y+b];v<A&&(A=v,x=b)}c[g]=x}return d.forEach(g=>r.disposeIntermediateTensorInfo(g)),r.makeTensorInfo(u,"int32",c)}var _q={kernelName:Ru,backendName:"cpu",kernelFunc:Dq},Lq=gt(Fu,e=>Math.asin(e)),Bq={kernelName:Fu,backendName:"cpu",kernelFunc:Lq},Wq=gt(Mu,e=>Math.asinh(e)),Vq={kernelName:Mu,backendName:"cpu",kernelFunc:Wq},Uq=gt($u,e=>Math.atan(e)),Gq={kernelName:$u,backendName:"cpu",kernelFunc:Uq},jq=Zt((e,t)=>Math.atan2(e,t)),Hq=mr(Ou,jq),qq={kernelName:Ou,backendName:"cpu",kernelFunc:Hq},Kq=gt(Pu,e=>Math.atanh(e)),Xq={kernelName:Pu,backendName:"cpu",kernelFunc:Kq};function Ix(e,t,r,a,n,s){let i=n.strideHeight,o=n.strideWidth,l=n.dilationHeight,d=n.dilationWidth,u=n.effectiveFilterHeight,p=n.effectiveFilterWidth,h=n.padInfo.top,c=n.padInfo.left,f=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=Le(n.outShape,r),g=m.values,y=n.outShape[1]*n.outShape[2]*n.outShape[3],A=n.outShape[2]*n.outShape[3],x=n.outShape[3];for(let b=0;b<n.batchSize;++b){let v=b*y,C=b*a[0];for(let T=0;T<n.inChannels;++T)for(let E=0;E<n.outHeight;++E){let R=E*i-h,z=Math.max(0,R),M=Math.min(n.inHeight,u+R),I=v+E*A;for(let D=0;D<n.outWidth;++D){let O=D*o-c,j=Math.max(0,O),X=Math.min(n.inWidth,p+O),_=f,K=0,W=0;for(let Q=z;Q<M;Q+=l){let ne=C+Q*a[1];for(let Z=j;Z<X;Z+=d){let ae=ne+Z*a[2],ie=e[ae+T];s==="max"&&ie>_?_=ie:s==="avg"&&(K+=ie,W++)}if(isNaN(_))break}let ee=I+D*x+T;g[ee]=s==="avg"?K/W:_}}}return m}function q6(e,t,r,a,n=!1,s=!1){let i=Le(a.outShape,"int32"),o=a.strideHeight,l=a.strideWidth,d=a.dilationHeight,u=a.dilationWidth,p=a.effectiveFilterHeight,h=a.effectiveFilterWidth,c=a.padInfo.top,f=a.padInfo.left,m=Le(t,r,e);for(let g=0;g<a.batchSize;++g)for(let y=0;y<a.inChannels;++y)for(let A=0;A<a.outHeight;++A){let x=A*o-c,b=x;for(;b<0;)b+=d;let v=Math.min(a.inHeight,p+x);for(let C=0;C<a.outWidth;++C){let T=C*l-f,E=T;for(;E<0;)E+=u;let R=Math.min(a.inWidth,h+T),z=Number.NEGATIVE_INFINITY,M=-1;for(let I=b;I<v;I+=d){let D=I-x;for(let O=E;O<R;O+=u){let j=O-T,X=m.get(g,I,O,y);X>z&&(z=X,n?M=s?((g*a.inHeight+I)*a.inWidth+O)*a.inChannels+y:(I*a.inWidth+O)*a.inChannels+y:M=D*h+j)}}i.set(M,g,A,C,y)}}return i}function K6(e,t,r,a,n,s){let i=n.strideDepth,o=n.strideHeight,l=n.strideWidth,d=n.dilationDepth,u=n.dilationHeight,p=n.dilationWidth,h=n.effectiveFilterDepth,c=n.effectiveFilterHeight,f=n.effectiveFilterWidth,m=n.padInfo.front,g=n.padInfo.top,y=n.padInfo.left,A=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,x=Le(n.outShape,r),b=x.values,v=n.outShape[1]*n.outShape[2]*n.outShape[3]*n.outShape[4],C=n.outShape[2]*n.outShape[3]*n.outShape[4],T=n.outShape[3]*n.outShape[4],E=n.outShape[4];for(let R=0;R<n.batchSize;++R){let z=R*v,M=R*a[0];for(let I=0;I<n.inChannels;++I)for(let D=0;D<n.outDepth;++D){let O=D*i-m,j=O;for(;j<0;)j+=d;let X=Math.min(n.inDepth,h+O),_=z+D*C;for(let K=0;K<n.outHeight;++K){let W=K*o-g,ee=W;for(;ee<0;)ee+=u;let Q=Math.min(n.inHeight,c+W),ne=_+K*T;for(let Z=0;Z<n.outWidth;++Z){let ae=Z*l-y,ie=ae;for(;ie<0;)ie+=p;let xe=Math.min(n.inWidth,f+ae),be=ne+Z*E,Te=A,Re=0,$e=0;for(let qe=j;qe<X;qe+=d){let Ze=M+qe*a[1];for(let st=ee;st<Q;st+=u){let ht=Ze+st*a[2];for(let ct=ie;ct<xe;ct+=p){let yt=ht+ct*a[3],Et=e[yt+I];if(s==="max"&&Et>Te?Te=Et:s==="avg"&&(Re+=Et,$e++),isNaN(Te))break}if(isNaN(Te))break}if(isNaN(Te))break}let _e=be+I;b[_e]=s==="avg"?Re/$e:Te}}}}return x}function Zq(e,t){let r=Le(t.outShape,"int32"),a=t.strideDepth,n=t.strideHeight,s=t.strideWidth,i=t.dilationDepth,o=t.dilationHeight,l=t.dilationWidth,d=t.effectiveFilterDepth,u=t.effectiveFilterHeight,p=t.effectiveFilterWidth,h=t.padInfo.front,c=t.padInfo.top,f=t.padInfo.left;for(let m=0;m<t.batchSize;++m)for(let g=0;g<t.inChannels;++g)for(let y=0;y<t.outDepth;++y){let A=y*a-h,x=A;for(;x<0;)x+=i;let b=Math.min(t.inDepth,d+A);for(let v=0;v<t.outHeight;++v){let C=v*n-c,T=C;for(;T<0;)T+=o;let E=Math.min(t.inHeight,u+C);for(let R=0;R<t.outWidth;++R){let z=R*s-f,M=z;for(;M<0;)M+=l;let I=Math.min(t.inWidth,p+z),D=Number.NEGATIVE_INFINITY,O=-1;for(let j=x;j<b;j+=i){let X=j-A;for(let _=T;_<E;_+=o){let K=_-C;for(let W=M;W<I;W+=l){let ee=W-z,Q=e.get(m,j,_,W,g);Q>=D&&(D=Q,O=X*u*p+K*u+ee)}}}r.set(O,m,y,v,R,g)}}}return r}function Yq(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t;Ne(n,"avgPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,d=1;w.assert(N.eitherStridesOrDilationsAreOne(i,d),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${d}'`);let u=N.computePool2DInfo(n.shape,s,i,d,o,l),p;if(u.filterWidth===1&&u.filterHeight===1&&w.arraysEqual(u.inShape,u.outShape))p=En({inputs:{x:n},backend:r});else{let h=r.data.get(n.dataId).values,c=w.computeStrides(n.shape),f=Ix(h,n.shape,n.dtype,c,u,"avg");p=r.makeTensorInfo(u.outShape,n.dtype,f.values)}return p}var Jq={kernelName:qs,backendName:"cpu",kernelFunc:Yq};function Qq(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:d}=a;Ne(n,"avgPool3d");let u=N.computePool3DInfo(n.shape,s,i,1,o,l,d),p=r.data.get(n.dataId).values,h=K6(p,n.shape,n.dtype,w.computeStrides(n.shape),u,"avg");return r.makeTensorInfo(h.shape,"float32",h.values)}var eK={kernelName:_p,backendName:"cpu",kernelFunc:Qq};function tK(e){let{inputs:t,backend:r,attrs:a}=e,{dy:n,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:d}=a;Ne([n,s],"avgPool3DGrad");let u=N.computePool3DInfo(s.shape,i,o,1,l,d),p=u.strideDepth,h=u.strideHeight,c=u.strideWidth,f=u.filterDepth,m=u.filterHeight,g=u.filterWidth,y=u.dilationDepth,A=u.dilationHeight,x=u.dilationWidth,b=u.effectiveFilterDepth,v=u.effectiveFilterHeight,C=u.effectiveFilterWidth,T=b-1-u.padInfo.front,E=C-1-u.padInfo.left,R=v-1-u.padInfo.top,z=Le(s.shape,"float32"),M=1/(f*m*g),I=r.bufferSync(n);for(let D=0;D<u.batchSize;++D)for(let O=0;O<u.inChannels;++O)for(let j=0;j<u.inDepth;++j)for(let X=0;X<u.inHeight;++X)for(let _=0;_<u.inWidth;++_){let K=j-T,W=X-R,ee=_-E,Q=0;for(let ne=0;ne<b;ne+=y){let Z=(K+ne)/p;if(!(Z<0||Z>=u.outDepth||Math.floor(Z)!==Z))for(let ae=0;ae<v;ae+=A){let ie=(W+ae)/h;if(!(ie<0||ie>=u.outHeight||Math.floor(ie)!==ie))for(let xe=0;xe<C;xe+=x){let be=(ee+xe)/c;be<0||be>=u.outWidth||Math.floor(be)!==be||(Q+=I.get(D,Z,ie,be,O))}}}z.set(Q*M,D,j,X,_,O)}return r.makeTensorInfo(z.shape,z.dtype,z.values)}var rK={kernelName:Cf,backendName:"cpu",kernelFunc:tK};function aK(e){let{inputs:t,backend:r,attrs:a}=e,{dy:n,input:s}=t,i=s;Ne([n,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:d}=a,u=N.computePool2DInfo(i.shape,o,l,1,d),p=u.strideHeight,h=u.strideWidth,c=u.filterHeight,f=u.filterWidth,m=u.dilationHeight,g=u.dilationWidth,y=u.effectiveFilterHeight,A=u.effectiveFilterWidth,x=A-1-u.padInfo.left,b=y-1-u.padInfo.top,v=Le(i.shape,"float32"),C=1/(c*f),T=r.data.get(n.dataId).values,E=Le(n.shape,"float32",T);for(let R=0;R<u.batchSize;++R)for(let z=0;z<u.inChannels;++z)for(let M=0;M<u.inHeight;++M)for(let I=0;I<u.inWidth;++I){let D=M-b,O=I-x,j=0;for(let X=0;X<y;X+=m){let _=(D+X)/p;if(!(_<0||_>=u.outHeight||Math.floor(_)!==_))for(let K=0;K<A;K+=g){let W=(O+K)/h;W<0||W>=u.outWidth||Math.floor(W)!==W||(j+=E.get(R,_,W,z))}}v.set(j*C,R,M,I,z)}return r.makeTensorInfo(v.shape,v.dtype,v.values)}var nK={kernelName:Tf,backendName:"cpu",kernelFunc:aK};function sK(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,scale:s,offset:i,mean:o,variance:l}=t;w.assert(o.shape.length===l.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),w.assert(i==null||o.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),w.assert(s==null||o.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),Ne([n,o,l,s,i],"batchNorm");let{varianceEpsilon:d}=a;d==null&&(d=.001);let u=r.data.get(n.dataId).values,p=r.data.get(o.dataId).values,h=r.data.get(l.dataId).values,c=s?r.data.get(s.dataId).values:new Float32Array([1]),f=i?r.data.get(i.dataId).values:new Float32Array([0]),m=new Float32Array(u.length),g=f.length,y=c.length,A=h.length,x=p.length,b=0,v=0,C=0,T=0;for(let E=0;E<u.length;++E)m[E]=f[b++]+(u[E]-p[v++])*c[C++]/Math.sqrt(h[T++]+d),b>=g&&(b=0),v>=x&&(v=0),C>=y&&(C=0),T>=A&&(T=0);return r.makeTensorInfo(n.shape,n.dtype,m)}var iK={kernelName:oi,backendName:"cpu",kernelFunc:sK};function oK(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{blockShape:s,crops:i}=a;Ne([n],"batchToSpaceND");let o=s.reduce((y,A)=>y*A),l=N.getReshaped(n.shape,s,o),d=N.getPermuted(l.length,s.length),u=N.getReshapedPermuted(n.shape,s,o),p=N.getSliceBeginCoords(i,s.length),h=N.getSliceSize(u,i,s.length),c=$t({inputs:{x:n},backend:r,attrs:{shape:l}}),f=Ma({inputs:{x:c},backend:r,attrs:{perm:d}}),m=$t({inputs:{x:f},backend:r,attrs:{shape:u}}),g=So({inputs:{x:m},backend:r,attrs:{begin:p,size:h}});return r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(f),r.disposeIntermediateTensorInfo(m),g}var lK={kernelName:Mo,backendName:"cpu",kernelFunc:oK};function uK(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,weights:s}=t,{size:i}=a,o=r.data.get(n.dataId).values,l=r.data.get(s.dataId).values,d=gx(o,l,s.dtype,s.shape,i);return r.makeTensorInfo([i],s.dtype,d)}var dK={kernelName:Nf,backendName:"cpu",kernelFunc:uK};function pK(e){let{inputs:t,backend:r}=e,{s0:a,s1:n}=t,s=r.data.get(a.dataId).values,i=r.data.get(n.dataId).values,o=N.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return r.makeTensorInfo([o.length],"int32",Int32Array.from(o))}var hK={kernelName:Ef,backendName:"cpu",kernelFunc:pK},cK=gt(Kn,(e,t)=>{let r=t;return e>r.clipValueMax?r.clipValueMax:e<r.clipValueMin?r.clipValueMin:e}),fK={kernelName:Kn,backendName:"cpu",kernelFunc:cK},mK=e=>{let{x:t}=e.inputs,r=e.backend,a=new Float32Array(w.sizeFromShape(t.shape)),n=r.data.get(t.dataId),s=n.complexTensorInfos.real,i=n.complexTensorInfos.imag,o=r.data.get(s.dataId).values,l=r.data.get(i.dataId).values;for(let d=0;d<o.length;d++){let u=o[d],p=l[d];a[d]=Math.hypot(u,p)}return r.makeOutput(a,t.shape,"float32")},gK={kernelName:Bp,backendName:"cpu",kernelFunc:mK};function bu(e){let{inputs:t,backend:r}=e,{input:a}=t,n=r.data.get(a.dataId).complexTensorInfos.imag,s=r.data.get(n.dataId).values;return r.makeTensorInfo(n.shape,n.dtype,s)}var yK={kernelName:Gp,backendName:"cpu",kernelFunc:bu};function vu(e){let{inputs:t,backend:r,attrs:a}=e,{axis:n}=a,s=w.parseAxisParam(n,t[0].shape)[0],i=N.computeOutShape(t.map(m=>m.shape),s);if(w.sizeFromShape(i)===0)return r.makeTensorInfo(i,t[0].dtype,[]);let o=t.filter(m=>w.sizeFromShape(m.shape)>0);if(o.length===1)return En({inputs:{x:o[0]},backend:r});let l=o.map(m=>m.shape);if(N.assertParamsConsistent(l,s),o[0].dtype==="complex64"){let m=o.map(b=>Io({inputs:{input:b},backend:r})),g=o.map(b=>bu({inputs:{input:b},backend:r})),y=vu({inputs:m,backend:r,attrs:{axis:s}}),A=vu({inputs:g,backend:r,attrs:{axis:s}}),x=ua({inputs:{real:y,imag:A},backend:r});return m.forEach(b=>r.disposeIntermediateTensorInfo(b)),g.forEach(b=>r.disposeIntermediateTensorInfo(b)),r.disposeIntermediateTensorInfo(y),r.disposeIntermediateTensorInfo(A),x}let d=o.map(m=>{let g=w.sizeFromShape(m.shape.slice(s));return $t({inputs:{x:m},backend:r,attrs:{shape:[-1,g]}})}),u=d.map(m=>({vals:r.data.get(m.dataId).values,shape:m.shape}));i=N.computeOutShape(d.map(m=>m.shape),1);let p=d[0].shape[0]===1,h=yx(u,i,t[0].dtype,p),c=N.computeOutShape(o.map(m=>m.shape),s),f=r.makeTensorInfo(c,t[0].dtype,h);return d.forEach(m=>r.disposeIntermediateTensorInfo(m)),f}var AK={kernelName:$o,backendName:"cpu",kernelFunc:vu};function X6(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:d,dimRoundingMode:u}=a;Ne([n,s],"conv2d");let p=N.convertConv2DDataFormat(l),h=N.computeConv2DInfo(n.shape,s.shape,i,d,o,u,!1,p),c=h.filterHeight,f=h.filterWidth,m=h.dilationHeight,g=h.dilationWidth,y=h.padInfo.left,A=h.padInfo.top,x=h.dataFormat==="channelsLast",b=new tr(h.outShape,n.dtype),v=w.computeStrides(n.shape),C=w.computeStrides(s.shape),T=v[0],E=x?v[1]:v[2],R=x?v[2]:1,z=x?1:v[1],M=b.strides[0],I=x?b.strides[1]:b.strides[2],D=x?b.strides[2]:1,O=x?1:b.strides[1],j=r.data.get(n.dataId).values,X=r.data.get(s.dataId).values,_=b.values;for(let K=0;K<h.batchSize;++K){let W=K*T,ee=K*M;for(let Q=0;Q<h.outHeight;++Q){let ne=ee+Q*I,Z=Q*h.strideHeight-A;for(let ae=0;ae<c;++ae){let ie=Z+ae*m;if(ie<0||ie>=h.inHeight)continue;let xe=ae*C[0],be=W+ie*E;for(let Te=0;Te<h.outWidth;++Te){let Re=ne+Te*D,$e=Te*h.strideWidth-y;for(let _e=0;_e<f;++_e){let qe=$e+_e*g;if(qe<0||qe>=h.inWidth)continue;let Ze=xe+_e*C[1],st=be+qe*R,ht=Ze;for(let ct=0;ct<h.inChannels;++ct){let yt=j[st+ct*z];for(let Et=0;Et<h.outChannels;++Et)_[Re+Et*O]+=yt*X[ht+Et];ht+=h.outChannels}}}}}}return r.makeTensorInfo(b.shape,b.dtype,_)}var xK={kernelName:Ys,backendName:"cpu",kernelFunc:X6};function bK(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,dy:s}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:d,filterShape:u}=a;Ne([n,s],"conv2dBackpropFilter");let p=N.convertConv2DDataFormat(l),h=N.computeConv2DInfo(n.shape,u,i,1,o,d,!1,p),{strideHeight:c,strideWidth:f,filterHeight:m,filterWidth:g}=h,y=h.dataFormat==="channelsLast",A=new tr(h.filterShape,"float32"),x=h.padInfo.left,b=h.padInfo.top,v=r.data.get(n.dataId).values,C=r.data.get(s.dataId).values,T=new tr(n.shape,n.dtype,v),E=new tr(s.shape,s.dtype,C);for(let R=0;R<m;++R){let z=Math.max(0,Math.ceil((b-R)/c)),M=Math.min(h.outHeight,(h.inHeight+b-R)/c);for(let I=0;I<g;++I){let D=Math.max(0,Math.ceil((x-I)/f)),O=Math.min(h.outWidth,(h.inWidth+x-I)/f);for(let j=0;j<h.inChannels;++j)for(let X=0;X<h.outChannels;++X){let _=0;for(let K=0;K<h.batchSize;++K)for(let W=z;W<M;++W){let ee=R+W*c-b;for(let Q=D;Q<O;++Q){let ne=I+Q*f-x;y?_+=T.get(K,ee,ne,j)*E.get(K,W,Q,X):_+=T.get(K,j,ee,ne)*E.get(K,X,W,Q)}}A.set(_,R,I,j,X)}}}return r.makeTensorInfo(A.shape,A.dtype,A.values)}var vK={kernelName:Rf,backendName:"cpu",kernelFunc:bK};function wK(e){let{inputs:t,backend:r,attrs:a}=e,{dy:n,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:d,dimRoundingMode:u}=a;Ne([n,s],"conv2dBackpropInput");let p=w.computeStrides(s.shape),h=w.computeStrides(n.shape),c=N.convertConv2DDataFormat(d),f=N.computeConv2DInfo(i,s.shape,o,1,l,u,!1,c),m=new tr(f.inShape,"float32"),g=m.values,y=r.data.get(n.dataId).values,A=r.data.get(s.dataId).values,[x,b,v]=p,{batchSize:C,filterHeight:T,filterWidth:E,inChannels:R,inHeight:z,inWidth:M,outChannels:I,outHeight:D,outWidth:O,strideHeight:j,strideWidth:X}=f;c=f.dataFormat;let _=T-1-f.padInfo.top,K=E-1-f.padInfo.left,W=c==="channelsLast",ee=m.strides[0],Q=W?m.strides[1]:m.strides[2],ne=W?m.strides[2]:1,Z=W?1:m.strides[1],ae=h[0],ie=W?h[1]:h[2],xe=W?h[2]:1,be=W?1:h[1];for(let Te=0;Te<C;++Te)for(let Re=0;Re<R;++Re)for(let $e=0;$e<z;++$e){let _e=$e-_,qe=Math.max(0,Math.ceil(_e/j)),Ze=Math.min(D,(T+_e)/j);for(let st=0;st<M;++st){let ht=st-K,ct=Math.max(0,Math.ceil(ht/X)),yt=Math.min(O,(E+ht)/X),Et=0;for(let ut=qe;ut<Ze;++ut){let qr=ut*j-_e;for(let gr=ct;gr<yt;++gr){let Kr=gr*X-ht,za=ae*Te+ie*ut+xe*gr,Xr=x*(T-1-qr)+b*(E-1-Kr)+v*Re;for(let Rr=0;Rr<I;++Rr){let Da=y[za+be*Rr],xn=A[Xr+Rr];Et+=Da*xn}}}let Hr=ee*Te+Q*$e+ne*st+Z*Re;g[Hr]=Et}}return r.makeTensorInfo(m.shape,m.dtype,m.values)}var kK={kernelName:Js,backendName:"cpu",kernelFunc:wK};function IK(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,filter:s}=t,{strides:i,pad:o,dilations:l}=a;Ne([n,s],"conv3d");let d=N.computeConv3DInfo(n.shape,s.shape,i,l,o),{filterDepth:u,filterHeight:p,filterWidth:h,dilationDepth:c,dilationHeight:f,dilationWidth:m,padInfo:g}=d,y=g.front,A=g.left,x=g.top,b=new tr(d.outShape,n.dtype),v=r.data.get(n.dataId).values,C=r.data.get(s.dataId).values,T=b.values,E=w.computeStrides(n.shape),R=w.computeStrides(s.shape);for(let z=0;z<d.batchSize;++z){let M=z*E[0],I=z*b.strides[0];for(let D=0;D<d.outDepth;++D){let O=I+D*b.strides[1],j=D*d.strideDepth-y;for(let X=0;X<u;++X){let _=j+X*c;if(_<0||_>=d.inDepth)continue;let K=X*R[0],W=M+_*E[1];for(let ee=0;ee<d.outHeight;++ee){let Q=O+ee*b.strides[2],ne=ee*d.strideHeight-x;for(let Z=0;Z<p;++Z){let ae=ne+Z*f;if(ae<0||ae>=d.inHeight)continue;let ie=K+Z*R[1],xe=W+ae*E[2];for(let be=0;be<d.outWidth;++be){let Te=Q+be*d.outChannels,Re=be*d.strideWidth-A;for(let $e=0;$e<h;++$e){let _e=Re+$e*m;if(_e<0||_e>=d.inWidth)continue;let qe=ie+$e*R[2],Ze=xe+_e*d.inChannels,st=qe;for(let ht=0;ht<d.inChannels;++ht){let ct=v[Ze+ht];for(let yt=0;yt<d.outChannels;++yt)T[Te+yt]+=ct*C[st+yt];st+=d.outChannels}}}}}}}}return r.makeTensorInfo(b.shape,b.dtype,b.values)}var SK={kernelName:Wp,backendName:"cpu",kernelFunc:IK};function TK(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,dy:s}=t,{strides:i,pad:o,filterShape:l}=a;Ne([n,s],"conv3dBackpropFilterV2");let d=w.computeStrides(n.shape),u=w.computeStrides(s.shape),p=N.computeConv3DInfo(n.shape,l,i,1,o),h=p.strideDepth,c=p.strideHeight,f=p.strideWidth,m=p.filterDepth,g=p.filterHeight,y=p.filterWidth,A=new tr(p.filterShape,"float32"),x=A.values,[b,v,C,T]=A.strides,E=r.data.get(s.dataId).values,[R,z,M,I]=u,D=r.data.get(n.dataId).values,[O,j,X,_]=d,K=p.padInfo.front,W=p.padInfo.left,ee=p.padInfo.top;for(let Q=0;Q<m;++Q){let ne=Math.max(0,Math.ceil((K-Q)/h)),Z=Math.min(p.outDepth,(p.inDepth+K-Q)/h),ae=Q*b;for(let ie=0;ie<g;++ie){let xe=Math.max(0,Math.ceil((ee-ie)/c)),be=Math.min(p.outHeight,(p.inHeight+ee-ie)/c),Te=ie*v+ae;for(let Re=0;Re<y;++Re){let $e=Math.max(0,Math.ceil((W-Re)/f)),_e=Math.min(p.outWidth,(p.inWidth+W-Re)/f),qe=Re*C+Te;for(let Ze=0;Ze<p.inChannels;++Ze){let st=Ze*T+qe;for(let ht=0;ht<p.outChannels;++ht){let ct=0;for(let yt=0;yt<p.batchSize;++yt){let Et=yt*O,Hr=yt*R;for(let ut=ne;ut<Z;++ut){let qr=(Q+ut*h-K)*j+Et,gr=ut*z+Hr;for(let Kr=xe;Kr<be;++Kr){let za=(ie+Kr*c-ee)*X+qr,Xr=Kr*M+gr;for(let Rr=$e;Rr<_e;++Rr){let Da=(Re+Rr*f-W)*_+za,xn=Rr*I+Xr;ct+=D[Da+Ze]*E[xn+ht]}}}}x[st+ht]=ct}}}}}return r.makeTensorInfo(A.shape,A.dtype,A.values)}var CK={kernelName:Ff,backendName:"cpu",kernelFunc:TK};function NK(e){let{inputs:t,backend:r,attrs:a}=e,{dy:n,filter:s}=t,{pad:i,strides:o,inputShape:l}=a;Ne([n],"conv3dBackpropInputV2");let d=w.computeStrides(n.shape),u=w.computeStrides(s.shape),p=N.computeConv3DInfo(l,s.shape,o,1,i),h=new tr(p.inShape,"float32"),c=h.values,[f,m,g,y]=h.strides,A=r.data.get(n.dataId).values,[x,b,v,C]=d,T=r.data.get(s.dataId).values,[E,R,z,M]=u,{batchSize:I,filterDepth:D,filterHeight:O,filterWidth:j,inChannels:X,inDepth:_,inHeight:K,inWidth:W,outChannels:ee,outDepth:Q,outHeight:ne,outWidth:Z,strideDepth:ae,strideHeight:ie,strideWidth:xe}=p,be=D-1-p.padInfo.front,Te=O-1-p.padInfo.top,Re=j-1-p.padInfo.left;for(let $e=0;$e<I;++$e)for(let _e=0;_e<X;++_e)for(let qe=0;qe<_;++qe){let Ze=qe-be,st=Math.max(0,Math.ceil(Ze/ae)),ht=Math.min(Q,(D+Ze)/ae);for(let ct=0;ct<K;++ct){let yt=ct-Te,Et=Math.max(0,Math.ceil(yt/ie)),Hr=Math.min(ne,(O+yt)/ie);for(let ut=0;ut<W;++ut){let qr=ut-Re,gr=Math.max(0,Math.ceil(qr/xe)),Kr=Math.min(Z,(j+qr)/xe),za=0;for(let Xr=st;Xr<ht;++Xr){let Rr=Xr*ae-Ze;for(let Da=Et;Da<Hr;++Da){let xn=Da*ie-yt;for(let ia=gr;ia<Kr;++ia){let _l=ia*xe-qr,Zr=x*$e+b*Xr+v*Da+C*ia,hs=E*(D-1-Rr)+R*(O-1-xn)+z*(j-1-_l)+M*_e;for(let va=0;va<ee;++va){let Bd=A[Zr+va],Wd=T[hs+va];za+=Bd*Wd}}}}c[f*$e+m*qe+g*ct+y*ut+_e]=za}}}return r.makeTensorInfo(h.shape,h.dtype,h.values)}var EK={kernelName:Mf,backendName:"cpu",kernelFunc:NK},RK=gt(Qs,e=>Math.cos(e)),FK={kernelName:Qs,backendName:"cpu",kernelFunc:RK},MK=gt(ei,e=>Math.cosh(e)),$K={kernelName:ei,backendName:"cpu",kernelFunc:MK};function PK(e){let{inputs:t,backend:r,attrs:a}=e,{image:n,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:d}=a,[u,p,h,c]=n.shape,f=s.shape[0],[m,g]=o,y=Le([f,m,g,c],"float32"),A=r.data.get(s.dataId).values,x=r.data.get(i.dataId).values,b=r.data.get(n.dataId).values,v=w.computeStrides(n.shape),C=w.computeStrides(y.shape);for(let T=0;T<f;T++){let E=T*4,R=A[E],z=A[E+1],M=A[E+2],I=A[E+3],D=x[T];if(D>=u)continue;let O=m>1?(M-R)*(p-1)/(m-1):0,j=g>1?(I-z)*(h-1)/(g-1):0;for(let X=0;X<m;X++){let _=m>1?R*(p-1)+X*O:.5*(R+M)*(p-1);if(_<0||_>p-1){for(let K=0;K<g;K++)for(let W=0;W<c;W++){let ee=W+K*C[2]+X*C[1]+T*C[0];y.values[ee]=d}continue}if(l==="bilinear"){let K=Math.floor(_),W=Math.ceil(_),ee=_-K;for(let Q=0;Q<g;Q++){let ne=g>1?z*(h-1)+Q*j:.5*(z+I)*(h-1);if(ne<0||ne>h-1){for(let xe=0;xe<c;xe++){let be=xe+Q*C[2]+X*C[1]+T*C[0];y.values[be]=d}continue}let Z=Math.floor(ne),ae=Math.ceil(ne),ie=ne-Z;for(let xe=0;xe<c;xe++){let be=xe+Z*v[2]+K*v[1]+D*v[0],Te=b[be];be=xe+ae*v[2]+K*v[1]+D*v[0];let Re=b[be];be=xe+Z*v[2]+W*v[1]+D*v[0];let $e=b[be];be=xe+ae*v[2]+W*v[1]+D*v[0];let _e=b[be],qe=Te+(Re-Te)*ie,Ze=$e+(_e-$e)*ie;be=xe+Q*C[2]+X*C[1]+T*C[0],y.values[be]=qe+(Ze-qe)*ee}}}else for(let K=0;K<g;++K){let W=g>1?z*(h-1)+K*j:.5*(z+I)*(h-1);if(W<0||W>h-1){for(let ne=0;ne<c;ne++){let Z=ne+K*C[2]+X*C[1]+T*C[0];y.values[Z]=d}continue}let ee=Math.round(W),Q=Math.round(_);for(let ne=0;ne<c;ne++){let Z=ne+ee*v[2]+Q*v[1]+D*v[0],ae=ne+K*C[2]+X*C[1]+T*C[0];y.values[ae]=b[Z]}}}}return r.makeTensorInfo(y.shape,y.dtype,y.values)}var OK={kernelName:Oo,backendName:"cpu",kernelFunc:PK};function zK(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{axis:s,exclusive:i,reverse:o}=a;Ne(n,"cumsum");let l=N.getAxesPermutation([s],n.shape.length),d=n;l!=null&&(d=Ma({inputs:{x:n},backend:r,attrs:{perm:l}}));let u=N.getInnerMostAxes(1,n.shape.length)[0];if(u!==d.shape.length-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${d.shape.length-1} but got axis=${u}`);let p=Or(d.dtype,"int32"),h=w.makeZerosTypedArray(w.sizeFromShape(d.shape),p),c=r.data.get(d.dataId).values,f=d.shape[d.shape.length-1],m=o?(y,A)=>y+f-A-1:(y,A)=>y+A;for(let y=0;y<c.length;y+=f)for(let A=0;A<f;A++){let x=m(y,A);if(A===0)h[x]=i?0:c[x];else{let b=m(y,A-1);h[x]=i?c[b]+h[b]:c[x]+h[b]}}let g=r.makeTensorInfo(d.shape,p,h);if(l!=null){let y=N.getUndoAxesPermutation(l),A=Ma({inputs:{x:g},backend:r,attrs:{perm:y}});return r.disposeIntermediateTensorInfo(g),r.disposeIntermediateTensorInfo(d),A}return g}var DK={kernelName:Po,backendName:"cpu",kernelFunc:zK};function _K(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,weights:s}=t,{size:i,binaryOutput:o}=a;if(n.shape.length===1){let l=r.data.get(n.dataId).values,d=r.data.get(s.dataId).values,u=gx(l,d,s.dtype,s.shape,i);return r.makeTensorInfo([i],s.dtype,u)}else if(n.shape.length===2){let l=r.bufferSync(n),d=r.bufferSync(s),u=s6(l,d,i,o);return r.makeTensorInfo(u.shape,s.dtype,u.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${n.shape.length}.`)}var LK={kernelName:$f,backendName:"cpu",kernelFunc:_K};function BK(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{blockSize:s,dataFormat:i}=a;w.assert(i==="NHWC",()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${i}`);let o=n.shape[0],l=n.shape[1],d=n.shape[2],u=n.shape[3],p=l*s,h=d*s,c=u/(s*s),f=r.data.get(n.dataId).values,m=new Float32Array(o*p*h*c),g=0;for(let y=0;y<o;++y)for(let A=0;A<p;++A){let x=Math.floor(A/s),b=A%s;for(let v=0;v<h;++v){let C=Math.floor(v/s),T=v%s,E=(b*s+T)*c;for(let R=0;R<c;++R){let z=R+E+u*(C+d*(x+l*y));m[g++]=f[z]}}}return r.makeTensorInfo([o,p,h,c],n.dtype,m)}var WK={kernelName:zo,backendName:"cpu",kernelFunc:BK};function Z6(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,filter:s}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:d}=a;Ne([n,s],"depthwiseConv2DNative");let u=w.computeStrides(n.shape),p=w.computeStrides(s.shape),h=l;h==null&&(h=[1,1]),w.assert(N.eitherStridesOrDilationsAreOne(i,h),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${h}'`);let c=N.computeConv2DInfo(n.shape,s.shape,i,h,o,d,!0),{filterHeight:f,filterWidth:m,dilationHeight:g,dilationWidth:y,padInfo:A}=c,x=A.left,b=A.top,v=c.outChannels/c.inChannels,C=new tr(c.outShape,n.dtype),T=r.data.get(n.dataId).values,E=r.data.get(s.dataId).values,R=C.values;for(let z=0;z<c.batchSize;++z){let M=z*u[0],I=z*C.strides[0];for(let D=0;D<c.outHeight;++D){let O=I+D*C.strides[1],j=D*c.strideHeight-b;for(let X=0;X<f;++X){let _=j+X*g;if(_<0||_>=c.inHeight)continue;let K=X*p[0],W=M+_*u[1];for(let ee=0;ee<c.outWidth;++ee){let Q=O+ee*C.strides[2],ne=ee*c.strideWidth-x;for(let Z=0;Z<m;++Z){let ae=ne+Z*y;if(ae<0||ae>=c.inWidth)continue;let ie=K+Z*p[1],xe=W+ae*c.inChannels,be=Q,Te=ie;for(let Re=0;Re<c.inChannels;++Re){let $e=T[xe+Re];for(let _e=0;_e<v;++_e)R[be+_e]+=$e*E[Te+_e];be+=v,Te+=v}}}}}}return r.makeTensorInfo(C.shape,C.dtype,C.values)}var VK={kernelName:ti,backendName:"cpu",kernelFunc:Z6};function UK(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,dy:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:d,filterShape:u}=a;Ne([n,s],"depthwiseConv2dNativeBackpropFilter");let p=N.computeConv2DInfo(n.shape,u,i,o,l,d,!0),{strideHeight:h,strideWidth:c,filterHeight:f,filterWidth:m}=p,g=new tr(p.filterShape,"float32"),y=p.padInfo.left,A=p.padInfo.top,x=p.outChannels/p.inChannels,b=r.data.get(n.dataId).values,v=new tr(n.shape,n.dtype,b),C=r.data.get(s.dataId).values,T=new tr(s.shape,s.dtype,C);for(let E=0;E<f;++E){let R=Math.max(0,Math.ceil((A-E)/h)),z=Math.min(p.outHeight,(p.inHeight+A-E)/h);for(let M=0;M<m;++M){let I=Math.max(0,Math.ceil((y-M)/c)),D=Math.min(p.outWidth,(p.inWidth+y-M)/c);for(let O=0;O<p.outChannels;++O){let j=Math.trunc(O/x),X=O%x,_=0;for(let K=0;K<p.batchSize;++K)for(let W=R;W<z;++W){let ee=E+W*h-A;for(let Q=I;Q<D;++Q){let ne=M+Q*c-y;_+=v.get(K,ee,ne,j)*T.get(K,W,Q,O)}}g.set(_,E,M,j,X)}}}return r.makeTensorInfo(g.shape,g.dtype,g.values)}var GK={kernelName:Pf,backendName:"cpu",kernelFunc:UK};function jK(e){let{inputs:t,backend:r,attrs:a}=e,{dy:n,filter:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:d,inputShape:u}=a;Ne([n,s],"depthwiseConv2DNativeBackpropInput");let p=w.computeStrides(n.shape),h=w.computeStrides(s.shape),c=N.computeConv2DInfo(u,s.shape,i,o,l,d,!0),f=new tr(c.inShape,"float32"),m=f.values,[g,y,A]=f.strides,x=r.data.get(n.dataId).values,[b,v,C]=p,T=r.data.get(s.dataId).values,[E,R,z]=h,{batchSize:M,filterHeight:I,filterWidth:D,inChannels:O,inHeight:j,inWidth:X,outChannels:_,outHeight:K,outWidth:W,strideHeight:ee,strideWidth:Q}=c,ne=I-1-c.padInfo.top,Z=D-1-c.padInfo.left,ae=_/O;for(let ie=0;ie<M;++ie)for(let xe=0;xe<O;++xe)for(let be=0;be<j;++be){let Te=be-ne,Re=Math.max(0,Math.ceil(Te/ee)),$e=Math.min(K,(I+Te)/ee);for(let _e=0;_e<X;++_e){let qe=_e-Z,Ze=Math.max(0,Math.ceil(qe/Q)),st=Math.min(W,(D+qe)/Q),ht=0;for(let ct=Re;ct<$e;++ct){let yt=ct*ee-Te;for(let Et=Ze;Et<st;++Et){let Hr=Et*Q-qe,ut=b*ie+v*ct+C*Et,qr=E*(I-1-yt)+R*(D-1-Hr)+z*xe;for(let gr=0;gr<ae;++gr){let Kr=xe*ae+gr,za=x[ut+Kr],Xr=T[qr+gr];ht+=za*Xr}}}m[g*ie+y*be+A*_e+xe]=ht}}return r.makeTensorInfo(f.shape,f.dtype,f.values)}var HK={kernelName:Of,backendName:"cpu",kernelFunc:jK};function qK(e){let{inputs:t,backend:r}=e,{x:a}=t,n=w.sizeFromShape(a.shape),s=r.data.get(a.dataId).values,i=Le([n,n],a.dtype),o=i.values;for(let d=0;d<s.length;d++)o[d*n+d]=s[d];let l=[...a.shape,...a.shape];return r.makeTensorInfo(l,i.dtype,i.values)}var KK={kernelName:zf,backendName:"cpu",kernelFunc:qK},XK={kernelName:Vp,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:r})=>{let{x:a,filter:n}=e,{strides:s,pad:i,dilations:o}=r,l=t,d=l.data.get(a.dataId).values,u=a.shape.length,p=l.data.get(n.dataId).values,h=n.shape.length,{batchSize:c,inHeight:f,inWidth:m,inChannels:g,outHeight:y,outWidth:A,padInfo:x,strideHeight:b,strideWidth:v,filterHeight:C,filterWidth:T,dilationHeight:E,dilationWidth:R,outShape:z}=N.computeDilation2DInfo(a.shape,n.shape,s,i,"NHWC",o),M=w.sizeFromShape(z),I=z.length,D=w.getArrayFromDType(a.dtype,M);for(let O=0;O<c;++O)for(let j=0;j<y;++j){let X=j*b-x.top;for(let _=0;_<A;++_){let K=_*v-x.left;for(let W=0;W<g;++W){let ee=Number.MIN_SAFE_INTEGER;for(let ne=0;ne<C;++ne){let Z=X+ne*E;if(Z>=0&&Z<f)for(let ae=0;ae<T;++ae){let ie=K+ae*R;if(ie>=0&&ie<m){let xe=w.locToIndex([O,Z,ie,W],u,w.computeStrides(a.shape)),be=w.locToIndex([ne,ae,W],h,w.computeStrides(n.shape)),Te=d[xe]+p[be];Te>ee&&(ee=Te)}}}let Q=w.locToIndex([O,j,_,W],I,w.computeStrides(z));D[Q]=ee}}}return{dataId:l.write(w.toTypedArray(D,a.dtype),z,a.dtype),shape:z,dtype:a.dtype}}},ZK={kernelName:Zc,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:r})=>{let{x:a,filter:n,dy:s}=e,{strides:i,pad:o,dilations:l}=r,d=t,u=w.toNestedArray(a.shape,d.data.get(a.dataId).values),p=w.toNestedArray(n.shape,d.data.get(n.dataId).values),{batchSize:h,inHeight:c,inWidth:f,inChannels:m,outHeight:g,outWidth:y,padInfo:A,strideHeight:x,strideWidth:b,filterHeight:v,filterWidth:C,dilationHeight:T,dilationWidth:E,outShape:R}=N.computeDilation2DInfo(a.shape,n.shape,i,o,"NHWC",l);w.assert(s.rank===R.length,()=>`Error in ${Zc}, dy must have the same rank as output ${R.length}, but got ${s.rank}`);let z=w.toNestedArray(R,d.data.get(s.dataId).values),M=w.makeZerosNestedTypedArray(n.shape,n.dtype);for(let I=0;I<h;++I)for(let D=0;D<g;++D){let O=D*x-A.top;for(let j=0;j<y;++j){let X=j*b-A.left;for(let _=0;_<m;++_){let K=Number.MIN_SAFE_INTEGER,W=0,ee=0;for(let Q=0;Q<v;++Q){let ne=O+Q*T;if(ne>=0&&ne<c)for(let Z=0;Z<C;++Z){let ae=X+Z*E;if(ae>=0&&ae<f){let ie=u[I][ne][ae][_]+p[Q][Z][_];ie>K&&(K=ie,W=Q,ee=Z)}}}M[W][ee][_]+=z[I][D][j][_]}}}return{dataId:d.write(w.toTypedArray(M,a.dtype),n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},YK={kernelName:Xc,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:r})=>{let{x:a,filter:n,dy:s}=e,{strides:i,pad:o,dilations:l}=r,d=t,u=w.toNestedArray(a.shape,d.data.get(a.dataId).values),p=w.toNestedArray(n.shape,d.data.get(n.dataId).values),{batchSize:h,inHeight:c,inWidth:f,inChannels:m,outHeight:g,outWidth:y,padInfo:A,strideHeight:x,strideWidth:b,filterHeight:v,filterWidth:C,dilationHeight:T,dilationWidth:E,outShape:R}=N.computeDilation2DInfo(a.shape,n.shape,i,o,"NHWC",l);w.assert(s.rank===R.length,()=>`Error in ${Xc}, dy must have the same rank as output ${R.length}, but got ${s.rank}`);let z=w.toNestedArray(R,d.data.get(s.dataId).values),M=w.makeZerosNestedTypedArray(a.shape,a.dtype);for(let I=0;I<h;++I)for(let D=0;D<g;++D){let O=D*x-A.top;for(let j=0;j<y;++j){let X=j*b-A.left;for(let _=0;_<m;++_){let K=Number.MIN_SAFE_INTEGER,W=O<0?0:O,ee=X<0?0:X;for(let Q=0;Q<v;++Q){let ne=O+Q*T;if(ne>=0&&ne<c)for(let Z=0;Z<C;++Z){let ae=X+Z*E;if(ae>=0&&ae<f){let ie=u[I][ne][ae][_]+p[Q][Z][_];ie>K&&(K=ie,W=ne,ee=ae)}}}M[I][W][ee][_]+=z[I][D][j][_]}}}return{dataId:d.write(w.toTypedArray(M,a.dtype),a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}};function Sh(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{axis:s,keepDims:i}=a;Ne(n,"sum");let o;n.dtype==="bool"?o=Us({inputs:{x:n},backend:r,attrs:{dtype:"int32"}}):o=En({inputs:{x:n},backend:r});let l=o.shape.length,d=w.parseAxisParam(s,o.shape),u=N.getAxesPermutation(d,l),p=d,h=o;u!=null&&(h=Ma({inputs:{x:o},backend:r,attrs:{perm:u}}),p=N.getInnerMostAxes(p.length,l)),N.assertAxesAreInnerMostDims("sum",p,h.shape.length);let[c,f]=N.computeOutAndReduceShapes(h.shape,p),m=N.upcastType(h.dtype,"int32"),g=ff(r,c,m),y=w.sizeFromShape(f),A=r.data.get(g.dataId).values,x=r.data.get(h.dataId).values;for(let b=0;b<A.length;++b){let v=b*y,C=0;for(let T=0;T<y;++T)C+=x[v+T];A[b]=C}if(i){let b=N.expandShapeToKeepDim(g.shape,d),v=g;g=$t({inputs:{x:g},backend:r,attrs:{shape:b}}),r.disposeIntermediateTensorInfo(v)}return r.disposeIntermediateTensorInfo(o),u!=null&&r.disposeIntermediateTensorInfo(h),g}var JK={kernelName:Ri,backendName:"cpu",kernelFunc:Sh};function QK(e){let{inputs:t,backend:r,attrs:a}=e,{equation:n}=a,s=t,{allDims:i,summedDims:o,idDims:l}=N.decodeEinsumEquation(n,s.length);N.checkEinsumDimSizes(i.length,l,s);let{path:d,steps:u}=N.getEinsumComputePath(o,l),p=u.length,h=null,c=i.length,f=[];for(let m=0;m<p;++m){for(let g of u[m]){let{permutationIndices:y,expandDims:A}=N.getEinsumPermutation(c,l[g]),x;N.isIdentityPermutation(y)?x=s[g]:(x=Ma({inputs:{x:s[g]},backend:r,attrs:{perm:y}}),f.push(x));let b=x.shape.slice();for(let v=0;v<A.length;++v)b.splice(A[v],0,1);w.arraysEqual(x.shape,b)||(x=$t({inputs:{x},backend:r,attrs:{shape:b}}),f.push(x)),h===null?h=x:(h=Xm({inputs:{a:x,b:h},backend:r}),f.push(h))}m<p-1&&(d[m]>=0&&(h=Sh({inputs:{x:h},backend:r,attrs:{axis:d[m]-(i.length-c),keepDims:!1}}),f.push(h)),c--)}for(let m of f)m!==h&&r.disposeIntermediateTensorInfo(m);return h}var eX={kernelName:Up,backendName:"cpu",kernelFunc:QK};function tX(e){let{inputs:t,backend:r}=e,{dy:a,y:n}=t;Ne([a,n],"eluGrad");let s=new Float32Array(w.sizeFromShape(n.shape)),i=r.data.get(n.dataId).values,o=r.data.get(a.dataId).values;for(let l=0;l<i.length;++l){let d=i[l];d>=1?s[l]=o[l]:s[l]=o[l]*(d+1)}return r.makeTensorInfo(n.shape,"float32",s)}var rX={kernelName:Df,backendName:"cpu",kernelFunc:tX},aX=N.ERF_P,nX=N.ERF_A1,sX=N.ERF_A2,iX=N.ERF_A3,oX=N.ERF_A4,lX=N.ERF_A5,uX=gt(zu,e=>{let t=Math.sign(e),r=Math.abs(e),a=1/(1+aX*r);return t*(1-((((lX*a+oX)*a+iX)*a+sX)*a+nX)*a*Math.exp(-r*r))}),dX={kernelName:zu,backendName:"cpu",kernelFunc:uX};function gf(e){let{inputs:t,backend:r,attrs:a}=e,{input:n}=t,{dim:s}=a,i=n.shape.length,o=n.shape.slice(),l=s;return s<0&&(w.assert(-(i+1)<=s,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+s+1),o.splice(l,0,1),$t({inputs:{x:n},backend:r,attrs:{shape:o}})}var pX={kernelName:_o,backendName:"cpu",kernelFunc:gf},hX=Zt((e,t)=>e/t),Sx=mr(ri,hX),my={kernelName:ri,backendName:"cpu",kernelFunc:Sx};function Y6(e,t,r){let a=e.shape,n=a[0],s=a[1],i=r.data.get(e.dataId),o=i.complexTensorInfos.real,l=i.complexTensorInfos.imag,d=[n,s],u=w.sizeFromShape(d),p=w.getTypedArrayFromDType("float32",u),h=w.getTypedArrayFromDType("float32",u);for(let g=0;g<n;g++){let y=So({inputs:{x:o},backend:r,attrs:{begin:[g,0],size:[1,s]}}),A=So({inputs:{x:l},backend:r,attrs:{begin:[g,0],size:[1,s]}}),x=ua({inputs:{real:y,imag:A},backend:r}),{real:b,imag:v}=cX(x,t,r),C=N.mergeRealAndImagArrays(b,v);for(let T=0;T<s;T++){let E=N.getComplexWithIndex(C,T);p[g*s+T]=E.real,h[g*s+T]=E.imag}r.disposeIntermediateTensorInfo(y),r.disposeIntermediateTensorInfo(A),r.disposeIntermediateTensorInfo(x)}let c=r.makeTensorInfo(d,"float32",p),f=r.makeTensorInfo(d,"float32",h),m=ua({inputs:{real:c,imag:f},backend:r});return r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(f),m}function cX(e,t,r){let a=w.sizeFromShape(e.shape),n=r.data.get(e.dataId),s=r.data.get(n.complexTensorInfos.real.dataId).values,i=r.data.get(n.complexTensorInfos.imag.dataId).values;if(fX(a)){let o=gy(s,i,a,t,r),l=[e.shape[0],e.shape[1]];if(t){let d=r.makeTensorInfo(l,"float32",o.real),u=r.makeTensorInfo(l,"float32",o.imag),p=r.makeTensorInfo([],"float32",w.createScalarValue(a,"float32")),h=En({inputs:{x:p},backend:r}),c=my.kernelFunc({inputs:{a:d,b:p},backend:r}),f=my.kernelFunc({inputs:{a:u,b:h},backend:r}),m=r.data.get(c.dataId).values,g=r.data.get(f.dataId).values;return r.disposeIntermediateTensorInfo(d),r.disposeIntermediateTensorInfo(u),r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(f),{real:m,imag:g}}return o}else{let o=N.mergeRealAndImagArrays(s,i),l=mX(o,a,t);return N.splitRealAndImagArrays(l)}}function fX(e){return(e&e-1)===0}function gy(e,t,r,a,n){if(r===1)return{real:e,imag:t};let s=N.mergeRealAndImagArrays(e,t),i=r/2,o=N.complexWithEvenIndex(s),l=o.real,d=o.imag,u=[l.length],p=n.makeTensorInfo(u,"float32",l),h=n.makeTensorInfo(u,"float32",d),c=ua({inputs:{real:p,imag:h},backend:n}),f=N.complexWithOddIndex(s),m=f.real,g=f.imag,y=[m.length],A=n.makeTensorInfo(y,"float32",m),x=n.makeTensorInfo(y,"float32",g),b=ua({inputs:{real:A,imag:x},backend:n}),v=gy(l,d,i,a,n),C=v.real,T=v.imag,E=[C.length],R=n.makeTensorInfo(E,"float32",C),z=n.makeTensorInfo(E,"float32",T),M=ua({inputs:{real:R,imag:z},backend:n}),I=gy(m,g,i,a,n),D=I.real,O=I.imag,j=[D.length],X=n.makeTensorInfo(j,"float32",D),_=n.makeTensorInfo(j,"float32",O),K=ua({inputs:{real:X,imag:_},backend:n}),W=N.exponents(r,a),ee=[W.real.length],Q=n.makeTensorInfo(ee,"float32",W.real),ne=n.makeTensorInfo(ee,"float32",W.imag),Z=ua({inputs:{real:Q,imag:ne},backend:n}),ae=Xm({inputs:{a:Z,b:K},backend:n}),ie=Ih({inputs:{a:M,b:ae},backend:n}),xe=wx({inputs:{a:M,b:ae},backend:n}),be=Io({inputs:{input:ie},backend:n}),Te=Io({inputs:{input:xe},backend:n}),Re=bu({inputs:{input:ie},backend:n}),$e=bu({inputs:{input:xe},backend:n}),_e=vu({inputs:[be,Te],backend:n,attrs:{axis:0}}),qe=vu({inputs:[Re,$e],backend:n,attrs:{axis:0}}),Ze=n.data.get(_e.dataId).values,st=n.data.get(qe.dataId).values;return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(A),n.disposeIntermediateTensorInfo(x),n.disposeIntermediateTensorInfo(b),n.disposeIntermediateTensorInfo(R),n.disposeIntermediateTensorInfo(z),n.disposeIntermediateTensorInfo(M),n.disposeIntermediateTensorInfo(X),n.disposeIntermediateTensorInfo(_),n.disposeIntermediateTensorInfo(K),n.disposeIntermediateTensorInfo(Q),n.disposeIntermediateTensorInfo(ne),n.disposeIntermediateTensorInfo(Z),n.disposeIntermediateTensorInfo(ae),n.disposeIntermediateTensorInfo(ie),n.disposeIntermediateTensorInfo(xe),n.disposeIntermediateTensorInfo(be),n.disposeIntermediateTensorInfo(Re),n.disposeIntermediateTensorInfo(Te),n.disposeIntermediateTensorInfo($e),n.disposeIntermediateTensorInfo(_e),n.disposeIntermediateTensorInfo(qe),{real:Ze,imag:st}}function mX(e,t,r){let a=new Float32Array(t*2);for(let n=0;n<t;n++){let s=0,i=0;for(let o=0;o<t;o++){let l=N.exponent(n*o,t,r),d=N.getComplexWithIndex(e,o);s+=d.real*l.real-d.imag*l.imag,i+=d.real*l.imag+d.imag*l.real}r&&(s/=t,i/=t),N.assignToTypedArray(a,s,i,n)}return a}function gX(e){let{inputs:t,backend:r}=e,{input:a}=t,n=w.sizeFromShape(a.shape),s=a.shape[a.shape.length-1],i=n/s,o=$t({inputs:{x:a},backend:r,attrs:{shape:[i,s]}}),l=Y6(o,!1,r),d=$t({inputs:{x:l},backend:r,attrs:{shape:a.shape}});return r.disposeIntermediateTensorInfo(o),r.disposeIntermediateTensorInfo(l),d}var yX={kernelName:_f,backendName:"cpu",kernelFunc:gX};function Tx(e){let{backend:t,attrs:r}=e,{shape:a,value:n,dtype:s}=r,i=s||w.inferDtype(n),o=w.getArrayFromDType(i,w.sizeFromShape(a));return xX(o,n,i),t.makeTensorInfo(a,i,o)}var AX={kernelName:Du,backendName:"cpu",kernelFunc:Tx};function xX(e,t,r){e.fill(t)}var bX={kernelName:Bo,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{image:a}=e,n=r,s=w.getTypedArrayFromDType(a.dtype,w.sizeFromShape(a.shape)),[i,o,l,d]=a.shape,u=n.data.get(a.dataId).values;for(let p=0;p<i;p++){let h=p*l*o*d;for(let c=0;c<o;c++){let f=c*(l*d);for(let m=0;m<l;m++){let g=m*d;for(let y=0;y<d;y++){let A=Math.round(l-m-1),x=h+f+g+y,b=u[x];if(A>=0&&A<l){let v=A*d,C=h+f+v+y;b=u[C]}s[x]=b}}}}return{dataId:n.write(s,a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}},vX=Zt((e,t)=>Math.floor(e/t)),wX=mr(ii,vX,null,"int32"),kX={kernelName:ii,backendName:"cpu",kernelFunc:wX};function IX(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:d,dataFormat:u,dilations:p,dimRoundingMode:h,activation:c,leakyreluAlpha:f}=a,m=X6({inputs:{x:n,filter:s},backend:r,attrs:{strides:l,pad:d,dataFormat:u,dilations:p,dimRoundingMode:h}});if(i){let g=m;m=Ih({inputs:{a:m,b:i},backend:r}),r.disposeIntermediateTensorInfo(g)}if(c){let g=m;m=kx(r,m,c,o,f),r.disposeIntermediateTensorInfo(g)}return m}var SX={kernelName:Fs,backendName:"cpu",kernelFunc:IX};function TX(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:d,dataFormat:u,dilations:p,dimRoundingMode:h,activation:c,leakyreluAlpha:f}=a,m=Z6({inputs:{x:n,filter:s},backend:r,attrs:{strides:l,pad:d,dataFormat:u,dilations:p,dimRoundingMode:h}});if(i){let g=m;m=Ih({inputs:{a:m,b:i},backend:r}),r.disposeIntermediateTensorInfo(g)}if(c){let g=m;m=kx(r,m,c,o,f),r.disposeIntermediateTensorInfo(g)}return m}var CX={kernelName:Ms,backendName:"cpu",kernelFunc:TX};function NX(e){let{inputs:t,backend:r}=e,{params:a,indices:n}=t,s=w.sizeFromShape(a.shape),i=n.shape,o=i[i.length-1],[l,d,u,p]=N.prepareAndValidate(a,n);if(d===0)return r.makeTensorInfo(l,a.dtype,[]);let h=r.data.get(n.dataId).values,c=r.bufferSync(a),f=c6(h,c,a.dtype,d,o,u,p,a.shape,s);return r.makeTensorInfo(l,a.dtype,f.values)}var EX={kernelName:Vo,backendName:"cpu",kernelFunc:NX};function RX(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,indices:s}=t,{axis:i,batchDims:o}=a;Ne([n,s],"gatherV2");let l=w.parseAxisParam(i,n.shape)[0],d=r.data.get(s.dataId).values,u=n.shape[l];for(let b=0;b<d.length;++b){let v=d[b];w.assert(v<=u-1&&v>=0,()=>`GatherV2: the index value ${v} is not in [0, ${u-1}]`)}let p=o;o==null&&(p=0);let h=w.sizeFromShape(s.shape),c=N.segment_util.collectGatherOpShapeInfo(n,s,l,p),f=$t({inputs:{x:n},backend:r,attrs:{shape:[c.batchSize,c.outerSize,c.dimSize,c.sliceSize]}}),m=$t({inputs:{x:s},backend:r,attrs:{shape:[c.batchSize,h/c.batchSize]}}),g=[c.batchSize,c.outerSize,h/c.batchSize,c.sliceSize],y=r.bufferSync(m),A=r.bufferSync(f),x=f6(A,y,g);return r.disposeIntermediateTensorInfo(f),r.disposeIntermediateTensorInfo(m),r.makeTensorInfo(c.outputShape,x.dtype,x.values)}var FX={kernelName:Wo,backendName:"cpu",kernelFunc:RX};function MX(e){let{inputs:t,backend:r}=e,{input:a}=t,n=w.sizeFromShape(a.shape),s=a.shape[a.shape.length-1],i=n/s,o=$t({inputs:{x:a},backend:r,attrs:{shape:[i,s]}}),l=Y6(o,!0,r),d=$t({inputs:{x:l},backend:r,attrs:{shape:a.shape}});return r.disposeIntermediateTensorInfo(o),r.disposeIntermediateTensorInfo(l),d}var $X={kernelName:Lf,backendName:"cpu",kernelFunc:MX},PX=gt(_u,e=>Number.isFinite(e)?1:0,"bool"),OX={kernelName:_u,backendName:"cpu",kernelFunc:PX},zX=gt(Lu,e=>Math.abs(e)===1/0?1:0,"bool"),DX={kernelName:Lu,backendName:"cpu",kernelFunc:zX},_X=gt(Bu,e=>Number.isNaN(e)?1:0,"bool"),LX={kernelName:Bu,backendName:"cpu",kernelFunc:_X};function BX(e){let{backend:t,attrs:r}=e,{start:a,stop:n,num:s}=r,i=x6(a,n,s);return t.makeTensorInfo([i.length],"float32",i)}var WX={kernelName:Bf,backendName:"cpu",kernelFunc:BX},VX=gt(Wu,e=>Math.log1p(e)),UX={kernelName:Wu,backendName:"cpu",kernelFunc:VX},GX=Zt((e,t)=>e&&t),jX=mr(Ho,GX,null,"bool"),HX={kernelName:Ho,backendName:"cpu",kernelFunc:jX},qX=gt(Vu,e=>e?0:1,"bool"),KX={kernelName:Vu,backendName:"cpu",kernelFunc:qX},XX=Zt((e,t)=>e||t),ZX=mr(jp,XX,null,"bool"),YX={kernelName:jp,backendName:"cpu",kernelFunc:ZX};function JX(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=a;Ne(n,"LRN");let d=n.shape[3],u=d-1,p=r.data.get(n.dataId).values,h=w.sizeFromShape(n.shape),c=new Float32Array(h);function f(m){let g=m%d,y=m-g+Math.max(0,g-s),A=m-g+Math.min(g+s,u),x=0;for(;y<=A;y++){let b=p[y];x+=b*b}return x}for(let m=0;m<h;m++){let g=f(m),y=p[m]*Math.pow(i+o*g,-l);c[m]=y}return r.makeTensorInfo(n.shape,n.dtype,c)}var QX={kernelName:Hp,backendName:"cpu",kernelFunc:JX};function eZ(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,y:s,dy:i}=t,{depthRadius:o,bias:l,alpha:d,beta:u}=a;Ne(i,"LRNGrad");let p=w.sizeFromShape(i.shape),h=i.shape[3],c=r.data.get(i.dataId).values,f=r.data.get(n.dataId).values,m=r.data.get(s.dataId).values,g=new Float32Array(p),y=p;for(let A=0;A<y;A++){let x=A%h,b=A-x+Math.max(0,x-o),v=A-x+Math.min(h,x+o+1),C=0;for(let T=b;T<v;T++)C+=Math.pow(f[T],2);C=d*C+l;for(let T=b;T<v;T++){let E=-2*d*u*f[T]*m[A]/C;A===T&&(E+=Math.pow(C,-u)),E*=c[A],g[T]+=E}}return r.makeTensorInfo(i.shape,n.dtype,g)}var tZ={kernelName:Wf,backendName:"cpu",kernelFunc:eZ};function J6(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{reductionIndices:s,keepDims:i}=a,o=r,l=n.shape,d=l.length,u=w.parseAxisParam(s,l),p=u,h=N.getAxesPermutation(p,d),c=o.data.get(n.dataId).values;if(h!=null){let b=new Array(d);for(let v=0;v<b.length;v++)b[v]=l[h[v]];c=xx(c,l,n.dtype,h,b),p=N.getInnerMostAxes(p.length,d),l=b}Ne(n,"max"),N.assertAxesAreInnerMostDims("max",p,d);let[f,m]=N.computeOutAndReduceShapes(l,p),g=w.sizeFromShape(m),y=v6(c,g,f,n.dtype),A=o.write(y,f,n.dtype),x=f;return i&&(x=N.expandShapeToKeepDim(f,u)),{dataId:A,shape:x,dtype:n.dtype}}var rZ={kernelName:hi,backendName:"cpu",kernelFunc:J6};function aZ(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t;Ne(n,"maxPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,d=1;w.assert(N.eitherStridesOrDilationsAreOne(i,d),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${d}'`);let u=N.computePool2DInfo(n.shape,s,i,d,o,l),p;if(u.filterWidth===1&&u.filterHeight===1&&w.arraysEqual(u.inShape,u.outShape))p=En({inputs:{x:n},backend:r});else{let h=r.data.get(n.dataId).values,c=w.computeStrides(n.shape),f=Ix(h,n.shape,n.dtype,c,u,"max");p=r.makeTensorInfo(u.outShape,n.dtype,f.values)}return p}var nZ={kernelName:fi,backendName:"cpu",kernelFunc:aZ};function sZ(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:d}=a;Ne(n,"maxPool3d");let u=N.computePool3DInfo(n.shape,s,i,1,o,l,d),p=r.data.get(n.dataId).values,h=K6(p,n.shape,n.dtype,w.computeStrides(n.shape),u,"max");return r.makeTensorInfo(h.shape,"float32",h.values)}var iZ={kernelName:qp,backendName:"cpu",kernelFunc:sZ};function oZ(e){let{inputs:t,backend:r,attrs:a}=e,{dy:n,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:d}=a;Ne([n,s],"maxPool3DGrad");let u=N.computePool3DInfo(s.shape,i,o,1,l,d),p=r.bufferSync(s),h=Zq(p,u),c=u.strideDepth,f=u.strideHeight,m=u.strideWidth,g=u.dilationDepth,y=u.dilationHeight,A=u.dilationWidth,x=u.effectiveFilterDepth,b=u.effectiveFilterHeight,v=u.effectiveFilterWidth,C=x-1-u.padInfo.front,T=v-1-u.padInfo.left,E=b-1-u.padInfo.top,R=Le(s.shape,"float32"),z=r.bufferSync(n);for(let M=0;M<u.batchSize;++M)for(let I=0;I<u.inChannels;++I)for(let D=0;D<u.inDepth;++D)for(let O=0;O<u.inHeight;++O)for(let j=0;j<u.inWidth;++j){let X=D-C,_=O-E,K=j-T,W=0;for(let ee=0;ee<x;ee+=g){let Q=(X+ee)/c;if(!(Q<0||Q>=u.outDepth||Math.floor(Q)!==Q))for(let ne=0;ne<b;ne+=y){let Z=(_+ne)/f;if(!(Z<0||Z>=u.outHeight||Math.floor(Z)!==Z))for(let ae=0;ae<v;ae+=A){let ie=(K+ae)/m;if(ie<0||ie>=u.outWidth||Math.floor(ie)!==ie)continue;let xe=x*b*v-1-h.get(M,Q,Z,ie,I),be=ee*b*v+ne*v+ae,Te=xe===be?1:0;Te!==0&&(W+=z.get(M,Q,Z,ie,I)*Te)}}}R.set(W,M,D,O,j,I)}return r.makeTensorInfo(R.shape,R.dtype,R.values)}var lZ={kernelName:Uf,backendName:"cpu",kernelFunc:oZ};function uZ(e){let{inputs:t,backend:r,attrs:a}=e,{dy:n,input:s,output:i}=t,o=s;Ne([s,i],"maxPoolGrad");let{filterSize:l,strides:d,pad:u,dimRoundingMode:p}=a,h=N.computePool2DInfo(o.shape,l,d,1,u,p),c=r.data.get(o.dataId).values,f=Le(h.outShape,o.dtype,q6(c,o.shape,o.dtype,h).values),m=h.strideHeight,g=h.strideWidth,y=h.dilationHeight,A=h.dilationWidth,x=h.effectiveFilterHeight,b=h.effectiveFilterWidth,v=b-1-h.padInfo.left,C=x-1-h.padInfo.top,T=Le(o.shape,"float32"),E=r.data.get(n.dataId).values,R=Le(n.shape,"float32",E);for(let z=0;z<h.batchSize;++z)for(let M=0;M<h.inChannels;++M)for(let I=0;I<h.inHeight;++I)for(let D=0;D<h.inWidth;++D){let O=I-C,j=D-v,X=0;for(let _=0;_<x;_+=y){let K=(O+_)/m;if(!(K<0||K>=h.outHeight||Math.floor(K)!==K))for(let W=0;W<b;W+=A){let ee=(j+W)/g;if(ee<0||ee>=h.outWidth||Math.floor(ee)!==ee)continue;let Q=x*b-1-f.get(z,K,ee,M),ne=_*b+W,Z=Q===ne?1:0;Z!==0&&(X+=R.get(z,K,ee,M)*Z)}}T.set(X,z,I,D,M)}return r.makeTensorInfo(T.shape,T.dtype,T.values)}var dZ={kernelName:Vf,backendName:"cpu",kernelFunc:uZ};function pZ(e,t,r,a,n){let s=w.computeStrides(t),i=Ix(e,t,r,s,n,"max"),o=q6(e,t,r,n,!0,a);return[i.values,o.values]}var hZ={kernelName:Gf,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{x:a}=e,{filterSize:n,strides:s,pad:i,includeBatchInIndex:o}=t,l=r;Ne(a,"MaxPoolWithArgmax");let d=l.data.get(a.dataId).values,u=N.computePool2DInfo(a.shape,n,s,[1,1],i),[p,h]=pZ(d,a.shape,a.dtype,o,u),c=l.write(p,u.outShape,a.dtype),f=l.write(h,u.outShape,a.dtype);return[{dataId:c,shape:u.outShape,dtype:a.dtype},{dataId:f,shape:u.outShape,dtype:"int32"}]}};function cZ(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{axis:s,keepDims:i}=a,o=w.parseAxisParam(s,n.shape),l=N.computeOutAndReduceShapes(n.shape,o)[1],d=w.sizeFromShape(l),u=[],p=r.makeTensorInfo([],"float32",new Float32Array([d]));u.push(p);let h=Us({inputs:{x:n},backend:r,attrs:{dtype:"float32"}});u.push(h);let c=Sx({inputs:{a:h,b:p},backend:r});u.push(c);let f=Sh({inputs:{x:c},backend:r,attrs:{axis:s,keepDims:i}});return u.forEach(m=>r.disposeIntermediateTensorInfo(m)),f}var fZ={kernelName:mi,backendName:"cpu",kernelFunc:cZ};function mZ(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{axis:s,keepDims:i}=a;Ne(n,"min");let o=w.parseAxisParam(s,n.shape),l=o,d=N.getAxesPermutation(l,n.shape.length),u=n;d!=null&&(u=Ma({inputs:{x:n},backend:r,attrs:{perm:d}}),l=N.getInnerMostAxes(l.length,n.shape.length)),N.assertAxesAreInnerMostDims("min",l,u.shape.length);let[p,h]=N.computeOutAndReduceShapes(u.shape,l),c=w.sizeFromShape(h),f=w.makeZerosTypedArray(w.sizeFromShape(p),u.dtype),m=r.data.get(u.dataId).values;for(let y=0;y<f.length;++y){let A=y*c,x=m[A];for(let b=0;b<c;++b){let v=m[A+b];(Number.isNaN(v)||v<x)&&(x=v)}f[y]=x}d!=null&&r.disposeIntermediateTensorInfo(u);let g=r.makeTensorInfo(p,u.dtype,f);if(i){let y=N.expandShapeToKeepDim(p,o),A=$t({inputs:{x:g},backend:r,attrs:{shape:y}});return r.disposeIntermediateTensorInfo(g),A}return g}var gZ={kernelName:gi,backendName:"cpu",kernelFunc:mZ};function yZ(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{paddings:s,mode:i}=a;Ne(n,"mirrorPad");let o=s.map((A,x)=>A[0]+n.shape[x]+A[1]),l=s.map(A=>A[0]),d=s.map((A,x)=>A[0]+n.shape[x]),u=i==="reflect"?0:1,p=r.data.get(n.dataId).values,h=n.shape.length,c=w.computeStrides(n.shape),f=w.sizeFromShape(o),m=o.length,g=w.computeStrides(o),y=w.getTypedArrayFromDType(n.dtype,f);for(let A=0;A<f;A++){let x=w.indexToLoc(A,m,g);for(let v=0;v<m;v++)x[v]<l[v]?x[v]=l[v]*2-x[v]-u:x[v]>=d[v]&&(x[v]=(d[v]-1)*2-x[v]+u);x=x.map((v,C)=>v-l[C]);let b=w.locToIndex(x,h,c);y[A]=p[b]}return{dataId:r.write(y,o,n.dtype),shape:o,dtype:n.dtype}}var AZ={kernelName:Ai,backendName:"cpu",kernelFunc:yZ},xZ=Zt((e,t)=>{let r=e%t;return e<0&&t<0||e>=0&&t>=0?r:(r+t)%t}),bZ=mr(Uu,xZ),vZ={kernelName:Uu,backendName:"cpu",kernelFunc:bZ},wZ=Eo(kf());function Q6(e){let{inputs:t,backend:r,attrs:a}=e,{logits:n}=t,{dim:s}=a,i=n.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=w.parseAxisParam([o],n.shape),d=J6({inputs:{x:n},backend:r,attrs:{reductionIndices:l,keepDims:!1}}),u=N.expandShapeToKeepDim(d.shape,l),p=$t({inputs:{x:d},backend:r,attrs:{shape:u}}),h=wx({inputs:{a:n,b:p},backend:r}),c=d6({inputs:{x:h},backend:r}),f=Sh({inputs:{x:c},backend:r,attrs:{axis:l,keepDims:!1}}),m=$t({inputs:{x:f},backend:r,attrs:{shape:u}}),g=Sx({inputs:{a:c,b:m},backend:r});return r.disposeIntermediateTensorInfo(d),r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(f),r.disposeIntermediateTensorInfo(m),g}var kZ={kernelName:Fi,backendName:"cpu",kernelFunc:Q6};function IZ(e){let{inputs:t,backend:r,attrs:a}=e,{logits:n}=t,{numSamples:s,seed:i,normalized:o}=a;Ne(n,"multinomial");let l=o?n:Q6({inputs:{logits:n},backend:r,attrs:{dim:-1}}),d=l.shape[0],u=l.shape[1],p=r.data.get(l.dataId).values,h=[d,s],c=w.makeZerosTypedArray(w.sizeFromShape(h),"int32");for(let f=0;f<d;++f){let m=f*u,g=new Float32Array(u-1);g[0]=p[m];for(let x=1;x<g.length;++x)g[x]=g[x-1]+p[m+x];let y=wZ.alea(i.toString()),A=f*s;for(let x=0;x<s;++x){let b=y();c[A+x]=g.length;for(let v=0;v<g.length;v++)if(b<g[v]){c[A+x]=v;break}}}return o||r.disposeIntermediateTensorInfo(l),r.makeTensorInfo(h,"int32",c)}var SZ={kernelName:jf,backendName:"cpu",kernelFunc:IZ},TZ=Ha.nonMaxSuppressionV3Impl;function CZ(e){let{inputs:t,backend:r,attrs:a}=e,{boxes:n,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=a;Ne(n,"NonMaxSuppression");let d=r.data.get(n.dataId).values,u=r.data.get(s.dataId).values,{selectedIndices:p}=TZ(d,u,i,o,l);return r.makeTensorInfo([p.length],"int32",new Int32Array(p))}var NZ={kernelName:Xo,backendName:"cpu",kernelFunc:CZ},EZ=Ha.nonMaxSuppressionV4Impl;function RZ(e){let{inputs:t,backend:r,attrs:a}=e,{boxes:n,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:d}=a;Ne(n,"NonMaxSuppressionPadded");let u=r.data.get(n.dataId).values,p=r.data.get(s.dataId).values,{selectedIndices:h,validOutputs:c}=EZ(u,p,i,o,l,d);return[r.makeTensorInfo([h.length],"int32",new Int32Array(h)),r.makeTensorInfo([],"int32",new Int32Array([c]))]}var FZ={kernelName:Gu,backendName:"cpu",kernelFunc:RZ},MZ=Ha.nonMaxSuppressionV5Impl;function $Z(e){let{inputs:t,backend:r,attrs:a}=e,{boxes:n,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:d}=a;Ne(n,"NonMaxSuppressionWithScore");let u=r.data.get(n.dataId).values,p=r.data.get(s.dataId).values,h=i,c=o,f=l,m=d,{selectedIndices:g,selectedScores:y}=MZ(u,p,h,c,f,m);return[r.makeTensorInfo([g.length],"int32",new Int32Array(g)),r.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var PZ={kernelName:Zo,backendName:"cpu",kernelFunc:$Z};function OZ(e){let{inputs:t,backend:r,attrs:a}=e,{indices:n}=t,{depth:s,onValue:i,offValue:o}=a;Ne(n,"oneHot");let l=w.sizeFromShape(n.shape),d=new Float32Array(l*s);d.fill(o);let u=r.data.get(n.dataId).values;for(let p=0;p<l;++p)u[p]>=0&&u[p]<s&&(d[p*s+u[p]]=i);return r.makeTensorInfo([...n.shape,s],"int32",d)}var zZ={kernelName:Jo,backendName:"cpu",kernelFunc:OZ};function yf(e){let{inputs:t,backend:r}=e,{x:a}=t;if(a.dtype==="string")throw new Error("zerosLike is not supported for string tensors");if(a.dtype==="complex64"){let n=Io({inputs:{input:a},backend:r}),s=yf({inputs:{x:n},backend:r}),i=bu({inputs:{input:a},backend:r}),o=yf({inputs:{x:i},backend:r}),l=ua({inputs:{real:s,imag:o},backend:r});return r.disposeIntermediateTensorInfo(n),r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(o),l}else return Tx({backend:r,attrs:{shape:a.shape,value:0,dtype:a.dtype}})}var DZ={kernelName:ml,backendName:"cpu",kernelFunc:yf};function eI(e){let{inputs:t,backend:r}=e,{x:a}=t;if(a.dtype==="string")throw new Error("onesLike is not supported for string tensors");if(a.dtype==="complex64"){let n=Io({inputs:{input:a},backend:r}),s=eI({inputs:{x:n},backend:r}),i=bu({inputs:{input:a},backend:r}),o=yf({inputs:{x:i},backend:r}),l=ua({inputs:{real:s,imag:o},backend:r});return r.disposeIntermediateTensorInfo(n),r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(o),l}else return Tx({backend:r,attrs:{shape:a.shape,value:1,dtype:a.dtype}})}var _Z={kernelName:Yo,backendName:"cpu",kernelFunc:eI};function tI(e){let{inputs:t,backend:r,attrs:a}=e,{axis:n}=a;if(t.length===1)return gf({inputs:{input:t[0]},backend:r,attrs:{dim:n}});let s=t[0].shape,i=t[0].dtype;t.forEach(u=>{w.assertShapesMatch(s,u.shape,"All tensors passed to stack must have matching shapes"),w.assert(i===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(u=>{let p=gf({inputs:{input:u},backend:r,attrs:{dim:n}});return o.push(p),p}),d=vu({inputs:l,backend:r,attrs:{axis:n}});return o.forEach(u=>r.disposeIntermediateTensorInfo(u)),d}var LZ={kernelName:Qo,backendName:"cpu",kernelFunc:tI};function BZ(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{paddings:s,constantValue:i}=a;Ne(n,"pad");let o=s.map((y,A)=>y[0]+n.shape[A]+y[1]),l=s.map(y=>y[0]),d=r.data.get(n.dataId).values,u=w.sizeFromShape(n.shape),p=n.shape.length,h=w.computeStrides(n.shape),c=w.sizeFromShape(o),f=o.length,m=w.computeStrides(o),g=w.getTypedArrayFromDType(n.dtype,c);i!==0&&g.fill(i);for(let y=0;y<u;y++){let A=w.indexToLoc(y,p,h).map((b,v)=>b+l[v]),x=w.locToIndex(A,f,m);g[x]=d[y]}return{dataId:r.write(g,o,n.dtype),shape:o,dtype:n.dtype}}var rI={kernelName:bi,backendName:"cpu",kernelFunc:BZ},WZ=Zt((e,t)=>Math.pow(e,t)),VZ=mr(vi,WZ),UZ={kernelName:vi,backendName:"cpu",kernelFunc:VZ};function GZ(e){let{backend:t,attrs:r}=e,{start:a,stop:n,dtype:s,step:i}=r,o=bx(a,n,i,s);return t.makeTensorInfo([o.length],s,o)}var jZ={kernelName:ju,backendName:"cpu",kernelFunc:GZ},HZ=gt(Hu,e=>1/e),qZ={kernelName:Hu,backendName:"cpu",kernelFunc:HZ};function KZ(e){let{inputs:t,backend:r,attrs:a}=e,{images:n}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a;Ne(n,"resizeBilinear");let l=w.computeStrides(n.shape),[d,u]=o,[p,h,c,f]=n.shape,m=r.data.get(n.dataId).values,g=new Float32Array(w.sizeFromShape([p,d,u,f])),y=[s&&d>1?h-1:h,s&&u>1?c-1:c],A=[s&&d>1?d-1:d,s&&u>1?u-1:u],x=0,b=y[0]/A[0],v=y[1]/A[1];for(let C=0;C<p;C++)for(let T=0;T<d;T++){let E;i?E=b*(T+.5)-.5:E=b*T;let R=Math.max(0,Math.floor(E)),z=E-R,M=Math.min(h-1,Math.ceil(E)),I=C*l[0]+R*l[1],D=C*l[0]+M*l[1];for(let O=0;O<u;O++){let j;i?j=v*(O+.5)-.5:j=v*O;let X=Math.max(0,Math.floor(j)),_=j-X,K=Math.min(c-1,Math.ceil(j)),W=I+X*l[2],ee=D+X*l[2],Q=I+K*l[2],ne=D+K*l[2];for(let Z=0;Z<f;Z++){let ae=m[W+Z],ie=m[ee+Z],xe=m[Q+Z],be=m[ne+Z],Te=ae+(xe-ae)*_,Re=ie+(be-ie)*_,$e=Te+(Re-Te)*z;g[x++]=$e}}}return r.makeTensorInfo([p,d,u,f],"float32",g)}var XZ={kernelName:Ii,backendName:"cpu",kernelFunc:KZ};function ZZ(e){let{inputs:t,backend:r,attrs:a}=e,{images:n,dy:s}=t,{alignCorners:i}=a;Ne([s,n],"resizeBilinearGrad");let o=w.computeStrides(n.shape),[l,d,u,p]=n.shape,[,h,c]=s.shape,f=new Float32Array(l*d*u*p),m=[i&&h>1?d-1:d,i&&c>1?u-1:u],g=[i&&h>1?h-1:h,i&&c>1?c-1:c],y=m[0]/g[0],A=m[1]/g[1],x=r.data.get(s.dataId).values,b=0;for(let v=0;v<l;v++){let C=v*o[0];for(let T=0;T<h;T++){let E=T*y,R=Math.floor(E),z=Math.min(Math.ceil(E),d-1),M=C+R*o[1],I=C+z*o[1],D=E-R,O=1-D;for(let j=0;j<c;j++){let X=j*A,_=Math.floor(X),K=Math.min(Math.ceil(X),u-1),W=X-_,ee=1-W,Q=M+_*o[2],ne=M+K*o[2],Z=I+_*o[2],ae=I+K*o[2],ie=O*ee,xe=O*W,be=D*ee,Te=D*W;for(let Re=0;Re<p;Re++){let $e=x[b++];f[Q+Re]+=$e*ie,f[ne+Re]+=$e*xe,f[Z+Re]+=$e*be,f[ae+Re]+=$e*Te}}}}return r.makeTensorInfo([l,u,d,p],"float32",f)}var YZ={kernelName:qf,backendName:"cpu",kernelFunc:ZZ};function JZ(e){let{inputs:t,backend:r,attrs:a}=e,{images:n}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a;Ne(n,"resizeNearestNeighbor");let l=w.computeStrides(n.shape),[d,u]=o,[p,h,c,f]=n.shape,m=r.data.get(n.dataId).values,g=new Float32Array(p*d*u*f),y=[s&&d>1?h-1:h,s&&u>1?c-1:c],A=[s&&d>1?d-1:d,s&&u>1?u-1:u],x=y[0]/A[0],b=y[1]/A[1],v=0;for(let C=0;C<p;C++){let T=C*l[0];for(let E=0;E<d;E++){let R=i?x*(E+.5):x*E,z=Math.min(h-1,s?Math.round(R):Math.floor(R));i&&(z=Math.max(0,z));let M=T+z*l[1];for(let I=0;I<u;I++){let D=i?b*(I+.5):b*I,O=Math.min(c-1,s?Math.round(D):Math.floor(D));i&&(O=Math.max(0,O));let j=M+O*l[2];for(let X=0;X<f;X++){let _=m[j+X];g[v++]=_}}}}return r.makeTensorInfo([p,d,u,f],n.dtype,g)}var QZ={kernelName:qu,backendName:"cpu",kernelFunc:JZ};function eY(e){let{inputs:t,backend:r,attrs:a}=e,{images:n,dy:s}=t,{alignCorners:i}=a;Ne([s,n],"resizeNearestNeighborGrad");let o=w.computeStrides(n.shape),l=w.computeStrides(s.shape),[d,u,p,h]=n.shape,[,c,f]=s.shape,m=new Float32Array(d*u*p*h),g=r.data.get(s.dataId).values,y=[i&&c>1?u-1:u,i&&f>1?p-1:p],A=[i&&c>1?c-1:c,i&&f>1?f-1:f],x=y[0]/A[0],b=y[1]/A[1],v=1/x,C=1/b,T=Math.ceil(v)*2+2,E=Math.ceil(C)*2+2;for(let R=0;R<d;R++){let z=R*o[0];for(let M=0;M<u;M++){let I=z+M*o[1],D=Math.floor(M*v),O=Math.floor(D-T/2);for(let j=0;j<p;j++){let X=I+j*o[2],_=Math.floor(j*C),K=Math.floor(_-E/2);for(let W=0;W<h;W++){let ee=0;for(let Q=0;Q<T;Q++){let ne=Q+O;if(ne<0||ne>=c)continue;let Z=z+ne*l[1],ae=ne*x,ie=Math.min(u-1,i?Math.round(ae):Math.floor(ae));if(M===ie)for(let xe=0;xe<E;xe++){let be=xe+K;if(be<0||be>=f)continue;let Te=Z+be*l[2],Re=be*b,$e=Math.min(p-1,i?Math.round(Re):Math.floor(Re));j===$e&&(ee+=g[Te+W])}}m[X+W]=ee}}}}return r.makeTensorInfo(n.shape,n.dtype,m)}var tY={kernelName:Hf,backendName:"cpu",kernelFunc:eY};function rY(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{dims:s}=a;Ne(n,"reverse");let i=n.shape.length,o=w.parseAxisParam(s,n.shape);if(i===0)return En({inputs:{x:n},backend:r});let l=new tr(n.shape,n.dtype),d=r.bufferSync(n);for(let u=0;u<l.size;u++){let p=l.indexToLoc(u),h=p.slice();o.forEach(c=>h[c]=n.shape[c]-1-h[c]),l.set(d.get(...h),...p)}return r.makeTensorInfo(l.shape,l.dtype,l.values)}var aY={kernelName:rl,backendName:"cpu",kernelFunc:rY},nY={kernelName:gl,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{image:a}=e,{radians:n,fillValue:s,center:i}=t,o=r,l=w.getTypedArrayFromDType(a.dtype,w.sizeFromShape(a.shape)),[d,u,p,h]=a.shape,[c,f]=N.getImageCenter(i,u,p),m=255,g=Math.sin(n),y=Math.cos(n),A=o.data.get(a.dataId).values;for(let x=0;x<d;x++){let b=x*p*u*h;for(let v=0;v<u;v++){let C=v*(p*h);for(let T=0;T<p;T++){let E=T*h;for(let R=0;R<h;R++){let z=[d,v,T,R],M=z[2],I=z[1],D=(M-c)*y-(I-f)*g,O=(M-c)*g+(I-f)*y;D=Math.round(D+c),O=Math.round(O+f);let j=s;if(typeof s!="number"&&(R===3?j=m:j=s[R]),D>=0&&D<p&&O>=0&&O<u){let _=O*(p*h),K=D*h,W=b+_+K+R;j=A[W]}let X=b+C+E+R;l[X]=j}}}}return{dataId:o.write(l,a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}},sY=gt(al,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}),iY={kernelName:al,backendName:"cpu",kernelFunc:sY};function aI(e,t,r,a,n,s,i,o,l,d){let u=[a/n,n],p=e.values,h=t.values;if(a===0)return Le(r,t.dtype);let c=Le(u,t.dtype);c.values.fill(l);for(let f=0;f<s;f++){let m=[],g=0;for(let y=0;y<i;y++){let A=p[f*i+y];m.push(A),g+=A*o[y]}if(g<0||g>=a/n)throw new Error(`Invalid indices: ${m} does not index into ${r}`);for(let y=0;y<n;y++)d?c.values[g*n+y]+=h[f*n+y]:c.values[g*n+y]=t.rank===0?h[0]:h[f*n+y]}return c}function oY(e){let{inputs:t,backend:r,attrs:a}=e,{indices:n,updates:s}=t,{shape:i}=a,{sliceRank:o,numUpdates:l,sliceSize:d,strides:u,outputSize:p}=N.calculateShapes(s,n,i),h=!0,c=r.bufferSync(n),f=r.bufferSync(s),m=aI(c,f,i,p,d,l,o,u,0,h);return r.makeTensorInfo(i,m.dtype,m.values)}var lY={kernelName:nl,backendName:"cpu",kernelFunc:oY};function uY(e){let{inputs:t,backend:r}=e,{condition:a,t:n,e:s}=t;Ne([a,n,s],"select");let i=a.shape.length,o=r.data.get(a.dataId).values,l=r.data.get(n.dataId).values,d=r.data.get(s.dataId).values,u=Or(n.dtype,s.dtype),p=w.makeZerosTypedArray(w.sizeFromShape(n.shape),u),h=0,c=i===0||i>1||n.shape.length===1?1:w.sizeFromShape(n.shape.slice(1));for(let f=0;f<o.length;f++)for(let m=0;m<c;m++)o[f]===1?p[h++]=l[f]:p[h++]=d[f];return r.makeTensorInfo(n.shape,u,p)}var dY={kernelName:sl,backendName:"cpu",kernelFunc:uY},pY=N.SELU_SCALEALPHA,hY=N.SELU_SCALE,cY=gt(Ku,e=>e>=0?hY*e:pY*(Math.exp(e)-1)),fY={kernelName:Ku,backendName:"cpu",kernelFunc:cY},mY=gt(Xu,e=>e<0?-1:e>0?1:0),gY={kernelName:Xu,backendName:"cpu",kernelFunc:mY},yY=gt(Ci,e=>Math.sin(e)),AY={kernelName:Ci,backendName:"cpu",kernelFunc:yY},xY=gt(ol,e=>Math.sinh(e)),bY={kernelName:ol,backendName:"cpu",kernelFunc:xY},vY=11920928955078125e-23,B3=Math.log(vY)+2,wY=gt(Zu,e=>{let t=e>-B3,r=e<B3,a=Math.exp(e),n;return r?n=a:t?n=e:n=Math.log(1+a),n}),kY={kernelName:Zu,backendName:"cpu",kernelFunc:wY};function IY(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{blockShape:s,paddings:i}=a;Ne([n],"spaceToBatchND");let o=w.sizeFromShape(s),l=[[0,0]];l.push(...i);for(let g=1+s.length;g<n.shape.length;++g)l.push([0,0]);let d=rI.kernelFunc({inputs:{x:n},backend:r,attrs:{paddings:l,constantValue:0}}),u=N.getReshaped(d.shape,s,o,!1),p=N.getPermuted(u.length,s.length,!1),h=N.getReshapedPermuted(d.shape,s,o,!1),c=$t({inputs:{x:d},backend:r,attrs:{shape:u}}),f=Ma({inputs:{x:c},backend:r,attrs:{perm:p}}),m=$t({inputs:{x:f},backend:r,attrs:{shape:h}});return r.disposeIntermediateTensorInfo(d),r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(f),m}var SY={kernelName:ll,backendName:"cpu",kernelFunc:IY};function TY(e){let{inputs:t,backend:r}=e,{indices:a,values:n,denseShape:s,defaultValue:i}=t;if(s.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
|
|
${s.shape}`);if(a.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
|
|
${a.shape}`);if(n.shape.length!==1)throw new Error(`Values must be a vector, saw:
|
|
${n.shape}`);if(i.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
|
|
${i.shape}`);let o=r.data.get(a.dataId).values,l=r.data.get(n.dataId).values,d=r.data.get(s.dataId).values,u=r.data.get(i.dataId).values[0],[p,h,c,f,m]=E6(o,a.shape,a.dtype,l,n.dtype,d,u);return[r.makeTensorInfo(h,a.dtype,p),r.makeTensorInfo([h[0]],n.dtype,c),r.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),r.makeTensorInfo([m.length],a.dtype,new Int32Array(m))]}var CY={kernelName:Xp,backendName:"cpu",kernelFunc:TY};function NY(e){let{inputs:t,backend:r}=e,{inputIndices:a,inputShape:n,newShape:s}=t;if(a.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
|
|
${a.shape}`);if(n.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
|
|
${n.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=Array.from(r.data.get(n.dataId).values),o=r.data.get(a.dataId).values,l=Array.from(r.data.get(s.dataId).values),[d,u,p]=R6(o,a.shape,a.dtype,i,l);return[r.makeTensorInfo(u,a.dtype,d),r.makeTensorInfo([p.length],s.dtype,new Int32Array(p))]}var EY={kernelName:Yu,backendName:"cpu",kernelFunc:NY};function RY(e){let{inputs:t,backend:r}=e,{data:a,indices:n,segmentIds:s}=t;if(a.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(n.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${n.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${s.shape}`);if(n.shape[0]!==s.shape[0])throw new Error("segmentIds and indices should have same size.");let i=r.data.get(a.dataId).values,o=r.data.get(n.dataId).values,l=r.data.get(s.dataId).values,[d,u]=vx(i,a.shape,a.dtype,o,l,!0);return r.makeTensorInfo(u,a.dtype,d)}var FY={kernelName:Zp,backendName:"cpu",kernelFunc:RY};function MY(e){let{inputs:t,backend:r}=e,{data:a,indices:n,segmentIds:s}=t;if(a.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(n.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${n.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${s.shape}`);if(n.shape[0]!==s.shape[0])throw new Error("segmentIds and indices should have same size.");let i=r.data.get(a.dataId).values,o=r.data.get(n.dataId).values,l=r.data.get(s.dataId).values,[d,u]=vx(i,a.shape,a.dtype,o,l);return r.makeTensorInfo(u,a.dtype,d)}var $Y={kernelName:Yp,backendName:"cpu",kernelFunc:MY};function PY(e){let{inputs:t,backend:r,attrs:a}=e,{sparseIndices:n,sparseValues:s,defaultValue:i}=t,{outputShape:o}=a,{sliceRank:l,numUpdates:d,sliceSize:u,strides:p,outputSize:h}=N.calculateShapes(s,n,o),c=!1,f=r.bufferSync(n),m=r.bufferSync(s),g=r.data.get(i.dataId).values[0],y=aI(f,m,o,h,u,d,l,p,g,c);return r.makeTensorInfo(o,y.dtype,y.values)}var OY={kernelName:Jp,backendName:"cpu",kernelFunc:PY};function zY(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{numOrSizeSplits:s,axis:i}=a,o=w.parseAxisParam(i,n.shape)[0],l=N.prepareSplitSize(n,s,o),d=new Array(n.shape.length).fill(0),u=n.shape.slice();return l.map(p=>{let h=[...u];h[o]=p;let c=So({inputs:{x:n},backend:r,attrs:{begin:d,size:h}});return d[o]+=p,c})}var DY={kernelName:ul,backendName:"cpu",kernelFunc:zY},_Y={kernelName:Ju,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{let{x:r}=e,a=t;Ne(r,"square");let n=a.data.get(r.dataId).values,s=new Float32Array(n.length);for(let i=0;i<n.length;++i){let o=n[i];s[i]=o*o}return{dataId:a.write(s,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},LY=gt(zi,(e,t)=>{let r=t;return isNaN(e)?NaN:e>0?1:r.alpha}),BY={kernelName:zi,backendName:"cpu",kernelFunc:LY};function WY(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:d,ellipsisMask:u,newAxisMask:p,shrinkAxisMask:h}=a;Ne(n,"stridedSlice");let{finalShapeSparse:c,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:A,end:x,strides:b}=Ot.sliceInfo(n.shape,s,i,o,l,d,u,p,h),v;if(m)v=$t({inputs:{x:n},backend:r,attrs:{shape:f}});else if(g||y){w.assert(n.shape.length>=1,()=>`Input must have rank at least 1, got: ${n.shape.length}`);let C=Ot.computeOutShape(A,x,b),T=So({inputs:{x:n},backend:r,attrs:{begin:A,size:C}});v=$t({inputs:{x:T},backend:r,attrs:{shape:f}}),r.disposeIntermediateTensorInfo(T)}else{let C=r.bufferSync(n),T=M6(c,C,b,A);v=r.makeTensorInfo(f,T.dtype,T.values)}return v}var VY={kernelName:dl,backendName:"cpu",kernelFunc:WY};function UY(e){let{inputs:t,backend:r,attrs:a}=e,{separator:n,nGramWidths:s,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:d}=a,{data:u,dataSplits:p}=t,h=r.data.get(u.dataId).values,c=r.data.get(p.dataId).values,[f,m]=$6(h,c,n,s,i,o,l,d);return[r.makeTensorInfo([f.length],"string",f),r.makeTensorInfo(p.shape,"int32",m)]}var GY={kernelName:Qp,backendName:"cpu",kernelFunc:UY};function jY(e){let{inputs:t,backend:r,attrs:a}=e,{skipEmpty:n}=a,{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=r.data.get(s.dataId).values,l=r.data.get(i.dataId).values[0],[d,u,p]=P6(o,l,n),h=u.length;return[r.makeTensorInfo([h,2],"int32",d),r.makeTensorInfo([h],"string",u),r.makeTensorInfo([2],"int32",new Int32Array(p))]}var HY={kernelName:Kf,backendName:"cpu",kernelFunc:jY};function qY(e){let{inputs:t,backend:r,attrs:a}=e,{numBuckets:n}=a,{input:s}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(n<=0)throw new Error("Number of buckets must be at least 1");let i=r.data.get(s.dataId).values,o=O6(i,n);return r.makeTensorInfo(s.shape,"int32",o)}var KY={kernelName:Xf,backendName:"cpu",kernelFunc:qY},XY=gt(pl,e=>Math.tan(e)),ZY={kernelName:pl,backendName:"cpu",kernelFunc:XY},YY=gt(Pi,e=>Math.tanh(e)),JY={kernelName:Pi,backendName:"cpu",kernelFunc:YY};function QY(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{reps:s}=a;Ne(n,"tile");let i=D6(r.bufferSync(n),s);return r.makeTensorInfo(i.shape,i.dtype,i.values)}var eJ={kernelName:Xn,backendName:"cpu",kernelFunc:QY};function tJ(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{k:s,sorted:i}=a;Ne(n,"topk");let o=r.data.get(n.dataId).values,[l,d]=L6(o,n.shape,n.dtype,s,i);return[r.makeTensorInfo(l.shape,l.dtype,l.values),r.makeTensorInfo(d.shape,d.dtype,d.values)]}var rJ={kernelName:hl,backendName:"cpu",kernelFunc:tJ};function aJ(e){let{inputs:t,attrs:r,backend:a}=e,{image:n,transforms:s}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:d}=r,[u,p,h,c]=n.shape,[f,m]=d!=null?d:[p,h],g=[u,f,m,c],y=w.computeStrides(n.shape),A=y[0],x=y[1],b=y[2],v=w.getTypedArrayFromDType(n.dtype,w.sizeFromShape(g));v.fill(l);let C=a.data.get(n.dataId).values,T=a.data.get(s.dataId).values;for(let E=0;E<u;++E){let R=s.shape[0]===1?T:T.subarray(E*8,E*8+8);for(let z=0;z<f;++z)for(let M=0;M<m;++M)for(let I=0;I<c;++I){let D,O=R[6]*M+R[7]*z+1;if(O===0)continue;let j=(R[0]*M+R[1]*z+R[2])/O,X=(R[3]*M+R[4]*z+R[5])/O,_=W3(j,h,o),K=W3(X,p,o);switch(i){case"nearest":D=uJ(C,p,h,A,x,b,E,K,_,I,l);break;case"bilinear":D=dJ(C,p,h,A,x,b,E,K,_,I,l);break;default:throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${i}`)}let W=E*A+z*x+M*b+I;v[W]=D}return a.makeTensorInfo(g,n.dtype,v)}return{dataId:a.write(v,g,n.dtype),shape:n.shape,dtype:n.dtype}}var nJ={kernelName:cl,backendName:"cpu",kernelFunc:aJ};function W3(e,t,r){switch(r){case"reflect":return sJ(e,t);case"wrap":return iJ(e,t);case"nearest":return lJ(e,t);case"constant":default:return oJ(e,t)}}function sJ(e,t){let r=e;if(r<0)if(t<=1)r=0;else{let a=2*t;r<a&&(r=a*Math.trunc(-r/a)+r),r=r<-t?r+a:-r-1}else if(r>t-1)if(t<=1)r=0;else{let a=2*t;r-=a*Math.trunc(r/a),r>=t&&(r=a-r-1)}return w.clamp(0,r,t-1)}function iJ(e,t){let r=e;if(r<0)if(t<=1)r=0;else{let a=t-1;r+=t*(Math.trunc(-r/a)+1)}else if(r>t-1)if(t<=1)r=0;else{let a=t-1;r-=t*Math.trunc(r/a)}return w.clamp(0,r,t-1)}function oJ(e,t){return e}function lJ(e,t){return w.clamp(0,e,t-1)}function cp(e,t,r,a,n,s,i,o,l,d,u){let p=i*a+o*n+l*s+d;return 0<=o&&o<t&&0<=l&&l<r?e[p]:u}function uJ(e,t,r,a,n,s,i,o,l,d,u){let p=Math.round(o),h=Math.round(l);return cp(e,t,r,a,n,s,i,p,h,d,u)}function dJ(e,t,r,a,n,s,i,o,l,d,u){let p=Math.floor(o),h=Math.floor(l),c=p+1,f=h+1,m=(f-l)*cp(e,t,r,a,n,s,i,p,h,d,u)+(l-h)*cp(e,t,r,a,n,s,i,p,f,d,u),g=(f-l)*cp(e,t,r,a,n,s,i,c,h,d,u)+(l-h)*cp(e,t,r,a,n,s,i,c,f,d,u);return(c-o)*m+(o-p)*g}function pJ(e){let{inputs:t,attrs:r,backend:a}=e,{axis:n}=r,{x:s}=t;Ne(s,"unique");let i=a.data.get(s.dataId).values,{outputValues:o,outputShape:l,indices:d}=B6(i,n,s.shape,s.dtype);return[a.makeTensorInfo(l,s.dtype,o),a.makeTensorInfo([d.length],"int32",d)]}var hJ={kernelName:Zf,backendName:"cpu",kernelFunc:pJ};function cJ(e){let{inputs:t,backend:r,attrs:a}=e,{value:n}=t,{axis:s}=a;s<0&&(s+=n.shape.length);let i=n.shape.length,o=n.shape[s],l=new Array(i-1),d=0;for(let c=0;c<i;c++)c!==s&&(l[d++]=n.shape[c]);let u=new Array(i).fill(0),p=n.shape.slice();p[s]=1;let h=new Array(o);for(let c=0;c<h.length;c++){u[s]=c;let f=So({inputs:{x:n},backend:r,attrs:{begin:u,size:p}});h[c]=$t({inputs:{x:f},backend:r,attrs:{shape:l}}),r.disposeIntermediateTensorInfo(f)}return h}var fJ={kernelName:fl,backendName:"cpu",kernelFunc:cJ};function mJ(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,segmentIds:s}=t,{numSegments:i}=a;Ne(n,"unsortedSegmentSum");let o=n.shape.length,l=s.shape.length,d=[],u=[],p=o-l,h=s;for(let f=0;f<p;++f){let m=gf({inputs:{input:h},backend:r,attrs:{dim:f+1}});h=m,u.push(m)}for(let f=0;f<i;++f){let m=w.createScalarValue(f,"int32"),g=r.makeTensorInfo([],"int32",m),y=l6({inputs:{a:g,b:h},backend:r}),A=Us({inputs:{x:y},backend:r,attrs:{dtype:"float32"}}),x=Xm({inputs:{a:A,b:n},backend:r}),b=Sh({inputs:{x},backend:r,attrs:{axis:0,keepDims:!1}});d.push(b),u.push(g),u.push(y),u.push(A),u.push(x),u.push(b)}let c=tI({inputs:d,backend:r,attrs:{axis:0}});return u.forEach(f=>r.disposeIntermediateTensorInfo(f)),c}var gJ={kernelName:eh,backendName:"cpu",kernelFunc:mJ},yJ=[Iq,gH,Tq,Nq,wH,Rq,Mq,Pq,zq,_q,Bq,Vq,Gq,qq,Xq,Jq,eK,rK,nK,wq,iK,lK,dK,hK,bH,IH,fK,yH,gK,AK,xK,vK,kK,SK,CK,EK,FK,$K,OK,DK,LK,WK,VK,GK,HK,KK,XK,ZK,YK,eX,mq,rX,SH,dX,TH,pX,NH,yX,AX,bX,RH,kX,SX,CX,EX,FX,MH,PH,AH,$X,yK,OX,DX,LX,gq,zH,_H,WX,BH,UX,HX,KX,YX,QX,tZ,rZ,VH,nZ,iZ,lZ,dZ,hZ,fZ,gZ,GH,AZ,vZ,SZ,HH,KH,NZ,FZ,PZ,ZH,zZ,_Z,LZ,rI,UZ,Aq,QH,jZ,xH,my,qZ,xq,bq,vq,XZ,YZ,QZ,tY,aY,nY,iY,tq,lY,dY,fY,aq,gY,AY,bY,nq,kZ,kY,SY,CY,EY,FY,$Y,OY,DY,oq,_Y,uq,BY,VY,GY,HY,KY,cq,JK,ZY,JY,eJ,rJ,nJ,YH,hJ,fJ,gJ,DZ];for(let e of yJ)Ga(e);var nI={};De(nI,{assertNotComplex:()=>hd,bindCanvasToFramebuffer:()=>EJ,bindColorTextureToFramebuffer:()=>Bc,bindTextureToProgramUniformSampler:()=>xI,bindTextureUnit:()=>gI,bindVertexBufferToProgramAttribute:()=>yy,callAndCheck:()=>we,canBeRepresented:()=>sI,createFragmentShader:()=>lI,createFramebuffer:()=>mI,createProgram:()=>uI,createStaticIndexBuffer:()=>hI,createStaticVertexBuffer:()=>pI,createTexture:()=>cI,createVertexShader:()=>oI,getBatchDim:()=>To,getExtensionOrThrow:()=>fp,getFramebufferErrorMessage:()=>bI,getMaxTexturesInShader:()=>II,getNumChannels:()=>CJ,getProgramUniformLocation:()=>AI,getProgramUniformLocationOrThrow:()=>yI,getRowsCols:()=>Co,getShapeAs3D:()=>Wc,getTextureShapeFromLogicalShape:()=>wI,getWebGLDisjointQueryTimerVersion:()=>SI,getWebGLErrorMessage:()=>iI,getWebGLMaxTextureSize:()=>kI,hasExtension:()=>Sa,isCapableOfRenderingToFloatTexture:()=>TI,isDownloadFloatTextureEnabled:()=>CI,isReshapeFree:()=>Op,isWebGLFenceEnabled:()=>NI,isWebGLVersionEnabled:()=>xy,linkProgram:()=>dI,resetMaxTextureSize:()=>RJ,resetMaxTexturesInShader:()=>FJ,unbindColorTextureFromFramebuffer:()=>Ay,unbindTextureUnit:()=>NJ,validateFramebuffer:()=>mp,validateProgram:()=>Lc,validateTextureSize:()=>fI});var uo={},E1={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function Zm(e,t){uo[e]=t}function pn(e,t){if(!(e in uo)||t!=null){let a=xJ(e,t);if(a!==null)uo[e]=a;else return console.log("Could not get context for WebGL version",e),null}let r=uo[e];return r==null||r.isContextLost()?(delete uo[e],pn(e)):(r.disable(r.DEPTH_TEST),r.disable(r.STENCIL_TEST),r.disable(r.BLEND),r.disable(r.DITHER),r.disable(r.POLYGON_OFFSET_FILL),r.disable(r.SAMPLE_COVERAGE),r.enable(r.SCISSOR_TEST),r.enable(r.CULL_FACE),r.cullFace(r.BACK),uo[e])}function AJ(e){if(typeof OffscreenCanvas!="undefined"&&e===2)return new OffscreenCanvas(300,150);if(typeof document!="undefined")return document.createElement("canvas");throw new Error("Cannot create a canvas in this context")}function xJ(e,t){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let r=t==null?AJ(e):t;return r.addEventListener("webglcontextlost",a=>{a.preventDefault(),delete uo[e]},!1),e===1?r.getContext("webgl",E1)||r.getContext("experimental-webgl",E1):r.getContext("webgl2",E1)}function Th(e,t){return[t,e]}function bJ(e,t){return e*t}function Mc(e){let t=w.sizeFromShape(e),r=Math.ceil(t/4);return w.sizeToSquarishShape(r)}function pd(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function vJ(e,t){let[r,a]=pd(e,t);return r*a*4}function Cx(e,t){let r=e,a,n,s,i,o,l,d,u,p,h;return Y().getNumber("WEBGL_VERSION")===2?(a=r.R32F,n=r.R16F,s=r.RGBA16F,i=r.RGBA32F,o=r.RED,d=4,u=1,p=r.HALF_FLOAT,h=r.FLOAT,l=r.RGBA8):(a=e.RGBA,n=e.RGBA,s=e.RGBA,i=r.RGBA,o=e.RGBA,d=4,u=4,p=t!=null?t.HALF_FLOAT_OES:null,h=e.FLOAT,l=e.RGBA),{internalFormatFloat:a,internalFormatHalfFloat:n,internalFormatPackedHalfFloat:s,internalFormatPackedFloat:i,textureFormatFloat:o,downloadTextureFormat:l,downloadUnpackNumChannels:d,defaultNumChannels:u,textureTypeHalfFloat:p,textureTypeFloat:h}}function we(e,t){let r=t();return Y().getBool("DEBUG")&&wJ(e),r}function wJ(e){let t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+iI(e,t))}var kJ=596e-10,IJ=65504;function sI(e){return!!(Y().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||e===0||kJ<Math.abs(e)&&Math.abs(e)<IJ)}function iI(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 fp(e,t){return es(e,()=>e.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function oI(e,t){let r=es(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(we(e,()=>e.shaderSource(r,t)),we(e,()=>e.compileShader(r)),e.getShaderParameter(r,e.COMPILE_STATUS)===!1)throw console.log(e.getShaderInfoLog(r)),new Error("Failed to compile vertex shader.");return r}function lI(e,t){let r=es(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(we(e,()=>e.shaderSource(r,t)),we(e,()=>e.compileShader(r)),e.getShaderParameter(r,e.COMPILE_STATUS)===!1)throw TJ(t,e.getShaderInfoLog(r)),new Error("Failed to compile fragment shader.");return r}var SJ=/ERROR: [0-9]+:([0-9]+):/g;function TJ(e,t){let r=SJ.exec(t);if(r==null){console.log(`Couldn't parse line number in error: ${t}`),console.log(e);return}let a=+r[1],n=e.split(`
|
|
`),s=n.length.toString().length+2,i=n.map((p,h)=>w.rightPad((h+1).toString(),s)+p),o=0;for(let p=0;p<i.length;p++)o=Math.max(i[p].length,o);let l=i.slice(0,a-1),d=i.slice(a-1,a),u=i.slice(a);console.log(l.join(`
|
|
`)),console.log(t.split(`
|
|
`)[0]),console.log(`%c ${w.rightPad(d[0],o)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(u.join(`
|
|
`))}function uI(e){return es(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function dI(e,t){if(we(e,()=>e.linkProgram(t)),e.getProgramParameter(t,e.LINK_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function Lc(e,t){if(we(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function pI(e,t){let r=es(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return we(e,()=>e.bindBuffer(e.ARRAY_BUFFER,r)),we(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),r}function hI(e,t){let r=es(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return we(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,r)),we(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),r}function CJ(){return Y().getNumber("WEBGL_VERSION")===2?1:4}function cI(e){return es(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function fI(e,t){let r=Y().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){let a=`[${e}x${t}]`;throw new Error("Requested texture size "+a+" is invalid.")}if(e>r||t>r){let a=`[${e}x${t}]`,n=`[${r}x${r}]`;throw new Error("Requested texture size "+a+" greater than WebGL maximum on this browser / GPU "+n+".")}}function mI(e){return es(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function yy(e,t,r,a,n,s,i){let o=e.getAttribLocation(t,r);return o===-1?!1:(we(e,()=>e.bindBuffer(e.ARRAY_BUFFER,a)),we(e,()=>e.vertexAttribPointer(o,n,e.FLOAT,!1,s,i)),we(e,()=>e.enableVertexAttribArray(o)),!0)}function gI(e,t,r){vI(e,r),we(e,()=>e.activeTexture(e.TEXTURE0+r)),we(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function NJ(e,t){vI(e,t),we(e,()=>e.activeTexture(e.TEXTURE0+t)),we(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function yI(e,t,r){return es(e,()=>e.getUniformLocation(t,r),'uniform "'+r+'" not present in program.')}function AI(e,t,r){return e.getUniformLocation(t,r)}function xI(e,t,r,a){we(e,()=>gI(e,t,a)),we(e,()=>e.uniform1i(r,a))}function EJ(e){we(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),we(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),we(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function Bc(e,t,r){we(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,r)),we(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function Ay(e,t){we(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),we(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function mp(e){let t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+bI(e,t))}function bI(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 es(e,t,r){let a=we(e,()=>t());if(a==null)throw new Error(r);return a}function vI(e,t){let r=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,a=t+e.TEXTURE0;if(a<e.TEXTURE0||a>r){let n=`[gl.TEXTURE0, gl.TEXTURE${r}]`;throw new Error(`textureUnit must be in ${n}.`)}}function To(e,t=2){return w.sizeFromShape(e.slice(0,e.length-t))}function Co(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 Wc(e){let t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[To(e),...Co(e)]),t}function wI(e,t=!1){let r=Y().getNumber("WEBGL_MAX_TEXTURE_SIZE");t&&(r=r*2,e=e.map((n,s)=>s>=e.length-2?w.nearestLargerEven(e[s]):e[s]),e.length===1&&(e=[2,e[0]])),e.length!==2&&(e=w.squeezeShape(e).newShape);let a=w.sizeFromShape(e);if(e.length<=1&&a<=r)return[1,a];if(e.length===2&&e[0]<=r&&e[1]<=r)return e;if(e.length===3&&e[0]*e[1]<=r&&e[2]<=r)return[e[0]*e[1],e[2]];if(e.length===3&&e[0]<=r&&e[1]*e[2]<=r)return[e[0],e[1]*e[2]];if(e.length===4&&e[0]*e[1]*e[2]<=r&&e[3]<=r)return[e[0]*e[1]*e[2],e[3]];if(e.length===4&&e[0]<=r&&e[1]*e[2]*e[3]<=r)return[e[0],e[1]*e[2]*e[3]];if(t){let n=To(e),s=2,i=2;return e.length&&([s,i]=Co(e)),a=n*(s/2)*(i/2),w.sizeToSquarishShape(a).map(o=>o*2)}return w.sizeToSquarishShape(a)}function $c(e){return e%2===0}function Op(e,t){if(e=e.slice(-2),t=t.slice(-2),w.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 r=e.slice(-1)[0],a=t.slice(-1)[0];if(r===a||$c(r)&&$c(a)&&(e[0]===1||t[0]===1))return!0}return e[1]===t[1]&&$c(e[0])&&$c(t[0])}var Vc,Uc;function kI(e){if(Vc==null){let t=pn(e);Vc=t.getParameter(t.MAX_TEXTURE_SIZE)}return Vc}function RJ(){Vc=null}function FJ(){Uc=null}function II(e){if(Uc==null){let t=pn(e);Uc=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,Uc)}function SI(e){if(e===0)return 0;let t,r=pn(e);return Sa(r,"EXT_disjoint_timer_query_webgl2")&&e===2?t=2:Sa(r,"EXT_disjoint_timer_query")?t=1:t=0,t}function Sa(e,t){return e.getExtension(t)!=null}function xy(e){try{if(pn(e)!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function TI(e){if(e===0)return!1;let t=pn(e);if(e===1){if(!Sa(t,"OES_texture_float"))return!1}else if(!Sa(t,"EXT_color_buffer_float"))return!1;return by(t)}function CI(e){if(e===0)return!1;let t=pn(e);if(e===1){if(!Sa(t,"OES_texture_float")||!Sa(t,"WEBGL_color_buffer_float"))return!1}else{if(Sa(t,"EXT_color_buffer_float"))return by(t);let r="EXT_color_buffer_half_float";if(Sa(t,r)){let a=t.getExtension(r);return MJ(t,a)}return!1}return by(t)}function by(e){let t=Cx(e),r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r);let a=1,n=1;e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,a,n,0,t.textureFormatFloat,t.textureTypeFloat,null);let s=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,r,0);let i=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(r),e.deleteFramebuffer(s),i}function MJ(e,t){let r=Cx(e,t),a=e.createTexture();e.bindTexture(e.TEXTURE_2D,a);let n=1,s=1;e.texImage2D(e.TEXTURE_2D,0,r.internalFormatHalfFloat,n,s,0,r.textureFormatFloat,r.textureTypeHalfFloat,null);let i=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,i),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,a,0);let o=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(a),e.deleteFramebuffer(i),o}function NI(e){return e!==2?!1:pn(e).fenceSync!=null}function hd(e,t){Array.isArray(e)||(e=[e]),e.forEach(r=>{r!=null&&w.assert(r.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the WebGL backend.`)})}var Pe=Y();Pe.registerFlag("HAS_WEBGL",()=>Pe.getNumber("WEBGL_VERSION")>0);Pe.registerFlag("WEBGL_VERSION",()=>xy(2)?2:xy(1)?1:0);Pe.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);Pe.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>Pe.get("WEBGL_VERSION")===2);Pe.registerFlag("WEBGL_CPU_FORWARD",()=>!0);Pe.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);Pe.registerFlag("WEBGL_PACK",()=>Pe.getBool("HAS_WEBGL"));Pe.registerFlag("WEBGL_PACK_NORMALIZATION",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_PACK_CLIP",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_PACK_REDUCE",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_LAZILY_UNPACK",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_CONV_IM2COL",()=>Pe.getBool("WEBGL_PACK"));Pe.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>kI(Pe.getNumber("WEBGL_VERSION")));Pe.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>II(Pe.getNumber("WEBGL_VERSION")));Pe.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{let e=Pe.getNumber("WEBGL_VERSION");return e===0?0:SI(e)});Pe.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>Pe.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!nh.isMobile());Pe.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>TI(Pe.getNumber("WEBGL_VERSION")));Pe.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>Pe.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:Pe.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));Pe.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>CI(Pe.getNumber("WEBGL_VERSION")));Pe.registerFlag("WEBGL_FENCE_API_ENABLED",()=>NI(Pe.getNumber("WEBGL_VERSION")));Pe.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>Pe.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0);Pe.registerFlag("WEBGL_DELETE_TEXTURE_THRESHOLD",()=>-1,e=>{if(e<0&&e!==-1)throw new Error(`WEBGL_DELETE_TEXTURE_THRESHOLD must be -1 (indicating never delete) or at least 0, but got ${e}.`)});Pe.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>nh.isMobile()?1:-1,e=>{if(e<0&&e!==-1)throw new Error(`WEBGL_FLUSH_THRESHOLD must be -1 (indicating never manual flush) or at least 0, but got ${e}.`)});Pe.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",()=>128);Pe.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",()=>!1);Pe.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e5);Pe.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",()=>128);function Br(){let e,t,r,a,n,s,i,o,l,d;return Y().getNumber("WEBGL_VERSION")===2?(e="#version 300 es",t="in",r="out",a="in",n="texture",s="outputColor",i="out vec4 outputColor;",o=`
|
|
bool isnan_custom(float val) {
|
|
return (val > 0.0 || val < 0.0) ? false : val != 0.0;
|
|
}
|
|
|
|
bvec4 isnan_custom(vec4 val) {
|
|
return bvec4(isnan_custom(val.x),
|
|
isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
|
|
}
|
|
|
|
#define isnan(value) isnan_custom(value)
|
|
`,l="",d=`
|
|
#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",r="varying",a="varying",n="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));
|
|
}
|
|
`,d=`
|
|
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:r,varyingFs:a,texture2D:n,output:s,defineOutput:i,defineSpecialNaN:o,defineSpecialInf:l,defineRound:d}}function Sl(e,t,r="index"){let a=w.computeStrides(t);return a.map((n,s)=>{let i=`int ${e[s]} = ${r} / ${n}`,o=s===a.length-1?`int ${e[s+1]} = ${r} - ${e[s]} * ${n}`:`index -= ${e[s]} * ${n}`;return`${i}; ${o};`}).join("")}function Ym(e,t,r="index"){let a=w.computeStrides(t);return a.map((n,s)=>{let i=`int ${e[s]} = ${r} / outShapeStrides[${s}]`,o=s===a.length-1?`int ${e[s+1]} = ${r} - ${e[s]} * outShapeStrides[${s}]`:`index -= ${e[s]} * outShapeStrides[${s}]`;return`${i}; ${o};`}).join("")}function $J(e,t){let r=e.length,a=e.map(s=>`${t}[${s}]`),n=new Array(r-1);n[r-2]=a[r-1];for(let s=r-3;s>=0;--s)n[s]=`(${n[s+1]} * ${a[s+1]})`;return n}function PJ(e,t,r="index"){let a=e.map((s,i)=>i),n=$J(a,t);return n.map((s,i)=>{let o=`int ${e[i]} = ${r} / ${n[i]}`,l=i===n.length-1?`int ${e[i+1]} = ${r} - ${e[i]} * ${n[i]}`:`index -= ${e[i]} * ${n[i]}`;return`${o}; ${l};`}).join("")}function Nx(e){let t=w.computeStrides(e).map(r=>r.toString());return`
|
|
int getFlatIndex(ivec3 coords) {
|
|
return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
|
|
}
|
|
`}function Ex(){return`
|
|
int getFlatIndex(ivec3 coords) {
|
|
return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;
|
|
}
|
|
`}var EI=`
|
|
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:RI}=N;function OJ(e,t,r){let a=[];if(e.forEach(h=>{let c=w.sizeFromShape(h.shapeInfo.logicalShape);if(h.shapeInfo.isUniform?a.push(`uniform float ${h.name}${c>1?`[${c}]`:""};`):(a.push(`uniform sampler2D ${h.name};`),a.push(`uniform int offset${h.name};`)),r.enableShapeUniforms){let{uniformShape:f}=Rx(r.packedInputs,h.shapeInfo.logicalShape,h.shapeInfo.texShape);switch(f.length){case 1:a.push(`uniform int ${h.name}Shape;`);break;case 2:a.push(`uniform ivec2 ${h.name}Shape;`);break;case 3:a.push(`uniform ivec3 ${h.name}Shape;`);break;case 4:a.push(`uniform ivec4 ${h.name}Shape;`);break;default:break}a.push(`uniform ivec2 ${h.name}TexShape;`)}}),r.enableShapeUniforms){switch(t.logicalShape.length){case 1:a.push("uniform int outShape;");break;case 2:a.push("uniform ivec2 outShape;"),a.push("uniform int outShapeStrides;");break;case 3:a.push("uniform ivec3 outShape;"),a.push("uniform ivec2 outShapeStrides;");break;case 4:a.push("uniform ivec4 outShape;"),a.push("uniform ivec3 outShapeStrides;");break;default:break}a.push("uniform ivec2 outTexShape;")}r.customUniforms&&r.customUniforms.forEach(h=>{a.push(`uniform ${h.type} ${h.name}${h.arrayIndex?`[${h.arrayIndex}]`:""};`)});let n=a.join(`
|
|
`),s=e.map(h=>zJ(h,t,r.packedInputs,r.enableShapeUniforms)).join(`
|
|
`),i=t.texShape,o=Br(),l=LJ(o),d,u,p=VJ(o);return t.isPacked?(d=DJ(t.logicalShape,i,r.enableShapeUniforms),u=WJ(o)):(d=_J(t.logicalShape,i,r.enableShapeUniforms),u=BJ(o)),r.packedInputs&&(p+=HJ),[p,l,u,n,d,s,r.userCode].join(`
|
|
`)}function cd(e,t=!1){let r=e.shapeInfo.logicalShape;switch(r.length){case 0:return nQ(e,t);case 1:return iQ(e,t);case 2:return lQ(e,t);case 3:return dQ(e,t);case 4:return hQ(e,t);case 5:return cQ(e);case 6:return fQ(e);default:throw new Error(`${r.length}-D input sampling is not yet supported`)}}function FI(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return aQ(e);case 1:return sQ(e,t);case 2:return oQ(e,t);case 3:return uQ(e,t);default:return pQ(e,t)}}function zJ(e,t,r=!1,a){let n="";r?n+=FI(e,a):n+=cd(e,a);let s=e.shapeInfo.logicalShape,i=t.logicalShape;return s.length<=i.length&&(r?n+=mQ(e,t):n+=gQ(e,t)),n}function DJ(e,t,r){switch(e.length){case 0:return MI();case 1:return qJ(e,t,r);case 2:return tQ(e,t,r);case 3:return XJ(e,t,r);default:return YJ(e,t,r)}}function _J(e,t,r){switch(e.length){case 0:return MI();case 1:return KJ(e,t,r);case 2:return rQ(e,t,r);case 3:return ZJ(e,t,r);case 4:return JJ(e,t,r);case 5:return QJ(e,t);case 6:return eQ(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function LJ(e){return`
|
|
float sampleTexture(sampler2D textureSampler, vec2 uv) {
|
|
return ${e.texture2D}(textureSampler, uv).r;
|
|
}
|
|
`}function BJ(e){return`
|
|
void setOutput(float val) {
|
|
${e.output} = vec4(val, 0, 0, 0);
|
|
}
|
|
`}function WJ(e){return`
|
|
void setOutput(vec4 val) {
|
|
${e.output} = val;
|
|
}
|
|
`}function VJ(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);
|
|
}
|
|
|
|
${UJ}
|
|
${GJ}
|
|
${jJ}
|
|
`}var UJ=`
|
|
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);
|
|
}
|
|
`,GJ=`
|
|
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);
|
|
}
|
|
`,jJ=`
|
|
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);
|
|
}
|
|
`,HJ=`
|
|
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 MI(){return`
|
|
int getOutputCoords() {
|
|
return 0;
|
|
}
|
|
`}function qJ(e,t,r){let a=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return a[0]===1?r?`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.x * ${a[1]}.0);
|
|
}
|
|
`:a[1]===1?r?`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.y * ${a[0]}.0);
|
|
}
|
|
`:r?`
|
|
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(${a[0]}, ${a[1]}));
|
|
return 2 * (resTexRC.x * ${a[1]} + resTexRC.y);
|
|
}
|
|
`}function KJ(e,t,r){return t[0]===1?r?`
|
|
int getOutputCoords() {
|
|
return int(resultUV.x * float(outTexShape[1]));
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
return int(resultUV.x * ${t[1]}.0);
|
|
}
|
|
`:t[1]===1?r?`
|
|
int getOutputCoords() {
|
|
return int(resultUV.y * float(outTexShape[0]));
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
return int(resultUV.y * ${t[0]}.0);
|
|
}
|
|
`:r?`
|
|
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 XJ(e,t,r){if(r)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 a=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],n=Math.ceil(e[2]/2),s=n*Math.ceil(e[1]/2);return`
|
|
ivec3 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${a[0]}, ${a[1]}));
|
|
int index = resTexRC.x * ${a[1]} + resTexRC.y;
|
|
|
|
int b = index / ${s};
|
|
index -= b * ${s};
|
|
|
|
int r = 2 * (index / ${n});
|
|
int c = imod(index, ${n}) * 2;
|
|
|
|
return ivec3(b, r, c);
|
|
}
|
|
`}function ZJ(e,t,r){if(r)return`
|
|
ivec3 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(outTexShape[0], outTexShape[1]));
|
|
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
|
|
${Ym(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`;let a=Sl(["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;
|
|
${a}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`}function YJ(e,t,r){if(r)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 a=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],n=Math.ceil(e[e.length-1]/2),s=n*Math.ceil(e[e.length-2]/2),i=s,o="",l="b, r, c";for(let d=2;d<e.length-1;d++)i*=e[e.length-d-1],o=`
|
|
int b${d} = index / ${i};
|
|
index -= b${d} * ${i};
|
|
`+o,l=`b${d}, `+l;return`
|
|
ivec${e.length} getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${a[0]}, ${a[1]}));
|
|
int index = resTexRC.x * ${a[1]} + resTexRC.y;
|
|
|
|
${o}
|
|
|
|
int b = index / ${s};
|
|
index -= b * ${s};
|
|
|
|
int r = 2 * (index / ${n});
|
|
int c = imod(index, ${n}) * 2;
|
|
|
|
return ivec${e.length}(${l});
|
|
}
|
|
`}function JJ(e,t,r){if(r)return`
|
|
ivec4 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(outTexShape[0], outTexShape[1]));
|
|
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
|
|
${Ym(["r","c","d","d2"],e)}
|
|
return ivec4(r, c, d, d2);
|
|
}
|
|
`;let a=Sl(["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;
|
|
${a}
|
|
return ivec4(r, c, d, d2);
|
|
}
|
|
`}function QJ(e,t){let r=Sl(["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;
|
|
|
|
${r}
|
|
|
|
ivec5 outShape = ivec5(r, c, d, d2, d3);
|
|
return outShape;
|
|
}
|
|
`}function eQ(e,t){let r=Sl(["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;
|
|
|
|
${r}
|
|
|
|
ivec6 result = ivec6(r, c, d, d2, d3, d4);
|
|
return result;
|
|
}
|
|
`}function tQ(e,t,r){let a=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(w.arraysEqual(e,t))return r?`
|
|
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(${a[0]}, ${a[1]}));
|
|
}
|
|
`;let n=Math.ceil(e[1]/2);return r?`
|
|
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(${a[0]}, ${a[1]}));
|
|
|
|
int index = resTexRC.x * ${a[1]} + resTexRC.y;
|
|
int r = 2 * (index / ${n});
|
|
int c = imod(index, ${n}) * 2;
|
|
|
|
return ivec2(r, c);
|
|
}
|
|
`}function rQ(e,t,r){return w.arraysEqual(e,t)?r?`
|
|
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?r?`
|
|
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?r?`
|
|
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);
|
|
}
|
|
`:r?`
|
|
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 Tl(e){return`offset${e}`}function aQ(e){let t=e.name,r="get"+t.charAt(0).toUpperCase()+t.slice(1),a=Br();return`
|
|
vec4 ${r}() {
|
|
return ${a.texture2D}(${t}, halfCR);
|
|
}
|
|
`}function nQ(e,t){let r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1);if(e.shapeInfo.isUniform)return`float ${a}() {return ${r};}`;let[n,s]=e.shapeInfo.texShape;if(n===1&&s===1)return`
|
|
float ${a}() {
|
|
return sampleTexture(${r}, halfCR);
|
|
}
|
|
`;let i=Tl(r);if(t)return`
|
|
float ${a}() {
|
|
vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], ${i});
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`;let[o,l]=e.shapeInfo.texShape;return`
|
|
float ${a}() {
|
|
vec2 uv = uvFromFlat(${o}, ${l}, ${i});
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`}function sQ(e,t){let r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),n=e.shapeInfo.texShape,s=Br();if(t)return`
|
|
vec4 ${a}(int index) {
|
|
ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}TexShape[1]) / 2.0));
|
|
vec2 uv = packedUVfrom1D(
|
|
packedTexShape[0], packedTexShape[1], index);
|
|
return ${s.texture2D}(${r}, uv);
|
|
}
|
|
`;let i=[Math.ceil(n[0]/2),Math.ceil(n[1]/2)];return`
|
|
vec4 ${a}(int index) {
|
|
vec2 uv = packedUVfrom1D(
|
|
${i[0]}, ${i[1]}, index);
|
|
return ${s.texture2D}(${r}, uv);
|
|
}
|
|
`}function iQ(e,t){let r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1);if(e.shapeInfo.isUniform)return`
|
|
float ${a}(int index) {
|
|
${fd(e)}
|
|
}
|
|
`;let n=e.shapeInfo.texShape,s=n[0],i=n[1];if(i===1&&s===1)return`
|
|
float ${a}(int index) {
|
|
return sampleTexture(${r}, halfCR);
|
|
}
|
|
`;let o=Tl(r);return i===1?t?`
|
|
float ${a}(int index) {
|
|
vec2 uv = vec2(0.5, (float(index + ${o}) + 0.5) / float(${r}TexShape[0]));
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${a}(int index) {
|
|
vec2 uv = vec2(0.5, (float(index + ${o}) + 0.5) / ${s}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:s===1?t?`
|
|
float ${a}(int index) {
|
|
vec2 uv = vec2((float(index + ${o}) + 0.5) / float(${r}TexShape[1]), 0.5);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${a}(int index) {
|
|
vec2 uv = vec2((float(index + ${o}) + 0.5) / ${i}.0, 0.5);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:t?`
|
|
float ${a}(int index) {
|
|
vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index + ${o});
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${a}(int index) {
|
|
vec2 uv = uvFromFlat(${s}, ${i}, index + ${o});
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`}function oQ(e,t){let r=e.shapeInfo.logicalShape,a=e.name,n="get"+a.charAt(0).toUpperCase()+a.slice(1),s=e.shapeInfo.texShape,i=s[0],o=s[1],l=Br();if(s!=null&&w.arraysEqual(r,s))return t?`
|
|
vec4 ${n}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${a}TexShape[1], ${a}TexShape[0]);
|
|
|
|
return ${l.texture2D}(${a}, uv);
|
|
}
|
|
`:`
|
|
vec4 ${n}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${o}.0, ${i}.0);
|
|
|
|
return ${l.texture2D}(${a}, uv);
|
|
}
|
|
`;if(t)return`
|
|
vec4 ${n}(int row, int col) {
|
|
ivec2 packedTexShape = ivec2(ceil(float(${a}TexShape[0]) / 2.0), ceil(float(${a}TexShape[1]) / 2.0));
|
|
int valuesPerRow = int(ceil(float(${a}Shape[1]) / 2.0));
|
|
vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);
|
|
return ${l.texture2D}(${a}, uv);
|
|
}
|
|
`;let d=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],u=Math.ceil(r[1]/2);return`
|
|
vec4 ${n}(int row, int col) {
|
|
vec2 uv = packedUVfrom2D(${u}, ${d[0]}, ${d[1]}, row, col);
|
|
return ${l.texture2D}(${a}, uv);
|
|
}
|
|
`}function lQ(e,t){let r=e.shapeInfo.logicalShape,a=e.name,n="get"+a.charAt(0).toUpperCase()+a.slice(1),s=e.shapeInfo.texShape;if(s!=null&&w.arraysEqual(r,s)){if(t)return`
|
|
float ${n}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${a}TexShape[1], ${a}TexShape[0]);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`;let h=s[0],c=s[1];return`
|
|
float ${n}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${c}.0, ${h}.0);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`}let{newShape:i,keptDims:o}=w.squeezeShape(r),l=i;if(l.length<r.length){let h=md(e,l),c=["row","col"];return`
|
|
${cd(h,t)}
|
|
float ${n}(int row, int col) {
|
|
return ${n}(${gd(c,o)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${n}(int row, int col) {
|
|
int index = round(dot(vec2(row, col), vec2(${r[1]}, 1)));
|
|
${fd(e)}
|
|
}
|
|
`;let d=s[0],u=s[1],p=Tl(a);return u===1?t?`
|
|
float ${n}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${p}), vec3(${a}Shape[1], 1, 1));
|
|
vec2 uv = vec2(0.5, (index + 0.5) / float(${a}TexShape[0]));
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`:`
|
|
float ${n}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${p}), vec3(${r[1]}, 1, 1));
|
|
vec2 uv = vec2(0.5, (index + 0.5) / ${d}.0);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`:d===1?t?`
|
|
float ${n}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${p}), vec3(${a}Shape[1], 1, 1));
|
|
vec2 uv = vec2((index + 0.5) / float(${a}TexShape[1]), 0.5);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`:`
|
|
float ${n}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${p}), vec3(${r[1]}, 1, 1));
|
|
vec2 uv = vec2((index + 0.5) / ${u}.0, 0.5);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`:t?`
|
|
float ${n}(int row, int col) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${a}Shape[1] + col + ${p};
|
|
vec2 uv = uvFromFlat(${a}TexShape[0], ${a}TexShape[1], index);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`:`
|
|
float ${n}(int row, int col) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${r[1]} + col + ${p};
|
|
vec2 uv = uvFromFlat(${d}, ${u}, index);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`}function uQ(e,t){let r=e.shapeInfo.logicalShape,a=e.name,n="get"+a.charAt(0).toUpperCase()+a.slice(1),s=e.shapeInfo.texShape,i=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];if(r[0]===1){let h=r.slice(1),c=[1,2],f=md(e,h),m=["b","row","col"];return`
|
|
${FI(f,t)}
|
|
vec4 ${n}(int b, int row, int col) {
|
|
return ${n}(${gd(m,c)});
|
|
}
|
|
`}let o=Br();if(t)return`
|
|
vec4 ${n}(int b, int row, int col) {
|
|
ivec2 packedTexShape = ivec2(ceil(float(${a}TexShape[0]) / 2.0), ceil(float(${a}TexShape[1]) / 2.0));
|
|
int valuesPerRow = int(ceil(float(${a}Shape[2]) / 2.0));
|
|
int texelsInBatch = valuesPerRow * int(ceil(float(${a}Shape[1]) / 2.0));
|
|
vec2 uv = packedUVfrom3D(
|
|
packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);
|
|
return ${o.texture2D}(${a}, uv);
|
|
}
|
|
`;let l=i[0],d=i[1],u=Math.ceil(r[2]/2),p=u*Math.ceil(r[1]/2);return`
|
|
vec4 ${n}(int b, int row, int col) {
|
|
vec2 uv = packedUVfrom3D(
|
|
${l}, ${d}, ${p}, ${u}, b, row, col);
|
|
return ${o.texture2D}(${a}, uv);
|
|
}
|
|
`}function dQ(e,t){let r=e.shapeInfo.logicalShape,a=e.name,n="get"+a.charAt(0).toUpperCase()+a.slice(1),s=r[1]*r[2],i=r[2],{newShape:o,keptDims:l}=w.squeezeShape(r),d=o;if(d.length<r.length){let m=md(e,d),g=["row","col","depth"];return`
|
|
${cd(m,t)}
|
|
float ${n}(int row, int col, int depth) {
|
|
return ${n}(${gd(g,l)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${n}(int row, int col, int depth) {
|
|
int index = round(dot(vec3(row, col, depth),
|
|
vec3(${s}, ${i}, 1)));
|
|
${fd(e)}
|
|
}
|
|
`;let u=e.shapeInfo.texShape,p=u[0],h=u[1],c=e.shapeInfo.flatOffset;if(h===s&&c==null)return t?`
|
|
float ${n}(int row, int col, int depth) {
|
|
int stride1 = ${a}Shape[2];
|
|
float texR = float(row);
|
|
float texC = dot(vec2(col, depth), vec2(stride1, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${a}TexShape[1], ${a}TexShape[0]);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`:`
|
|
float ${n}(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(${h}.0, ${p}.0);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`;if(h===i&&c==null)return t?`
|
|
float ${n}(int row, int col, int depth) {
|
|
float texR = dot(vec2(row, col), vec2(${a}Shape[1], 1));
|
|
float texC = float(depth);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${a}TexShape[1], ${a}TexShape[0]);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`:`
|
|
float ${n}(int row, int col, int depth) {
|
|
float texR = dot(vec2(row, col), vec2(${r[1]}, 1));
|
|
float texC = float(depth);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${h}.0, ${p}.0);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`;let f=Tl(a);return t?`
|
|
float ${n}(int row, int col, int depth) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int stride0 = ${a}Shape[1] * ${a}Shape[2];
|
|
int stride1 = ${a}Shape[2];
|
|
int index = row * ${s} + col * ${i} + depth + ${f};
|
|
vec2 uv = uvFromFlat(${a}TexShape[0], ${a}TexShape[1], index);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`:`
|
|
float ${n}(int row, int col, int depth) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${s} + col * ${i} + depth + ${f};
|
|
vec2 uv = uvFromFlat(${p}, ${h}, index);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`}function pQ(e,t){let r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),n=Br();if(t)return`
|
|
vec4 ${a}(int b2, int b, int row, int col) {
|
|
int valuesPerRow = int(ceil(float(${r}Shape[3]) / 2.0));
|
|
int texelsInBatch = valuesPerRow * int(ceil(float(${r}Shape[2]) / 2.0));
|
|
int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);
|
|
texelsInBatch *= ${r}Shape[1];
|
|
index = b2 * texelsInBatch + index;
|
|
ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}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 ${n.texture2D}(${r}, uv);
|
|
}
|
|
`;let s=e.shapeInfo.logicalShape,i=s.length,o=e.shapeInfo.texShape,l=[Math.ceil(o[0]/2),Math.ceil(o[1]/2)],d=l[0],u=l[1],p=Math.ceil(s[i-1]/2),h=p*Math.ceil(s[i-2]/2),c="int b, int row, int col",f=`b * ${h} + (row / 2) * ${p} + (col / 2)`;for(let m=2;m<i-1;m++)c=`int b${m}, `+c,h*=s[i-m-1],f=`b${m} * ${h} + `+f;return`
|
|
vec4 ${a}(${c}) {
|
|
int index = ${f};
|
|
int texR = index / ${u};
|
|
int texC = index - texR * ${u};
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${u}, ${d});
|
|
return ${n.texture2D}(${r}, uv);
|
|
}
|
|
`}function hQ(e,t){let r=e.shapeInfo.logicalShape,a=e.name,n="get"+a.charAt(0).toUpperCase()+a.slice(1),s=r[3],i=r[2]*s,o=r[1]*i,{newShape:l,keptDims:d}=w.squeezeShape(r);if(l.length<r.length){let A=md(e,l),x=["row","col","depth","depth2"];return`
|
|
${cd(A,t)}
|
|
float ${n}(int row, int col, int depth, int depth2) {
|
|
return ${n}(${gd(x,d)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${n}(int row, int col, int depth, int depth2) {
|
|
int index = round(dot(vec4(row, col, depth, depth2),
|
|
vec4(${o}, ${i}, ${s}, 1)));
|
|
${fd(e)}
|
|
}
|
|
`;let u=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,h=p[0],c=p[1],f=`int stride2 = ${a}Shape[3];`,m=`int stride1 = ${a}Shape[2] * stride2;`,g=`int stride0 = ${a}Shape[1] * stride1;`;if(c===o&&u==null)return t?`
|
|
float ${n}(int row, int col, int depth, int depth2) {
|
|
${f}
|
|
${m}
|
|
float texR = float(row);
|
|
float texC =
|
|
dot(vec3(col, depth, depth2),
|
|
vec3(stride1, stride2, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${a}TexShape[1], ${a}TexShape[0]);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`:`
|
|
float ${n}(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(${c}.0, ${h}.0);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`;if(c===s&&u==null)return t?`
|
|
float ${n}(int row, int col, int depth, int depth2) {
|
|
float texR = dot(vec3(row, col, depth),
|
|
vec3(${a}Shape[1] * ${a}Shape[2], ${a}Shape[2], 1));
|
|
float texC = float(depth2);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${a}TexShape[1], ${a}TexShape[0]);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`:`
|
|
float ${n}(int row, int col, int depth, int depth2) {
|
|
float texR = dot(vec3(row, col, depth),
|
|
vec3(${r[1]*r[2]}, ${r[2]}, 1));
|
|
float texC = float(depth2);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${c}.0, ${h}.0);
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`;let y=Tl(a);return t?`
|
|
float ${n}(int row, int col, int depth, int depth2) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
${f}
|
|
${m}
|
|
${g}
|
|
int index = row * stride0 + col * stride1 +
|
|
depth * stride2 + depth2;
|
|
vec2 uv = uvFromFlat(${a}TexShape[0], ${a}TexShape[1], index + ${y});
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`:`
|
|
float ${n}(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(${h}, ${c}, index + ${y});
|
|
return sampleTexture(${a}, uv);
|
|
}
|
|
`}function cQ(e){let t=e.shapeInfo.logicalShape,r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),n=t[4],s=t[3]*n,i=t[2]*s,o=t[1]*i,{newShape:l,keptDims:d}=w.squeezeShape(t);if(l.length<t.length){let m=md(e,l),g=["row","col","depth","depth2","depth3"];return`
|
|
${cd(m)}
|
|
float ${a}(int row, int col, int depth, int depth2, int depth3) {
|
|
return ${a}(${gd(g,d)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${a}(int row, int col, int depth, int depth2, int depth3) {
|
|
float index = dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${o}, ${i}, ${s}, ${n})) +
|
|
depth3;
|
|
${fd(e)}
|
|
}
|
|
`;let u=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,h=p[0],c=p[1];if(c===o&&u==null)return`
|
|
float ${a}(int row, int col, int depth, int depth2, int depth3) {
|
|
int texR = row;
|
|
float texC = dot(vec4(col, depth, depth2, depth3),
|
|
vec4(${i}, ${s}, ${n}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${c}.0, ${h}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`;if(c===n&&u==null)return`
|
|
float ${a}(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(${c}.0, ${h}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`;let f=Tl(r);return`
|
|
float ${a}(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 * ${n} + depth3 + ${f};
|
|
vec2 uv = uvFromFlat(${h}, ${c}, index);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`}function fQ(e){let t=e.shapeInfo.logicalShape,r=e.name,a="get"+r.charAt(0).toUpperCase()+r.slice(1),{newShape:n,keptDims:s}=w.squeezeShape(t);if(n.length<t.length){let g=md(e,n),y=["row","col","depth","depth2","depth3","depth4"];return`
|
|
${cd(g)}
|
|
float ${a}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
return ${a}(${gd(y,s)});
|
|
}
|
|
`}let i=t[5],o=t[4]*i,l=t[3]*o,d=t[2]*l,u=t[1]*d;if(e.shapeInfo.isUniform)return`
|
|
float ${a}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
int index = round(dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${u}, ${d}, ${l}, ${o})) +
|
|
dot(
|
|
vec2(depth3, depth4),
|
|
vec2(${i}, 1)));
|
|
${fd(e)}
|
|
}
|
|
`;let p=e.shapeInfo.flatOffset,h=e.shapeInfo.texShape,c=h[0],f=h[1];if(f===u&&p==null)return`
|
|
float ${a}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
int texR = row;
|
|
float texC = dot(vec4(col, depth, depth2, depth3),
|
|
vec4(${d}, ${l}, ${o}, ${i})) +
|
|
float(depth4);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${f}.0, ${c}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`;if(f===i&&p==null)return`
|
|
float ${a}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
float texR = dot(vec4(row, col, depth, depth2),
|
|
vec4(${t[1]*t[2]*t[3]*t[4]},
|
|
${t[2]*t[3]*t[4]},
|
|
${t[3]*t[4]},
|
|
${t[4]})) + float(depth3);
|
|
int texC = depth4;
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${f}.0, ${c}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`;let m=Tl(r);return`
|
|
float ${a}(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 * ${u} + col * ${d} + depth * ${l} +
|
|
depth2 * ${o} + depth3 * ${i} + depth4 + ${m};
|
|
vec2 uv = uvFromFlat(${c}, ${f}, index);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`}function fd(e){let t=e.name,r=w.sizeFromShape(e.shapeInfo.logicalShape);return r<2?`return ${t};`:`
|
|
for (int i = 0; i < ${r}; i++) {
|
|
if (i == index) {
|
|
return ${t}[i];
|
|
}
|
|
}
|
|
`}function mQ(e,t){let r=e.name,a=r.charAt(0).toUpperCase()+r.slice(1),n="get"+a+"AtOutCoords",s=e.shapeInfo.logicalShape.length,i=t.logicalShape.length,o=RI(e.shapeInfo.logicalShape,t.logicalShape),l=vt(i),d=i-s,u,p=["x","y","z","w","u","v"];s===0?u="":i<2&&o.length>=1?u="coords = 0;":u=o.map(g=>`coords.${p[g+d]} = 0;`).join(`
|
|
`);let h="";i<2&&s>0?h="coords":h=e.shapeInfo.logicalShape.map((g,y)=>`coords.${p[y+d]}`).join(", ");let c="return outputValue;",f=w.sizeFromShape(e.shapeInfo.logicalShape)===1,m=w.sizeFromShape(t.logicalShape)===1;if(s===1&&!f&&!m)c=`
|
|
return vec4(outputValue.xy, outputValue.xy);
|
|
`;else if(f&&!m)i===1?c=`
|
|
return vec4(outputValue.x, outputValue.x, 0., 0.);
|
|
`:c=`
|
|
return vec4(outputValue.x);
|
|
`;else if(o.length){let g=s-2,y=s-1;o.indexOf(g)>-1&&o.indexOf(y)>-1?c="return vec4(outputValue.x);":o.indexOf(g)>-1?c="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":o.indexOf(y)>-1&&(c="return vec4(outputValue.xx, outputValue.zz);")}return`
|
|
vec4 ${n}() {
|
|
${l} coords = getOutputCoords();
|
|
${u}
|
|
vec4 outputValue = get${a}(${h});
|
|
${c}
|
|
}
|
|
`}function gQ(e,t){let r=e.name,a=r.charAt(0).toUpperCase()+r.slice(1),n="get"+a+"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&&w.arraysEqual(i,s))return`
|
|
float ${n}() {
|
|
return sampleTexture(${r}, resultUV);
|
|
}
|
|
`;let d=vt(l),u=RI(e.shapeInfo.logicalShape,t.logicalShape),p=l-o,h,c=["x","y","z","w","u","v"];o===0?h="":l<2&&u.length>=1?h="coords = 0;":h=u.map(m=>`coords.${c[m+p]} = 0;`).join(`
|
|
`);let f="";return l<2&&o>0?f="coords":f=e.shapeInfo.logicalShape.map((m,g)=>`coords.${c[g+p]}`).join(", "),`
|
|
float ${n}() {
|
|
${d} coords = getOutputCoords();
|
|
${h}
|
|
return get${a}(${f});
|
|
}
|
|
`}function vt(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 Rx(e,t,r){let{newShape:a,keptDims:n}=w.squeezeShape(t),s=t.length,i=e&&s===3&&t[0]===1,o=i?t.slice(1):a,l=!e&&s>1&&!w.arraysEqual(t,r)&&a.length<s||i;return{useSqueezeShape:l,uniformShape:l?o:t,keptDims:n}}function md(e,t){let r=JSON.parse(JSON.stringify(e));return r.shapeInfo.logicalShape=t,r}function gd(e,t){return t.map(r=>e[r]).join(", ")}function yQ(e,t,r,a){let n=r.map((b,v)=>{let C={logicalShape:b.shape,texShape:b.isUniform?null:b.texData.texShape,isUniform:b.isUniform,isPacked:b.isUniform?!1:b.texData.isPacked,flatOffset:null};return b.texData!=null&&b.texData.slice!=null&&b.texData.slice.flatOffset>0&&(C.flatOffset=b.texData.slice.flatOffset),{name:t.variableNames[v],shapeInfo:C}}),s=n.map(b=>b.shapeInfo),i={logicalShape:a.shape,texShape:a.texData.texShape,isUniform:!1,isPacked:a.texData.isPacked,flatOffset:null},o=OJ(n,i,t),l=lI(e.gl,o),d=e.createProgram(l),u=null,p=e.getUniformLocation(d,"NAN",!1);Y().getNumber("WEBGL_VERSION")===1&&(u=e.getUniformLocation(d,"INFINITY",!1));let h=!1,c={},f={},m={};for(let b=0;b<t.variableNames.length;b++){let v=t.variableNames[b];c[v]=e.getUniformLocation(d,v,h),c[`offset${v}`]=e.getUniformLocation(d,`offset${v}`,h),t.enableShapeUniforms&&(f[`${v}Shape`]=e.getUniformLocation(d,`${v}Shape`,h),m[`${v}TexShape`]=e.getUniformLocation(d,`${v}TexShape`,h))}let g,y,A;t.enableShapeUniforms&&(g=e.getUniformLocation(d,"outShape",h),A=e.getUniformLocation(d,"outShapeStrides",h),y=e.getUniformLocation(d,"outTexShape",h));let x=[];return t.customUniforms&&t.customUniforms.forEach((b,v)=>{x[v]=e.getUniformLocation(d,b.name,h)}),{program:t,fragmentShader:l,source:o,webGLProgram:d,uniformLocations:c,customUniformLocations:x,inShapeInfos:s,outShapeInfo:i,infLoc:u,nanLoc:p,inShapesLocations:f,inTexShapesLocations:m,outShapeLocation:g,outShapeStridesLocation:A,outTexShapeLocation:y}}function V3(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((r,a)=>{let n=r.logicalShape,s=t[a],i=s.shape;if(!w.arraysEqual(n,i))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${n} and ${i} must match`);if(r.isUniform&&s.isUniform)return;let o=r.texShape,l=s.isUniform?null:s.texData.texShape;if(!w.arraysEqual(o,l))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${o} and ${l} must match`)})}function AQ(e,t,r,a,n){t.program.enableShapeUniforms||(V3(t.inShapeInfos,r),V3([t.outShapeInfo],[a]));let s=a.texData.texture,i=a.texData.texShape;a.texData.isPacked?e.setOutputPackedMatrixTexture(s.texture,i[0],i[1]):e.setOutputMatrixTexture(s.texture,i[0],i[1]),e.setProgram(t.webGLProgram),Y().getNumber("WEBGL_VERSION")===1&&t.infLoc!==null&&e.gl.uniform1f(t.infLoc,1/0),t.nanLoc!==null&&e.gl.uniform1f(t.nanLoc,NaN),r.forEach((l,d)=>{let u=t.program.variableNames[d],p=t.uniformLocations[u],h=t.uniformLocations[`offset${u}`],c=t.inShapesLocations[`${u}Shape`],f=t.inTexShapesLocations[`${u}TexShape`];if(c){let{uniformShape:m}=Rx(t.program.packedInputs,l.shape,l.texData.texShape);switch(m.length){case 1:e.gl.uniform1iv(c,new Int32Array(m));break;case 2:e.gl.uniform2iv(c,new Int32Array(m));break;case 3:e.gl.uniform3iv(c,new Int32Array(m));break;case 4:e.gl.uniform4iv(c,new Int32Array(m));break;default:break}}if(f&&e.gl.uniform2i(f,l.texData.texShape[0],l.texData.texShape[1]),p!=null){if(l.isUniform){if(w.sizeFromShape(l.shape)<2)e.gl.uniform1f(p,l.uniformValues[0]);else{let m=l.uniformValues;m instanceof Float32Array||(m=new Float32Array(m)),e.gl.uniform1fv(p,m)}return}l.texData.slice!=null&&h!=null&&e.gl.uniform1i(h,l.texData.slice.flatOffset),e.setInputMatrixTexture(l.texData.texture.texture,p,d)}});let o=t.outShapeLocation;if(o)switch(a.shape.length){case 1:e.gl.uniform1iv(o,new Int32Array(a.shape));break;case 2:e.gl.uniform2iv(o,new Int32Array(a.shape));break;case 3:e.gl.uniform3iv(o,new Int32Array(a.shape));break;case 4:e.gl.uniform4iv(o,new Int32Array(a.shape));break;default:break}if(t.outShapeStridesLocation){let l=w.computeStrides(a.shape);switch(a.shape.length){case 2:e.gl.uniform1iv(t.outShapeStridesLocation,new Int32Array(l));break;case 3:e.gl.uniform2iv(t.outShapeStridesLocation,new Int32Array(l));break;case 4:e.gl.uniform3iv(t.outShapeStridesLocation,new Int32Array(l));break;default:break}}t.outTexShapeLocation&&e.gl.uniform2i(t.outTexShapeLocation,a.texData.texShape[0],a.texData.texShape[1]),t.program.customUniforms&&n&&t.program.customUniforms.forEach((l,d)=>{let u=t.customUniformLocations[d],p=n[d];if(l.type==="float")e.gl.uniform1fv(u,p);else if(l.type==="vec2")e.gl.uniform2fv(u,p);else if(l.type==="vec3")e.gl.uniform3fv(u,p);else if(l.type==="vec4")e.gl.uniform4fv(u,p);else if(l.type==="int")e.gl.uniform1iv(u,p);else if(l.type==="ivec2")e.gl.uniform2iv(u,p);else if(l.type==="ivec3")e.gl.uniform3iv(u,p);else if(l.type==="ivec4")e.gl.uniform4iv(u,p);else throw Error(`uniform type ${l.type} is not supported yet.`)}),e.executeProgram()}function xQ(e,t,r){let a="";t.concat(r).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:d,uniformShape:u,keptDims:p}=Rx(e.packedInputs,i.shape,l),h="",c="",f="";if(u.length===1&&e.packedInputs){let v=[Math.ceil(l[0]/2),Math.ceil(l[1]/2)];h=`${v[0]>1}_${v[1]>1}`}else if(u.length===2&&!e.packedInputs)c=`${u[0]>1}_${u[1]>1}`;else if(u.length>2&&!e.packedInputs){let v=w.computeStrides(u);f=`${v[0]===l[1]}_${v[v.length-1]===l[1]}`}let m=i.shape.length,g=u.length===2&&w.arraysEqual(i.shape,l),y=w.sizeFromShape(i.shape)===1,A=N.getBroadcastDims(i.shape,r.shape),x=!e.packedInputs&&m===r.shape.length&&w.arraysEqual(l,r.texData.texShape),b=e.packedInputs||u.length>2?"":`${l[0]>1}_${l[1]>1}`;a+=`${m}_${x}_${d?p:""}_${u.length}_${y}_${A}_${g}_${h}_${c}_${f}_${b}_${o}`}else{let l=i.isUniform?"uniform":i.texData.texShape;a+=`${i.shape}_${l}_${o}`}});let n=e.userCode,s=e.constructor.name;return s+="_"+a+"_"+n+`${Y().getNumber("WEBGL_VERSION")}`,s}function sa(e){return Y().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4}var bQ=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=Br();this.outputShape=e,this.enableShapeUniforms=sa(this.outputShape.length),this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${this.enableShapeUniforms?Ym(["r","c","d"],e):Sl(["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;
|
|
}
|
|
`}},vQ=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=Br();this.outputShape=e,this.enableShapeUniforms=sa(this.outputShape.length),this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${this.enableShapeUniforms?Ym(["r","c","d"],e):Sl(["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;
|
|
}
|
|
`}},wQ=class{constructor(e){this.variableNames=["A"],this.outTexUsage=3;let t=Br();this.outputShape=e,this.userCode=`
|
|
${EI}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}},kQ=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=3;let t=Br();this.outputShape=e,this.userCode=`
|
|
${EI}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}},IQ=class{constructor(e,t=!1){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];let r=Br();this.outputShape=e,this.enableShapeUniforms=sa(this.outputShape.length);let a="result";t&&(a="floor(result * 255. + 0.5)"),this.userCode=`
|
|
${this.enableShapeUniforms?Ex():Nx(e)}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
|
|
int flatIndex = getFlatIndex(coords);
|
|
int offset = imod(flatIndex, 4);
|
|
|
|
flatIndex = idiv(flatIndex, 4, 1.);
|
|
|
|
int r = flatIndex / texShape[1];
|
|
int c = imod(flatIndex, texShape[1]);
|
|
vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
|
|
vec4 values = ${r.texture2D}(A, uv);
|
|
|
|
float result;
|
|
|
|
if(offset == 0) {
|
|
result = values[0];
|
|
} else if(offset == 1) {
|
|
result = values[1];
|
|
} else if(offset == 2) {
|
|
result = values[2];
|
|
} else {
|
|
result = values[3];
|
|
}
|
|
|
|
${r.output} = vec4(${a}, 0., 0., 0.);
|
|
}
|
|
`}},SQ=class{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let r=Br();this.outputShape=e,this.enableShapeUniforms=sa(this.outputShape.length);let a="",n="result";t&&(n="floor(result * 255. + 0.5)");for(let s=0;s<=1;s++)for(let i=0;i<=1;i++){let o=s*2+i;a+=`
|
|
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 = ${r.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?Ex():Nx(e)}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
|
|
vec4 result = vec4(0.);
|
|
int flatIndex, r, c, offset;
|
|
ivec3 localCoords;
|
|
vec2 uv;
|
|
vec4 values;
|
|
|
|
${a}
|
|
|
|
${r.output} = ${n};
|
|
}
|
|
`}},$I={};De($I,{bindVertexProgramAttributeStreams:()=>VI,createBufferFromOutputTexture:()=>jI,createFloat16MatrixTexture:()=>_I,createFloat16PackedMatrixTexture:()=>WI,createFloat32MatrixTexture:()=>DI,createIndexBuffer:()=>zI,createPackedMatrixTexture:()=>BI,createUnsignedBytesMatrixTexture:()=>LI,createVertexBuffer:()=>OI,createVertexShader:()=>PI,downloadByteEncodedFloatMatrixFromOutputTexture:()=>qI,downloadFloat32MatrixFromBuffer:()=>HI,downloadMatrixFromPackedOutputTexture:()=>XI,downloadPackedMatrixFromBuffer:()=>KI,getInternalFormatForFloat16MatrixTexture:()=>Mx,getInternalFormatForFloat16PackedMatrixTexture:()=>Ox,getInternalFormatForFloat32MatrixTexture:()=>Fx,getInternalFormatForPackedMatrixTexture:()=>Px,getInternalFormatForUnsignedBytesMatrixTexture:()=>$x,uploadDenseMatrixToTexture:()=>UI,uploadPixelDataToTexture:()=>GI});function PI(e){let t=Br(),r=`${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 oI(e,r)}function OI(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 pI(e,t)}function zI(e){let t=new Uint16Array([0,1,2,2,1,3]);return hI(e,t)}function Ch(e,t,r,a,n,s){fI(t,r);let i=cI(e),o=e.TEXTURE_2D;return we(e,()=>e.bindTexture(o,i)),we(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),we(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),we(e,()=>e.texParameteri(o,e.TEXTURE_MIN_FILTER,e.NEAREST)),we(e,()=>e.texParameteri(o,e.TEXTURE_MAG_FILTER,e.NEAREST)),Y().getNumber("WEBGL_VERSION")===1?we(e,()=>e.texImage2D(o,0,a,t,r,0,n,s,null)):we(e,()=>e.texStorage2D(o,1,a,t,r)),we(e,()=>e.bindTexture(e.TEXTURE_2D,null)),{texture:i,texShape:[r,t]}}function Fx(e){return e.internalFormatFloat}function DI(e,t,r,a){let[n,s]=Th(t,r);return Ch(e,n,s,Fx(a),a.textureFormatFloat,e.FLOAT)}function Mx(e){return e.internalFormatHalfFloat}function _I(e,t,r,a){let[n,s]=Th(t,r);return Ch(e,n,s,Mx(a),a.textureFormatFloat,a.textureTypeHalfFloat)}function $x(e){return e.downloadTextureFormat}function LI(e,t,r,a){let[n,s]=Th(t,r);return Ch(e,n,s,$x(a),e.RGBA,e.UNSIGNED_BYTE)}function Px(e){return e.internalFormatPackedFloat}function BI(e,t,r,a){let[n,s]=pd(t,r);return Ch(e,n,s,Px(a),e.RGBA,e.FLOAT)}function Ox(e){return e.internalFormatPackedHalfFloat}function WI(e,t,r,a){let[n,s]=pd(t,r);return Ch(e,n,s,Ox(a),e.RGBA,a.textureTypeHalfFloat)}function VI(e,t,r){return we(e,()=>e.bindBuffer(e.ARRAY_BUFFER,r)),yy(e,t,"clipSpacePos",r,3,20,0)&&yy(e,t,"uv",r,2,20,12)}function UI(e,t,r,a,n,s){we(e,()=>e.bindTexture(e.TEXTURE_2D,t));let i,o,l;n instanceof Uint8Array?(i=new Uint8Array(r*a*4),o=e.UNSIGNED_BYTE,l=e.RGBA):(i=new Float32Array(r*a*4),o=e.FLOAT,l=s.internalFormatPackedFloat),i.set(n),Y().getNumber("WEBGL_VERSION")===2?we(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,a,e.RGBA,o,i)):we(e,()=>e.texImage2D(e.TEXTURE_2D,0,l,r,a,0,e.RGBA,o,i)),we(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function GI(e,t,r){we(e,()=>e.bindTexture(e.TEXTURE_2D,t)),r.data instanceof Uint8Array?Y().getNumber("WEBGL_VERSION")===2?we(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,r.width,r.height,e.RGBA,e.UNSIGNED_BYTE,r.data)):we(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,r.width,r.height,0,e.RGBA,e.UNSIGNED_BYTE,r.data)):Y().getNumber("WEBGL_VERSION")===2?we(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,r)):we(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,r)),we(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function jI(e,t,r,a){let n=e.createBuffer();we(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,n));let s=4*4*t*r;return we(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,s,e.STREAM_READ)),we(e,()=>e.readPixels(0,0,r,t,e.RGBA,e.FLOAT,0)),we(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),n}function HI(e,t,r){let a=e,n=new Float32Array(r);return a.bindBuffer(a.PIXEL_PACK_BUFFER,t),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,n),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),n}function qI(e,t,r,a){let[n,s]=Th(t,r),i=4,o=new Uint8Array(bJ(t*r,i));return we(e,()=>e.readPixels(0,0,n,s,a.downloadTextureFormat,e.UNSIGNED_BYTE,o)),new Float32Array(o.buffer)}function KI(e,t,r,a,n,s,i,o){let l=e,d=new Float32Array(vJ(s,i));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,d),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),d}function XI(e,t,r){let a=new Float32Array(t*r*4);return we(e,()=>e.readPixels(0,0,r,t,e.RGBA,e.FLOAT,a)),a}var uu=class{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];let t=Y().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,Zm(t,e)):this.gl=pn(t);let r="WEBGL_color_buffer_float",a="EXT_color_buffer_half_float";if(Y().getNumber("WEBGL_VERSION")===1){let n="OES_texture_float",s="OES_texture_half_float";if(this.textureFloatExtension=fp(this.gl,n),Sa(this.gl,s))this.textureHalfFloatExtension=fp(this.gl,s);else if(Y().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support half float textures, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.");if(this.colorBufferFloatExtension=this.gl.getExtension(r),Sa(this.gl,a))this.colorBufferHalfFloatExtension=fp(this.gl,a);else if(Y().get("WEBGL_FORCE_F16_TEXTURES"))throw new Error("GL context does not support color renderable half floats, yet the environment flag WEBGL_FORCE_F16_TEXTURES is set to true.")}else if(r="EXT_color_buffer_float",Sa(this.gl,r))this.colorBufferFloatExtension=this.gl.getExtension(r);else if(Sa(this.gl,a))this.colorBufferHalfFloatExtension=this.gl.getExtension(a);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=OI(this.gl),this.indexBuffer=zI(this.gl),this.framebuffer=mI(this.gl),this.textureConfig=Cx(this.gl,this.textureHalfFloatExtension)}get debug(){return Y().getBool("DEBUG")}dispose(){if(this.disposed)return;this.program!=null&&console.warn("Disposing a GPGPUContext that still has a bound WebGLProgram. This is probably a resource leak, delete the program with GPGPUContext.deleteProgram before disposing."),this.outputTexture!=null&&console.warn("Disposing a GPGPUContext that still has a bound output matrix texture. This is probably a resource leak, delete the output matrix texture with GPGPUContext.deleteMatrixTexture before disposing.");let e=this.gl;we(e,()=>e.finish()),we(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),we(e,()=>e.deleteFramebuffer(this.framebuffer)),we(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),we(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),we(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),DI(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),_I(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),LI(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),GI(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,r,a){this.throwIfDisposed(),UI(this.gl,e,t,r,a,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),WI(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),BI(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(Ay(this.gl,this.framebuffer),this.outputTexture=null),we(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,r){return this.downloadMatrixDriver(e,()=>qI(this.gl,t,r,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,r,a,n,s){return KI(this.gl,e,t,r,a,n,s,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return HI(this.gl,e,t)}createBufferFromTexture(e,t,r){this.bindTextureToFrameBuffer(e);let a=jI(this.gl,t,r,this.textureConfig);return this.unbindTextureToFrameBuffer(),a}createAndWaitForFence(){let e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,r;if(Y().getBool("WEBGL_FENCE_API_ENABLED")){let a=e,n=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),r=()=>{let s=a.clientWaitSync(n,0,0);return s===a.ALREADY_SIGNALED||s===a.CONDITION_SATISFIED},t=n}else Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),r=()=>this.isQueryAvailable(t,Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):r=()=>!0;return{query:t,isFencePassed:r}}downloadMatrixFromPackedTexture(e,t,r){return this.downloadMatrixDriver(e,()=>XI(this.gl,t,r))}createProgram(e){this.throwIfDisposed();let t=this.gl;this.vertexShader==null&&(this.vertexShader=PI(t));let r=uI(t);return we(t,()=>t.attachShader(r,this.vertexShader)),we(t,()=>t.attachShader(r,e)),dI(t,r),this.debug&&Lc(t,r),this.vertexAttrsAreBound||(this.setProgram(r),this.vertexAttrsAreBound=VI(t,this.program,this.vertexBuffer)),r}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&we(this.gl,()=>this.gl.deleteProgram(e))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&Lc(this.gl,this.program),we(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,r=!0){return this.throwIfDisposed(),r?yI(this.gl,e,t):AI(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),we(this.gl,()=>this.gl.getAttribLocation(e,t))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,r){this.throwIfDisposed(),this.throwIfNoProgram(),xI(this.gl,e,t,r)}setOutputMatrixTexture(e,t,r){this.setOutputMatrixTextureDriver(e,r,t)}setOutputPackedMatrixTexture(e,t,r){this.throwIfDisposed();let[a,n]=pd(t,r);this.setOutputMatrixTextureDriver(e,a,n)}setOutputMatrixWriteRegion(e,t,r,a){this.setOutputMatrixWriteRegionDriver(r,e,a,t)}setOutputPackedMatrixWriteRegion(e,t,r,a){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){this.program!=null&&Lc(this.gl,this.program),mp(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();let e=this.gl;this.debug&&this.debugValidate(),we(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),we(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=fp(this.gl,Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2?"EXT_disjoint_timer_query_webgl2":"EXT_disjoint_timer_query")),this.disjointQueryTimerExtension}getQueryTimerExtensionWebGL2(){return this.getQueryTimerExtension()}getQueryTimerExtensionWebGL1(){return this.getQueryTimerExtension()}beginQuery(){if(Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){let r=this.gl,a=this.getQueryTimerExtensionWebGL2(),n=r.createQuery();return r.beginQuery(a.TIME_ELAPSED_EXT,n),n}let e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){let t=this.gl,r=this.getQueryTimerExtensionWebGL2();t.endQuery(r.TIME_ELAPSED_EXT);return}let e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){return await w.repeatedTry(()=>this.disposed||this.isQueryAvailable(e,Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))}getQueryTime(e,t){if(t===0)return null;if(t===2){let r=this.gl;return r.getQueryParameter(e,r.QUERY_RESULT)/1e6}else{let r=this.getQueryTimerExtensionWebGL1();return r.getQueryObjectEXT(e,r.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(t===0)return!0;if(t===2){let r=this.gl,a=this.getQueryTimerExtensionWebGL2(),n=r.getQueryParameter(e,r.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(a.GPU_DISJOINT_EXT)),n&&!this.disjoint}else{let r=this.getQueryTimerExtensionWebGL1(),a=r.getQueryObjectEXT(e,r.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),a&&!this.disjoint}}pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){let e=TQ(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=e;++t){let{resolveFn:r}=this.itemsToPoll[t];r()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),!(this.itemsToPoll.length>1)&&w.repeatedTry(()=>(this.pollItems(),this.itemsToPoll.length===0))}bindTextureToFrameBuffer(e){this.throwIfDisposed(),Bc(this.gl,e,this.framebuffer),this.debug&&mp(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(Bc(this.gl,this.outputTexture,this.framebuffer),this.debug&&mp(this.gl)):Ay(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);let r=t();return this.unbindTextureToFrameBuffer(),r}setOutputMatrixTextureDriver(e,t,r){this.throwIfDisposed();let a=this.gl;Bc(a,e,this.framebuffer),this.debug&&mp(a),this.outputTexture=e,we(a,()=>a.viewport(0,0,t,r)),we(a,()=>a.scissor(0,0,t,r))}setOutputMatrixWriteRegionDriver(e,t,r,a){this.throwIfDisposed(),we(this.gl,()=>this.gl.scissor(e,t,r,a))}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 TQ(e){let t=0;for(;t<e.length&&e[t]();++t);return t-1}var{addImpl:CQ,bincountImpl:ZI,bincountReduceImpl:NQ,ceilImpl:EQ,concatImpl:RQ,equalImpl:FQ,expImpl:MQ,expm1Impl:$Q,floorImpl:PQ,gatherNdImpl:OQ,gatherV2Impl:zQ,greaterImpl:DQ,greaterEqualImpl:_Q,lessImpl:LQ,lessEqualImpl:BQ,linSpaceImpl:WQ,logImpl:VQ,maxImpl:UQ,maximumImpl:GQ,minimumImpl:jQ,multiplyImpl:HQ,negImpl:qQ,notEqualImpl:KQ,prodImpl:XQ,rangeImpl:ZQ,rsqrtImpl:YQ,sigmoidImpl:JQ,simpleAbsImpl:YI,sliceImpl:QQ,sparseFillEmptyRowsImpl:eee,sparseReshapeImpl:tee,sparseSegmentReductionImpl:JI,sqrtImpl:ree,stridedSliceImpl:aee,stringNGramsImpl:nee,stringSplitImpl:see,stringToHashBucketFastImpl:iee,subImpl:oee,tileImpl:lee,topKImpl:uee,transposeImpl:zx,uniqueImpl:dee}=Km;function QI(e,t){return["x","y","z","w","u","v"].slice(0,t).map(r=>`${e}.${r}`)}function $r(e,t){return t===1?[e]:QI(e,t)}function pee(e,t){if(e===1)return"rc";let r="";for(let a=0;a<e;a++)r+=t[a],a<e-1&&(r+=",");return r}var hee=class{constructor(e){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.enableShapeUniforms=sa(this.outputShape.length),this.rank===0)this.userCode=`
|
|
void main() {
|
|
setOutput(vec4(getA(), 0., 0., 0.));
|
|
}
|
|
`;else{let t=$r("rc",this.rank),r=vt(this.rank),a=this.getOutOfBoundsCondition(t),n=this.getSetup(t),s=this.getOutput(t);this.userCode=`
|
|
void main() {
|
|
${r} rc = getOutputCoords();
|
|
|
|
if(${a}) {
|
|
setOutput(vec4(0));
|
|
} else {
|
|
${n}
|
|
|
|
setOutput(vec4(${s}));
|
|
}
|
|
}
|
|
`}}getSourceCoordsArr(e){let t=[];for(let r=0;r<=1;r++)for(let a=0;a<=1;a++){let n=`${r===0?"r":"rp1"}, ${a===0?"c":"cp1"}`;for(let s=2;s<this.rank;s++)n=`${e[e.length-1-s]},`+n;t.push(n)}return t}getOutOfBoundsCondition(e){if(this.rank===1)return`rc > ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`;let t="";for(let r=this.rank-2;r<this.rank;r++)t+=`${e[r]} >= ${this.enableShapeUniforms?`outShape[${r}]`:this.outputShape[r]}`,r<this.rank-1&&(t+="||");return t}getSetup(e){if(this.rank===1)return"";let t=e.slice(-2),r=this.enableShapeUniforms?`outShape[${this.rank} - 1]`:this.outputShape[this.rank-1],a=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 >= ${r};
|
|
bool rEdge = rp1 >= ${a};
|
|
`}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]})`}},e8=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=sa(this.outputShape.length);let r="";for(let a=0;a<4;a++){let n="thisRC = rc;";a%2===1&&(n+="thisRC.z += 1;"),a>1&&(n+="thisRC.y += 1;"),r+=`
|
|
${n}
|
|
${a>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[${a}] =
|
|
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
|
|
${a>0?"}":""}
|
|
`}this.userCode=`
|
|
${cee(t,this.enableShapeUniforms)}
|
|
${this.enableShapeUniforms?Ex():Nx(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]};
|
|
|
|
${r}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}};function cee(e,t){return`
|
|
ivec3 inputCoordsFromReshapedOutCoords(int index) {
|
|
${t?PJ(["r","c","d"],"inputShape"):Sl(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`}var fee=class{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}acquireTexture(e,t,r){let a=G3(t,r),n=j3(e,a,r);n in this.freeTextures||(this.freeTextures[n]=[]),n in this.usedTextures||(this.usedTextures[n]=[]);let s=U3(e,a,this.gpgpu.gl,this.gpgpu.textureConfig,r);if(this.freeTextures[n].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=s,this.log();let o=this.freeTextures[n].shift();return this.usedTextures[n].push(o),o}let i;return a===3?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):a===4?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):a===1?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):a===0?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):a===2&&(i=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[n].push(i),this.numUsedTextures++,this._numBytesAllocated+=s,this.log(),i}releaseTexture(e,t,r,a){if(this.freeTextures==null)return;let n=G3(r,a),s=j3(t,n,a);s in this.freeTextures||(this.freeTextures[s]=[]);let i=U3(t,n,this.gpgpu.gl,this.gpgpu.textureConfig,a),o=Y().get("WEBGL_DELETE_TEXTURE_THRESHOLD");o!==-1&&this._numBytesAllocated>o?(this.gpgpu.deleteMatrixTexture(e.texture),this._numBytesAllocated-=i):(this.freeTextures[s].push(e),this.numFreeTextures++,this._numBytesFree+=i),this.numUsedTextures--;let l=this.usedTextures[s],d=l.indexOf(e);if(d<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l.splice(d,1),this.log()}log(){if(!this.logEnabled)return;let e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);let t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures!=null){for(let e in this.freeTextures)this.freeTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});for(let e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}};function mee(e,t){let r=e;if(t===r.R32F)return 4;if(t===r.R16F)return 2;if(t===r.RGBA32F||t===e.RGBA)return 16;if(t===r.RGBA16F)return 8;if(t===r.RGBA8)return 4;throw new Error(`Unknown internal format ${t}`)}function U3(e,t,r,a,n){let s=gee(t,a),i;if(n){let[l,d]=pd(e[0],e[1]);i=l*d}else{let[l,d]=Th(e[0],e[1]);i=l*d}let o=mee(r,s);return i*o}function gee(e,t){switch(e){case 3:return Px(t);case 4:return Ox(t);case 1:return Fx(t);case 0:return Mx(t);case 2:return $x(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function yee(e){return Y().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?3:1:e?4:0}function G3(e,t){if(e===1)return 3;if(e===0||e==null)return yee(t);if(e===3||e===2)return 2;throw new Error(`Unknown logical texture type ${e}`)}function j3(e,t,r){return`${e[0]}_${e[1]}_${t}_${r}`}var Gn=class{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=sa(this.outputShape.length),this.userCode=`
|
|
float unaryOperation(float x) {
|
|
${t}
|
|
}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
float y = unaryOperation(x);
|
|
|
|
setOutput(y);
|
|
}
|
|
`}},Ka="if (isnan(x)) return x;",Aee="return x;",H3="return abs(x);",xee="return (x >= 0.0) ? x : (exp(x) - 1.0);",bee=Ka+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,vee=Ka+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,Zl="return x;",wee="return 1.0 / (1.0 + exp(-1.0 * x));",kee="return x;",Iee=`
|
|
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;
|
|
`,See=`
|
|
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;
|
|
`,Tee=`
|
|
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="return 1.0 / (1.0 + exp(-1.0 * x));",co=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=sa(this.outputShape.length),this.userCode=`
|
|
vec4 unaryOperation(vec4 x) {
|
|
${t}
|
|
}
|
|
|
|
void main() {
|
|
vec4 x = getAAtOutCoords();
|
|
vec4 y = unaryOperation(x);
|
|
|
|
setOutput(y);
|
|
}
|
|
`}},Nee=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=sa(this.outputShape.length);let t=e.length,r=$r("rc",t),a=vt(t),n=pee(t,r),s=r.slice(-2),i=t<=1?"rc":`vec2(${s.join(",")})`;this.userCode=`
|
|
void main() {
|
|
${a} rc = getOutputCoords();
|
|
vec4 packedInput = getA(${n});
|
|
|
|
setOutput(getChannel(packedInput, ${i}));
|
|
}
|
|
`}},Eee=Ha.whereImpl,Ree=1e-7,Fee=1e-4,R1={};function Mee(e){return e in R1||(R1[e]={}),R1[e]}var $ee=Y().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),Pee=600;function Oee(){return Y().global.screen==null?1024:Y().global.screen.height*Y().global.screen.width*window.devicePixelRatio*Pee/1024/1024}var t8=class extends Iu{constructor(e){super();if(this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.pendingDeletes=0,this.disposed=!1,!Y().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let t;if(e!=null){if(e instanceof uu)t=e;else{let r=pn(Y().getNumber("WEBGL_VERSION"),e);t=new uu(r)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{let r=pn(Y().getNumber("WEBGL_VERSION"));t=new uu(r),this.binaryCache=Mee(Y().getNumber("WEBGL_VERSION")),this.gpgpuCreatedLocally=!0}this.gpgpu=t,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new fee(this.gpgpu),this.numMBBeforeWarning=Oee(),this.texData=new Dp(this,kr())}nextDataId(){return t8.nextDataId++}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}write(e,t,r){if((Y().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||Y().getBool("DEBUG"))&&this.checkNumericalProblems(e),r==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let a={id:this.nextDataId()};return this.texData.set(a,{shape:t,dtype:r,values:e,usage:1,refCount:1}),a}refCount(e){return this.texData.has(e)?this.texData.get(e).refCount:0}incRef(e){let t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){let t=this.texData.get(e);t.refCount--}}move(e,t,r,a,n){if(Y().getBool("DEBUG")&&this.checkNumericalProblems(t),a==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:r,dtype:a,values:t,usage:1,refCount:n})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){let t=this.texData.get(e),{values:r,dtype:a,complexTensorInfos:n,slice:s,shape:i,isPacked:o}=t;if(s!=null){let p;o?p=new co(i,Zl):p=new Gn(i,Zl);let h=this.runWebGLProgram(p,[{dataId:e,shape:i,dtype:a}],a),c=this.readSync(h.dataId);return this.disposeIntermediateTensorInfo(h),c}if(r!=null)return this.convertAndCacheOnCPU(e);if(a==="string")return r;let l=this.activeTimers!=null,d;l&&(d=w.now());let u;if(a==="complex64"){let p=this.readSync(n.real.dataId),h=this.readSync(n.imag.dataId);u=N.mergeRealAndImagArrays(p,h)}else u=this.getValuesFromTexture(e);return l&&(this.downloadWaitMs+=w.now()-d),this.convertAndCacheOnCPU(e,u)}async read(e){if(this.pendingRead.has(e)){let c=this.pendingRead.get(e);return new Promise(f=>c.push(f))}let t=this.texData.get(e),{values:r,shape:a,slice:n,dtype:s,complexTensorInfos:i,isPacked:o}=t;if(n!=null){let c;o?c=new co(a,Zl):c=new Gn(a,Zl);let f=this.runWebGLProgram(c,[{dataId:e,shape:a,dtype:s}],s),m=this.read(f.dataId);return this.disposeIntermediateTensorInfo(f),m}if(r!=null)return this.convertAndCacheOnCPU(e);if(Y().getBool("DEBUG")&&!Y().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&Y().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let l=null,d;if(s!=="complex64"&&Y().get("WEBGL_BUFFER_SUPPORTED")){d=this.decode(e);let c=this.texData.get(d.dataId);l=this.gpgpu.createBufferFromTexture(c.texture.texture,...Mc(a))}this.pendingRead.set(e,[]),s!=="complex64"&&await this.gpgpu.createAndWaitForFence();let u;if(s==="complex64"){let c=await Promise.all([this.read(i.real.dataId),this.read(i.imag.dataId)]),f=c[0],m=c[1];u=N.mergeRealAndImagArrays(f,m)}else if(l==null)u=this.getValuesFromTexture(e);else{let c=w.sizeFromShape(a);u=this.gpgpu.downloadFloat32MatrixFromBuffer(l,c)}if(d!=null&&this.disposeIntermediateTensorInfo(d),l!=null){let c=this.gpgpu.gl;we(c,()=>c.deleteBuffer(l))}let p=this.convertAndCacheOnCPU(e,u),h=this.pendingRead.get(e);return this.pendingRead.delete(e),h.forEach(c=>c(p)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&kr().removeDataId(e,this),this.pendingDeletes--),p}readToGPU(e,t={}){let r=this.texData.get(e),{values:a,shape:n,slice:s,dtype:i,isPacked:o,texture:l}=r;if(i==="complex64")throw new Error("Does not support reading texture for complex64 dtype.");if(s!=null){let h;o?h=new co(n,Zl):h=new Gn(n,Zl);let c=this.runWebGLProgram(h,[{dataId:e,shape:n,dtype:i}],i),f=this.readToGPU(c,t);return this.disposeIntermediateTensorInfo(c),f}if(l==null)throw a!=null?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");let d=this.decode(e,t.customTexShape),u=kr().makeTensorFromDataId(d.dataId,d.shape,d.dtype),p=this.texData.get(d.dataId);return{tensorRef:u,...p.texture}}bufferSync(e){let t=this.readSync(e.dataId),r=t;if(e.dtype==="string")try{r=t.map(a=>w.decodeString(a))}catch(a){throw new Error("Failed to decode encoded string bytes into utf-8")}return Le(e.shape,e.dtype,r)}checkNumericalProblems(e){if(e!=null)for(let t=0;t<e.length;t++){let r=e[t];if(!sI(r))throw Y().getBool("WEBGL_RENDER_FLOAT32_CAPABLE")?Error(`The value ${r} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`):Error(`The value ${r} cannot be represented on this device.`)}}getValuesFromTexture(e){let{shape:t,dtype:r,isPacked:a}=this.texData.get(e),n=w.sizeFromShape(t);if(Y().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){let p=this.decode(e),h=this.texData.get(p.dataId),c=this.gpgpu.downloadMatrixFromPackedTexture(h.texture.texture,...Mc(t)).subarray(0,n);return this.disposeIntermediateTensorInfo(p),c}let s=Y().getBool("WEBGL_PACK")&&a===!0,i=s?Wc(t):t,o=s?new kQ(i):new wQ(i),l=this.runWebGLProgram(o,[{shape:i,dtype:r,dataId:e}],"float32"),d=this.texData.get(l.dataId),u=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(d.texture.texture,d.texShape[0],d.texShape[1]).subarray(0,n);return this.disposeIntermediateTensorInfo(l),u}timerAvailable(){return Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}time(e){let t=this.activeTimers,r=[],a=!1;this.programTimersStack==null?(this.programTimersStack=r,a=!0):this.activeTimers.push(r),this.activeTimers=r,e();let n=w.flatten(this.activeTimers.map(o=>o.query)).filter(o=>o!=null),s=w.flatten(this.activeTimers.map(o=>o.name)).filter(o=>o!=null);this.activeTimers=t,a&&(this.programTimersStack=null);let i={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>{if(Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){let o=await Promise.all(n);i.kernelMs=w.sum(o),i.getExtraProfileInfo=()=>o.map((l,d)=>({name:s[d],ms:l})).map(l=>`${l.name}: ${l.ms}`).join(", ")}else i.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,i})()}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:w.now(),endMs:null}}endTimer(e){return Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=w.now(),e)}async getQueryTime(e){if(Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0)return this.gpgpu.waitForQueryAndGetTime(e);let t=e;return t.endMs-t.startMs}disposeData(e,t=!1){if(this.pendingDisposal.has(e))return!1;if(!this.texData.has(e))return!0;if(t?this.texData.get(e).refCount=0:this.texData.get(e).refCount--,!t&&this.texData.get(e).refCount>0)return!1;if(this.pendingRead.has(e))return this.pendingDisposal.add(e),this.pendingDeletes++,!1;this.releaseGPUData(e);let{complexTensorInfos:r}=this.texData.get(e);return r!=null&&(this.disposeData(r.real.dataId,t),this.disposeData(r.imag.dataId,t)),this.texData.delete(e),!0}releaseGPUData(e){let{texture:t,dtype:r,texShape:a,usage:n,isPacked:s,slice:i}=this.texData.get(e),o=i&&i.origDataId||e,l=this.dataRefCount.get(o);l>1?this.dataRefCount.set(o,l-1):(this.dataRefCount.delete(o),t!=null&&(this.numBytesInGPU-=this.computeBytes(a,r),this.textureManager.releaseTexture(t,a,n,s)));let d=this.texData.get(e);d.texture=null,d.texShape=null,d.isPacked=!1,d.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture.texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=$ee){return Y().getBool("WEBGL_CPU_FORWARD")&&e.every(r=>this.texData.get(r.dataId).texture==null&&w.sizeFromShape(r.shape)<t)}getGPGPUContext(){return this.gpgpu}where(e){N.warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");let t=e.dataSync();return Eee(e.shape,t)}packedUnaryOp(e,t,r){let a=new co(e.shape,t),n=this.compileAndRun(a,[e],r);return kr().makeTensorFromDataId(n.dataId,n.shape,n.dtype)}abs(e){if(this.shouldExecuteOnCPU([e])&&e.dtype!=="complex64"){let a=YI(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,a)}if(Y().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,H3,e.dtype);let t=new Gn(e.shape,H3),r=this.compileAndRun(t,[e]);return kr().makeTensorFromDataId(r.dataId,r.shape,r.dtype)}makeTensorInfo(e,t,r){let a;if(t==="string"&&r!=null&&r.length>0&&w.isString(r[0])){let n=r.map(s=>w.encodeString(s));a=this.write(n,e,t)}else a=this.write(r,e,t);return this.texData.get(a).usage=null,{dataId:a,shape:e,dtype:t}}makeOutput(e,t,r){let{dataId:a}=this.makeTensorInfo(e,t,r);return kr().makeTensorFromDataId(a,e,t,this)}unpackTensor(e){let t=new Nee(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){let t=new hee(e.shape),r=!0;return this.runWebGLProgram(t,[e],e.dtype,null,r)}packedReshape(e,t){let r=[To(e.shape),...Co(e.shape)],a={dtype:e.dtype,shape:r,dataId:e.dataId},n=[To(t),...Co(t)],s=new e8(n,r),i=!0,o=[r],l=this.runWebGLProgram(s,[a],e.dtype,o,i);return{dataId:l.dataId,shape:t,dtype:l.dtype}}decode(e,t){let r=this.texData.get(e),{isPacked:a,shape:n,dtype:s}=r;if(t!=null){let p=w.sizeFromShape(n),h=t[0]*t[1]*4;w.assert(p<=h,()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data.")}let i=Wc(n),o;a?o=new vQ(i):o=new bQ(i);let l=!0,d=[t!=null?t:Mc(i)],u=this.runWebGLProgram(o,[{shape:i,dtype:s,dataId:e}],s,d,l,t);return{dtype:s,shape:n,dataId:u.dataId}}runWebGLProgram(e,t,r,a,n=!1,s){let i=this.makeTensorInfo(e.outputShape,r),o=this.texData.get(i.dataId);if(e.packedOutput&&(o.isPacked=!0),e.outPackingScheme===0){let g=s!=null?s:Mc(e.outputShape);o.texShape=g.map(y=>y*2)}if(e.outTexUsage!=null&&(o.usage=e.outTexUsage),w.sizeFromShape(i.shape)===0)return o.values=w.getTypedArrayFromDType(i.dtype,0),i;let l=[],d=t.map(g=>{if(g.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let y=this.texData.get(g.dataId);if(y.texture==null){if(!e.packedInputs&&w.sizeFromShape(g.shape)<=Y().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:g.shape,texData:null,isUniform:!0,uniformValues:y.values};e.packedInputs&&(y.isPacked=!0,y.shape=g.shape)}if(this.uploadToGPU(g.dataId),!!y.isPacked!=!!e.packedInputs)g=y.isPacked?this.unpackTensor(g):this.packTensor(g),l.push(g),y=this.texData.get(g.dataId);else if(y.isPacked&&!Op(y.shape,g.shape)){let A=g,x=g.shape;g.shape=y.shape,g=this.packedReshape(g,x),l.push(g),y=this.texData.get(g.dataId),A.shape=x}return{shape:g.shape,texData:y,isUniform:!1}});this.uploadToGPU(i.dataId);let u={shape:i.shape,texData:o,isUniform:!1},p=xQ(e,d,u),h=this.getAndSaveBinary(p,()=>yQ(this.gpgpu,e,d,u)),c=this.activeTimers!=null,f;c&&(f=this.startTimer()),AQ(this.gpgpu,h,d,u,a),l.forEach(g=>this.disposeIntermediateTensorInfo(g)),c&&(f=this.endTimer(f),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(f)}));let m=Y().get("WEBGL_FLUSH_THRESHOLD");if(m>0){let g=w.now();g-this.lastGlFlushTime>m&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=g)}if(!Y().getBool("WEBGL_LAZILY_UNPACK")&&o.isPacked&&n===!1){let g=this.unpackTensor(i);return this.disposeIntermediateTensorInfo(i),g}return i}compileAndRun(e,t,r,a,n=!1){return r=r||t[0].dtype,this.runWebGLProgram(e,t,r,a,n)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(Y().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach(e=>{this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram),delete this.binaryCache[e]}),this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement!="undefined"&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)}floatPrecision(){return this.floatPrecisionValue==null&&(this.floatPrecisionValue=q(()=>{if(!Y().get("WEBGL_RENDER_FLOAT32_ENABLED")){let e=Y().getBool("DEBUG");Y().set("DEBUG",!1);let t=this.abs(Se(1e-8)).dataSync()[0];if(Y().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?Ree:Fee}uploadToGPU(e){let t=this.texData.get(e),{shape:r,dtype:a,values:n,texture:s,usage:i,isPacked:o}=t;if(s!=null)return;let l=this.activeTimers!=null,d;l&&(d=w.now());let u=t.texShape;if(u==null&&(u=wI(r,o),t.texShape=u),n!=null){let p=Wc(r),h,c=u[1],f=u[0],m=n instanceof Uint8Array||n instanceof Uint8ClampedArray;(o||!m)&&([c,f]=pd(u[0],u[1])),o?h=new SQ(p,m):h=new IQ(p,m);let g=m?[f,c]:u,y=this.makeTensorInfo(g,a),A=this.texData.get(y.dataId);m?A.usage=2:A.usage=1,A.texShape=g,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(y.dataId),c,f,n);let x=[[f,c]],b=!0,v=this.runWebGLProgram(h,[y],a,x,b),C=this.texData.get(v.dataId);t.texture=C.texture,t.texShape=C.texShape,t.isPacked=C.isPacked,t.usage=C.usage,this.disposeIntermediateTensorInfo(y),this.texData.delete(v.dataId),t.values=null,l&&(this.uploadWaitMs+=w.now()-d)}else{let p=this.acquireTexture(u,i,a,o);t.texture=p}}convertAndCacheOnCPU(e,t){let r=this.texData.get(e),{dtype:a}=r;return this.releaseGPUData(e),t!=null&&(r.values=zee(t,a)),r.values}acquireTexture(e,t,r,a){if(this.numBytesInGPU+=this.computeBytes(e,r),!this.warnedAboutMemory&&this.numBytesInGPU>this.numMBBeforeWarning*1024*1024){let n=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${n} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,a)}computeBytes(e,t){return e[0]*e[1]*w.bytesPerElement(t)}},Nh=t8;Nh.nextDataId=0;function zee(e,t){if(t==="float32"||t==="complex64")return e;if(t==="int32"||t==="bool"){let r=t==="int32"?new Int32Array(e.length):new Uint8Array(e.length);for(let a=0;a<r.length;++a)r[a]=Math.round(e[a]);return r}else throw new Error(`Unknown dtype ${t}`)}var Dee="0.0.0";function r8(){Y().set("WEBGL_FORCE_F16_TEXTURES",!0)}nh.isBrowser()&&Al("webgl",()=>new Nh,2);var _ee={forceHalfFloat:r8},a8=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,wu=class{constructor(e,t,r){this.variableNames=["A","B"],this.outputShape=N.assertAndGetBroadcastShape(t,r),this.enableShapeUniforms=sa(this.outputShape.length),this.userCode=`
|
|
float binaryOperation(float a, float b) {
|
|
${e}
|
|
}
|
|
|
|
void main() {
|
|
float a = getAAtOutCoords();
|
|
float b = getBAtOutCoords();
|
|
setOutput(binaryOperation(a, b));
|
|
}
|
|
`}},Jm=`
|
|
result.r = isNaN.r > 0. ? NAN : result.r;
|
|
result.g = isNaN.g > 0. ? NAN : result.g;
|
|
result.b = isNaN.b > 0. ? NAN : result.b;
|
|
result.a = isNaN.a > 0. ? NAN : result.a;
|
|
`,Eh=class{constructor(e,t,r,a=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=N.assertAndGetBroadcastShape(t,r);let n=this.outputShape.length;this.enableShapeUniforms=sa(n);let s="";if(a)if(n===0||w.sizeFromShape(this.outputShape)===1)s=`
|
|
result.y = 0.;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;else if(s=`
|
|
${vt(n)} coords = getOutputCoords();
|
|
`,n===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=$r("coords",n);this.enableShapeUniforms?s+=`
|
|
bool nextRowOutOfBounds =
|
|
(${i[n-2]} + 1) >= outShape[${n} - 2];
|
|
bool nextColOutOfBounds =
|
|
(${i[n-1]} + 1) >= outShape[${n} - 1];
|
|
result.y = nextColOutOfBounds ? 0. : result.y;
|
|
result.z = nextRowOutOfBounds ? 0. : result.z;
|
|
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
|
|
`:s+=`
|
|
bool nextRowOutOfBounds =
|
|
(${i[n-2]} + 1) >= ${this.outputShape[n-2]};
|
|
bool nextColOutOfBounds =
|
|
(${i[n-1]} + 1) >= ${this.outputShape[n-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 ha(e){let{inputs:t,backend:r}=e,{x:a}=t;return r.incRef(a.dataId),{dataId:a.dataId,shape:a.shape,dtype:a.dtype}}var Lee={kernelName:ui,backendName:"webgl",kernelFunc:ha};function Bi(e){let{inputs:t,backend:r}=e,{real:a,imag:n}=t,s=r.makeTensorInfo(a.shape,"complex64"),i=r.texData.get(s.dataId),o=ha({inputs:{x:a},backend:r}),l=ha({inputs:{x:n},backend:r});return i.complexTensorInfos={real:o,imag:l},s}var Bee={kernelName:Lp,backendName:"webgl",kernelFunc:Bi},n8="return (a < 0.) ? b * a : a;",s8=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function Wee(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{alpha:s}=a,i=r.makeTensorInfo([],"float32",w.createScalarValue(s,"float32")),o=Y().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Eh(s8,n.shape,i.shape):new wu(n8,n.shape,i.shape),l=r.runWebGLProgram(o,[n,i],"float32");return r.disposeIntermediateTensorInfo(i),l}var Vee={kernelName:di,backendName:"webgl",kernelFunc:Wee},i8="return (a < 0.) ? b * a : a;",o8=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function Uee(e){let{inputs:t,backend:r}=e,{x:a,alpha:n}=t,s=Y().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Eh(o8,a.shape,n.shape):new wu(i8,a.shape,n.shape);return r.runWebGLProgram(s,[a,n],"float32")}var Gee={kernelName:wi,backendName:"webgl",kernelFunc:Uee},yd="if (isnan(x)) return x;",jee=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,Hee=`
|
|
result.r = isNaN.r > 0. ? NAN : result.r;
|
|
result.g = isNaN.g > 0. ? NAN : result.g;
|
|
result.b = isNaN.b > 0. ? NAN : result.b;
|
|
result.a = isNaN.a > 0. ? NAN : result.a;
|
|
`;function it({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:r,dtype:a}){return({inputs:n,backend:s})=>{let{x:i}=n,o=s,l=a||i.dtype;if(o.shouldExecuteOnCPU([i])&&r!=null){let p=o.texData.get(i.dataId),h=r(p.values,l);return o.makeTensorInfo(i.shape,l,h)}let d=Y().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,u;return d?u=new co(i.shape,t):u=new Gn(i.shape,e),o.runWebGLProgram(u,[i],l)}}function Ar({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:r=!1,supportsComplex:a=!1,cpuKernelImpl:n,dtype:s}){return({inputs:i,backend:o})=>{let{a:l,b:d}=i,u=o;if(a&&l.dtype==="complex64"){let f=u.texData.get(l.dataId),m=u.texData.get(d.dataId),[g,y]=[[f.complexTensorInfos.real,m.complexTensorInfos.real],[f.complexTensorInfos.imag,m.complexTensorInfos.imag]].map(x=>{let[b,v]=x,C={dataId:b.dataId,dtype:b.dtype,shape:l.shape},T={dataId:v.dataId,dtype:v.dtype,shape:d.shape},E=new wu(e,l.shape,d.shape);return u.runWebGLProgram(E,[C,T],Or(b.dtype,v.dtype))}),A=Bi({inputs:{real:g,imag:y},backend:u});return u.disposeIntermediateTensorInfo(g),u.disposeIntermediateTensorInfo(y),A}let p=s||Or(l.dtype,d.dtype);if((l.dtype==="string"||d.dtype==="string"||u.shouldExecuteOnCPU([l,d]))&&n!=null){let f=u.texData.get(l.dataId).values,m=u.texData.get(d.dataId).values,g=l.dtype==="string"?N.fromUint8ToStringArray(f):f,y=l.dtype==="string"?N.fromUint8ToStringArray(m):m,[A,x]=n(l.shape,d.shape,g,y,p),b=u.makeTensorInfo(x,p),v=u.texData.get(b.dataId);return v.values=A,b}let h=Y().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,c;return h?c=new Eh(t,l.shape,d.shape,r):c=new wu(e,l.shape,d.shape),u.runWebGLProgram(c,[l,d],p)}}function Qm(e,t=!1){if(e==="linear")return t?kee:Aee;if(e==="relu")return t?See:bee;if(e==="elu")return t?Iee:xee;if(e==="relu6")return t?Tee:vee;if(e==="prelu")return t?o8:i8;if(e==="leakyrelu")return t?s8:n8;if(e==="sigmoid")return t?Cee:wee;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}var l8=class{constructor(e,t,r,a=!1,n=!1,s=!1,i=null,o=!1,l=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r,this.enableShapeUniforms=sa(this.outputShape.length);let d=a?e[1]:e[2],u=Math.ceil(d/2),p=a?"i * 2, rc.y":"rc.y, i * 2",h=n?"rc.z, i * 2":"i * 2, rc.z",c=a?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=n?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],m="",g="";i&&(o?m=`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${i}
|
|
}`:l?m=`vec4 activation(vec4 a) {
|
|
vec4 b = getLeakyreluAlphaAtOutCoords();
|
|
${i}
|
|
}`:m=`vec4 activation(vec4 x) {
|
|
${i}
|
|
}`,g="result = activation(result);");let y=s?"result += getBiasAtOutCoords();":"";s&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),l&&this.variableNames.push("leakyreluAlpha");let A="rc.x",x="rc.x";e[0]<t[0]?A=`int(min(float(rc.x), ${e[0]-1}.))`:t[0]<e[0]&&(x=`int(min(float(rc.x), ${t[0]-1}.))`),this.userCode=`
|
|
${m}
|
|
// Don't use uniform for sharedDimensionPacked for performance.
|
|
const float sharedDimension = ${u}.0;
|
|
|
|
vec4 dot2x2ARowBCol(ivec3 rc) {
|
|
vec4 result = vec4(0);
|
|
for (int i = 0; i < ${u}; i++) {
|
|
int batchA = ${A};
|
|
int batchB = ${x};
|
|
vec4 a = getMatrixA(batchA, ${p});
|
|
vec4 b = getMatrixB(batchB, ${h});
|
|
|
|
// These swizzled products need to be separately added.
|
|
// See: https://github.com/tensorflow/tfjs/issues/1735
|
|
result += (${c[0]} * ${f[0]});
|
|
result += (${c[1]} * ${f[1]});
|
|
}
|
|
return result;
|
|
}
|
|
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
vec4 result = dot2x2ARowBCol(rc);
|
|
|
|
${y}
|
|
|
|
${g}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}},q3={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},K3=class{constructor(e,t,r){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=N.assertAndGetBroadcastShape(t,r),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));
|
|
}
|
|
`}},X3="return a * b;";function Dx(e){let{inputs:t,backend:r}=e,{a,b:n}=t,s=N.upcastType(a.dtype,n.dtype);if(a.dtype==="complex64"){let o=r.texData.get(a.dataId),l=r.texData.get(n.dataId),d=new K3(q3.REAL,a.shape,n.shape),u=new K3(q3.IMAG,a.shape,n.shape),p=[{dataId:o.complexTensorInfos.real.dataId,dtype:o.complexTensorInfos.real.dtype,shape:a.shape},{dataId:o.complexTensorInfos.imag.dataId,dtype:o.complexTensorInfos.imag.dtype,shape:a.shape},{dataId:l.complexTensorInfos.real.dataId,dtype:l.complexTensorInfos.real.dtype,shape:n.shape},{dataId:l.complexTensorInfos.imag.dataId,dtype:l.complexTensorInfos.imag.dtype,shape:n.shape}],h=r.runWebGLProgram(d,p,"float32"),c=r.runWebGLProgram(u,p,"float32"),f=Bi({inputs:{real:h,imag:c},backend:r});return r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(c),f}if(r.shouldExecuteOnCPU([a,n])){let o=r.texData.get(a.dataId),l=r.texData.get(n.dataId),[d,u]=HQ(a.shape,n.shape,o.values,l.values,s),p=r.makeTensorInfo(u,s),h=r.texData.get(p.dataId);return h.values=d,p}let i;return Y().getBool("WEBGL_PACK_BINARY_OPERATIONS")?i=new Eh(X3,a.shape,n.shape):i=new wu(X3,a.shape,n.shape),r.runWebGLProgram(i,[a,n],s)}var qee={kernelName:xi,backendName:"webgl",kernelFunc:Dx};function Kee(e,t,r){let a=[To(e.shape),...Co(e.shape)],n={dtype:e.dtype,shape:a,dataId:e.dataId},s=[To(t),...Co(t)],i=new e8(s,a),o=!0,l=[a],d=r.runWebGLProgram(i,[n],e.dtype,l,o);return{dataId:d.dataId,shape:t,dtype:d.dtype}}function ve(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{shape:s}=a,i=r,o=w.sizeFromShape(n.shape),l=w.inferFromImplicitShape(s,o),d=w.sizeFromShape(l);w.assert(o===d,()=>`The new shape (${l}) has ${d} elements and the old shape (${n.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`);let u=i.texData.get(n.dataId);return u.isPacked&&!Op(n.shape,l)&&!(u.texture!==null&&Op(u.shape,l))?Kee(n,l,i):(i.incRef(n.dataId),{dataId:n.dataId,shape:l,dtype:n.dtype})}var Xee={kernelName:tl,backendName:"webgl",kernelFunc:ve},Z3=class{constructor(e,t){this.variableNames=["x"];let{windowSize:r,batchSize:a,inSize:n,outSize:s}=e;this.outputShape=[a,s];let i=Math.floor(r/4)*4,o=r%4,l="sumValue += dot(values, ones);";if(t!=null){let u=1/t;l=`sumValue += dot(values * ${w.isInt(u)?u.toPrecision(2):u}, ones);`}let d="";n%r>0&&(d=`
|
|
if (inIdx < 0 || inIdx >= ${n}) {
|
|
return 0.0;
|
|
}
|
|
`),this.userCode=`
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
${d}
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = outIdx * ${r};
|
|
|
|
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);
|
|
}
|
|
`}},Zee=class{constructor(e,t){this.variableNames=["x"];let{windowSize:r,batchSize:a,inSize:n,outSize:s}=e;this.outputShape=[a,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 d=Math.floor(r/4)*4,u=r%4,p=`
|
|
if (${t==="sum"}) {
|
|
sumValue += dot(values, ones);
|
|
} else if (${t==="prod"}) {
|
|
vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
|
|
prodValue *= tmp[0] * tmp[1];
|
|
} else {
|
|
minMaxValue = ${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);
|
|
}
|
|
}
|
|
}
|
|
`,h="vec4";t==="all"?(i="1.0",p=`
|
|
bool reducedAllValue = all(values);
|
|
float floatedReducedAllValue = float(reducedAllValue);
|
|
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
|
|
`,h="bvec4"):t==="any"&&(i="0.0",p=`
|
|
bool reducedAnyValue = any(values);
|
|
float floatedReducedAnyValue = float(reducedAnyValue);
|
|
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
|
|
`,h="bvec4");let c="";n%r>0&&(c=`
|
|
if (inIdx < 0 || inIdx >= ${n}) {
|
|
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) {
|
|
${c}
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = outIdx * ${r};
|
|
|
|
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 < ${d}; i += 4) {
|
|
int inIdx = inOffset + i;
|
|
${h} values = ${h}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
${p}
|
|
}
|
|
|
|
int inIdx = inOffset + ${d};
|
|
if (${u===1}) {
|
|
${h} values = ${h}(
|
|
getValue(batch, inIdx),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${p}
|
|
} else if (${u===2}) {
|
|
${h} values = ${h}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${p}
|
|
} else if (${u===3}) {
|
|
${h} values = ${h}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
initializationValue
|
|
);
|
|
|
|
${p}
|
|
}
|
|
setOutput(${l});
|
|
}
|
|
`}};function Yee(e){let t=[];for(;t.length===0||t[t.length-1].outSize!==1;){let r=t.length?t[t.length-1].outSize:e[1],a=N.computeOptimalWindowSize(r);t.push({inSize:r,windowSize:a,outSize:Math.ceil(r/a)})}return t}function Cl(e,t,r,a){let n=Yee(e.shape),s=e;for(let i=0;i<n.length;i++){let{inSize:o,windowSize:l,outSize:d}=n[i],u,p;r==="mean"?u=i===0?new Z3({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:d},o):new Z3({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:d}):u=new Zee({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:d},r),p=s,s=a.runWebGLProgram(u,[s],t),p.dataId!==e.dataId&&a.disposeIntermediateTensorInfo(p)}return s}var Jee=class{constructor(e,t){this.variableNames=["A"];let r=new Array(e.length);for(let s=0;s<r.length;s++)r[s]=e[t[s]];this.outputShape=r,this.rank=r.length;let a=vt(this.rank),n=Qee(t);this.userCode=`
|
|
void main() {
|
|
${a} resRC = getOutputCoords();
|
|
setOutput(getA(${n}));
|
|
}
|
|
`}};function Qee(e){let t=e.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);let r=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],a=new Array(t);for(let n=0;n<e.length;n++)a[e[n]]=r[n];return a.join()}var ete=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let r=new Array(e.length);for(let d=0;d<r.length;d++)r[d]=e[t[d]];if(this.outputShape=r,this.rank=r.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let a=vt(this.rank),n=QI("rc",this.rank),s=new Array(this.rank);for(let d=0;d<t.length;d++)s[t[d]]=n[d];let i=`vec2(${s.slice(-2).join()})`,o=`++${n[this.rank-1]} < ${r[this.rank-1]}`,l=`getChannel(getA(${s.join()}), ${i})`;this.userCode=`
|
|
void main() {
|
|
${a} rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result[0] = ${l};
|
|
if(${o}) {
|
|
result[1] = ${l};
|
|
}
|
|
--${n[this.rank-1]};
|
|
if(++${n[this.rank-2]} < ${r[this.rank-2]}) {
|
|
result[2] = ${l};
|
|
if(${o}) {
|
|
result[3] = ${l};
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}};function e0(e,t,r){let a=Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new ete(e.shape,t):new Jee(e.shape,t);return r.runWebGLProgram(a,[e],e.dtype)}function tte(e,t,r,a){let n=t,s=e.shape.length,i=w.parseAxisParam(n,e.shape),o=i,l=N.getAxesPermutation(o,s),d=l!=null,u=e;d&&(u=e0(e,l,a),o=N.getInnerMostAxes(o.length,s)),N.assertAxesAreInnerMostDims("sum",o,s);let[p,h]=N.computeOutAndReduceShapes(u.shape,o),c=p;r&&(c=N.expandShapeToKeepDim(p,i));let f=w.sizeFromShape(h),m=w.sizeFromShape(e.shape)/f,g=ve({inputs:{x:u},attrs:{shape:[m,f]},backend:a}),y=ah(e.dtype),A=Cl(g,y,"sum",a),x=ve({inputs:{x:A},attrs:{shape:c},backend:a});return a.disposeIntermediateTensorInfo(g),a.disposeIntermediateTensorInfo(A),d&&a.disposeIntermediateTensorInfo(u),x}function t0(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{axis:s,keepDims:i}=a;return tte(n,s,i,r)}var rte={kernelName:Ri,backendName:"webgl",kernelFunc:t0};function Dr(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{perm:s}=a,i=r,o=n.shape.length,l=new Array(o);for(let u=0;u<l.length;u++)l[u]=n.shape[s[u]];let d;if(i.shouldExecuteOnCPU([n])){let u=i.texData.get(n.dataId).values,p=zx(u,n.shape,n.dtype,s,l);d=i.makeTensorInfo(l,n.dtype);let h=i.texData.get(d.dataId);h.values=p}else d=e0(n,s,i);return d}var ate={kernelName:Oi,backendName:"webgl",kernelFunc:Dr},u8=1e3;function Af({a:e,b:t,transposeA:r,transposeB:a,backend:n,bias:s=null,preluActivationWeights:i=null,leakyreluAlpha:o=0,activation:l=null}){let d=e.shape.length,u=t.shape.length,p=r?e.shape[d-2]:e.shape[d-1],h=a?t.shape[u-1]:t.shape[u-2],c=r?e.shape[d-1]:e.shape[d-2],f=a?t.shape[u-2]:t.shape[u-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),y=w.sizeFromShape(m),A=w.sizeFromShape(g),x=yl.assertAndGetBroadcastShape(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([c,f]);w.assert(p===h,()=>`Error in matMul: inner shapes (${p}) and (${h}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${r} and transposeB=${a} must match.`);let b=r?[y,p,c]:[y,c,p],v=a?[A,f,h]:[A,h,f],C=ve({inputs:{x:e},backend:n,attrs:{shape:b}}),T=ve({inputs:{x:t},backend:n,attrs:{shape:v}}),E=[C,T],R=Math.max(y,A),z=r?C.shape[1]:C.shape[2],M=s!=null,I=i!=null,D=l==="leakyrelu",O=l!=null?Qm(l,!0):null,j=M||I||D||O!=null,X;if((c===1||f===1)&&z>u8&&j===!1){let K=C,W=T;r&&(K=Dr({inputs:{x:C},backend:n,attrs:{perm:[0,2,1]}}),E.push(K)),a&&(W=Dr({inputs:{x:T},backend:n,attrs:{perm:[0,2,1]}}),E.push(W));let ee=f!==1,Q=f===1,ne=K;ee&&(ne=ve({inputs:{x:K},backend:n,attrs:{shape:[R,z,1]}}),E.push(ne));let Z=f===1?2:1,ae=W;Q&&(ae=ve({inputs:{x:W},backend:n,attrs:{shape:[R,1,z]}}),E.push(ae));let ie=Dx({inputs:{a:ne,b:ae},backend:n});X=t0({inputs:{x:ie},backend:n,attrs:{axis:Z,keepDims:!0}}),E.push(ie)}else{let K=Or(e.dtype,t.dtype),W=new l8(b,v,[R,c,f],r,a,M,O,I,D),ee=[C,T];if(s!=null&&ee.push(s),I&&ee.push(i),D){let Q=n.makeTensorInfo([],"float32",w.createScalarValue(o,"float32"));ee.push(Q),E.push(Q)}X=n.runWebGLProgram(W,ee,K)}let _=ve({inputs:{x:X},backend:n,attrs:{shape:x}});E.push(X);for(let K of E)n.disposeIntermediateTensorInfo(K);return _}function nte(e){let{inputs:t,backend:r,attrs:a}=e,{a:n,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:d,activation:u,leakyreluAlpha:p}=a;return Af({a:n,b:s,transposeA:l,transposeB:d,backend:r,bias:i,preluActivationWeights:o,leakyreluAlpha:p,activation:u})}var ste={kernelName:Rs,backendName:"webgl",kernelFunc:nte},Y3="return abs(x);";function ite(e){let{inputs:t,backend:r}=e,{x:a}=t;if(r.shouldExecuteOnCPU([a])&&a.dtype!=="complex64"){let s=r.texData.get(a.dataId),i=YI(s.values);return r.makeTensorInfo(a.shape,a.dtype,i)}let n;return Y().getBool("WEBGL_PACK_UNARY_OPERATIONS")?n=new co(a.shape,Y3):n=new Gn(a.shape,Y3),r.runWebGLProgram(n,[a],a.dtype)}var ote={kernelName:Fo,backendName:"webgl",kernelFunc:ite},lte=Ka+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return acos(x);
|
|
`,ute=it({opSnippet:lte}),dte={kernelName:Tu,backendName:"webgl",kernelFunc:ute},pte=Ka+`
|
|
if (x < 1.0) return NAN;
|
|
return log(x + sqrt(x * x - 1.0));`,hte=it({opSnippet:pte}),cte={kernelName:Cu,backendName:"webgl",kernelFunc:hte},J3="return a + b;",fte=Ar({opSnippet:J3,packedOpSnippet:J3,supportsComplex:!0,cpuKernelImpl:CQ}),mte={kernelName:qn,backendName:"webgl",kernelFunc:fte},gte=class{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((n,s)=>`T${s}`);let r=[];this.variableNames.forEach(n=>{r.push(`float v${n} = get${n}AtOutCoords();`)});let a=this.variableNames.map(n=>`v${n}`).join(" + ");this.userCode=`
|
|
void main() {
|
|
${r.join(`
|
|
`)}
|
|
|
|
float result = ${a};
|
|
setOutput(result);
|
|
}
|
|
`}},yte=class{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((n,s)=>`T${s}`);let r=[];this.variableNames.forEach(n=>{r.push(`vec4 v${n} = get${n}AtOutCoords();`)});let a=this.variableNames.map(n=>`v${n}`).join(" + ");this.userCode=`
|
|
void main() {
|
|
${r.join(`
|
|
`)}
|
|
|
|
vec4 result = ${a};
|
|
setOutput(result);
|
|
}
|
|
`}};function Gc(e){let{inputs:t,backend:r}=e,a=t;if(a.length===1)return ha({inputs:{x:a[0]},backend:r});if(a.length>Y().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let o=Math.floor(a.length/2),l=Gc({inputs:a.slice(0,o),backend:r}),d=Gc({inputs:a.slice(o),backend:r});return Gc({inputs:[l,d],backend:r})}let n=a.map(o=>o.dtype).reduce((o,l)=>Or(o,l)),s=a.map(o=>o.shape),i=Y().getBool("WEBGL_PACK")?new yte(a[0].shape,s):new gte(a[0].shape,s);return r.runWebGLProgram(i,a,n)}var Ate={kernelName:js,backendName:"webgl",kernelFunc:Gc};function xte(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{axis:s,keepDims:i}=a,o=n.shape.length,l=w.parseAxisParam(s,n.shape),d=l,u=N.getAxesPermutation(d,o),p=n;u!=null&&(p=Dr({inputs:{x:n},backend:r,attrs:{perm:u}}),d=N.getInnerMostAxes(d.length,o)),N.assertAxesAreInnerMostDims("all",d,o);let[h,c]=N.computeOutAndReduceShapes(p.shape,d),f=w.sizeFromShape(c),m=ve({inputs:{x:p},backend:r,attrs:{shape:[-1,f]}}),g=Cl(m,m.dtype,"all",r),y;if(i){let A=N.expandShapeToKeepDim(h,l);y=ve({inputs:{x:g},backend:r,attrs:{shape:A}})}else y=ve({inputs:{x:g},backend:r,attrs:{shape:h}});return r.disposeIntermediateTensorInfo(m),r.disposeIntermediateTensorInfo(g),u!=null&&r.disposeIntermediateTensorInfo(p),y}var bte={kernelName:Nu,backendName:"webgl",kernelFunc:xte};function vte(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{axis:s,keepDims:i}=a,o=n.shape.length,l=w.parseAxisParam(s,n.shape),d=l,u=N.getAxesPermutation(d,o),p=n;u!=null&&(p=Dr({inputs:{x:n},backend:r,attrs:{perm:u}}),d=N.getInnerMostAxes(d.length,o)),N.assertAxesAreInnerMostDims("any",d,o);let[h,c]=N.computeOutAndReduceShapes(p.shape,d),f=w.sizeFromShape(c),m=ve({inputs:{x:p},backend:r,attrs:{shape:[-1,f]}}),g=Cl(m,m.dtype,"any",r),y;if(i){let A=N.expandShapeToKeepDim(h,l);y=ve({inputs:{x:g},backend:r,attrs:{shape:A}})}else y=ve({inputs:{x:g},backend:r,attrs:{shape:h}});return r.disposeIntermediateTensorInfo(m),r.disposeIntermediateTensorInfo(g),u!=null&&r.disposeIntermediateTensorInfo(p),y}var wte={kernelName:Eu,backendName:"webgl",kernelFunc:vte},kte=class{constructor(e,t,r){this.variableNames=["A"];let{windowSize:a,batchSize:n,outSize:s}=e;r||this.variableNames.push("bestIndicesA"),this.outputShape=[n,s];let i=t==="max"?">":"<",o=r?"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 * ${a};
|
|
|
|
int bestIndex = inOffset;
|
|
float bestValue = getA(batch, bestIndex);
|
|
|
|
for (int i = 0; i < ${a}; i++) {
|
|
int inIdx = ${o};
|
|
float candidate = getA(batch, inIdx);
|
|
if (candidate ${i} bestValue) {
|
|
bestValue = candidate;
|
|
bestIndex = inIdx;
|
|
}
|
|
}
|
|
setOutput(float(bestIndex));
|
|
}
|
|
`}},Ite=class{constructor(e,t,r,a){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,w.assert(e.length>2,()=>`Packed arg${r.charAt(0).toUpperCase()+r.slice(1)} supports only inputs with rank above 2.`);let n=e[e.length-1],s=Math.ceil(n/t);this.outputShape=e.slice(0,-1),s>1&&this.outputShape.push(s),a||this.variableNames.push("bestIndicesA");let i=this.outputShape,o=i.length,l=vt(o),d=$r("coords",o),u,p;if(s===1){p=o+1;let T=vt(p);u=`
|
|
${T} sourceLocR = ${T}(${d.join()}, 0);
|
|
++${d[o-1]};
|
|
${T} sourceLocG = ${T}(${d.join()}, 0);
|
|
++${d[o-2]};
|
|
${T} sourceLocA = ${T}(${d.join()}, 0);
|
|
--${d[o-1]};
|
|
${T} sourceLocB = ${T}(${d.join()}, 0);
|
|
--${d[o-2]};`}else p=o,u=`
|
|
${l} sourceLocR = coords;
|
|
++${d[o-1]};
|
|
${l} sourceLocG = coords;
|
|
++${d[o-2]};
|
|
${l} sourceLocA = coords;
|
|
--${d[o-1]};
|
|
${l} sourceLocB = coords;
|
|
--${d[o-2]};`;let h=["x","y","z","w","u","v"].slice(0,p),c="."+h[p-1],f=h.map(T=>"int "+T),m=$r("sourceLocR",p-1).concat("inIdx.r"),g=$r("sourceLocG",p-1).concat("inIdx.g"),y=$r("sourceLocB",p-1).concat("inIdx.b"),A=$r("sourceLocA",p-1).concat("inIdx.a"),x=r==="max"?"greaterThan":"lessThan",b=a?"":`
|
|
inIdx = round(vec4(getBestIndicesAChannel(${m.join()}),
|
|
getBestIndicesAChannel(${g.join()}),
|
|
getBestIndicesAChannel(${y.join()}),
|
|
getBestIndicesAChannel(${A.join()})));`,v=`vec4(
|
|
getAChannel(${m.join()}),
|
|
hasNextCol ? getAChannel(${g.join()}) : 0.,
|
|
hasNextRow ? getAChannel(${y.join()}) : 0.,
|
|
hasNextRow && hasNextCol ? getAChannel(${A.join()}) : 0.)`,C=a?"":`
|
|
float getBestIndicesAChannel(${f.join()}) {
|
|
return getChannel(getBestIndicesA(${h.join()}),
|
|
vec2(${h.slice(-2).join()}));
|
|
}`;this.userCode=`
|
|
float getAChannel(${f.join()}) {
|
|
return getChannel(getA(${h.join()}),
|
|
vec2(${h.slice(-2).join()}));
|
|
}
|
|
${C}
|
|
void main() {
|
|
${l} coords = getOutputCoords();
|
|
bool hasNextCol = ${d[o-1]} < ${i[o-1]-1};
|
|
bool hasNextRow = ${d[o-2]} < ${i[o-2]-1};
|
|
${u}
|
|
ivec4 srcIdx = ivec4(sourceLocR${c}, sourceLocG${c},
|
|
sourceLocB${c}, sourceLocA${c}) * ${t};
|
|
ivec4 inIdx = srcIdx;
|
|
vec4 bestIndex = vec4(inIdx);
|
|
vec4 bestValue = ${v};
|
|
|
|
for (int i = 0; i < ${t}; i++) {
|
|
inIdx = srcIdx;
|
|
${b}
|
|
vec4 candidate = ${v};
|
|
bvec4 nan = isnan(candidate);
|
|
bvec4 replace = bvec4(
|
|
vec4(${x}(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 d8(e,t,r,a=null){let n=t.shape[0],s=t.shape[1];a!=null&&(n=a.shape[0],s=a.shape[1]);let i=N.computeOptimalWindowSize(s),o={windowSize:i,inSize:s,batchSize:n,outSize:Math.ceil(s/i)},l=new kte(o,r,a==null),d=[t];a!=null&&d.push(a);let u=e.runWebGLProgram(l,d,"int32");if(u.shape[1]===1)return u;let p=d8(e,t,r,u);return e.disposeIntermediateTensorInfo(u),p}function p8(e,t,r,a=null){let n=a!=null?a.shape:t.shape,s=n[n.length-1],i=N.computeOptimalWindowSize(s),o=new Ite(n,i,r,a==null),l=a==null?[t]:[t,a],d=e.runWebGLProgram(o,l,"int32");if(d.shape.length===t.shape.length){let u=p8(e,t,r,d);return e.disposeIntermediateTensorInfo(d),u}return d}function h8(e,t,r,a){let n=[r];if(N.assertAxesAreInnerMostDims("arg"+a.charAt(0).toUpperCase()+a.slice(1),n,t.shape.length),!Y().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[d,u]=N.computeOutAndReduceShapes(l.shape,n),p=w.sizeFromShape(u),h=ve({inputs:{x:l},backend:e,attrs:{shape:[-1,p]}});s.push(h);let c=d8(e,h,a);s.push(c);let f=ve({inputs:{x:c},backend:e,attrs:{shape:d}});return s.forEach(m=>e.disposeIntermediateTensorInfo(m)),f}return p8(e,t,a)}function Ste(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{axis:s}=a,i=w.parseAxisParam(s,n.shape),o=N.getAxesPermutation(i,n.shape.length),l=n,d=[];o!=null&&(l=Dr({inputs:{x:n},backend:r,attrs:{perm:o}}),d.push(l),i=N.getInnerMostAxes(i.length,l.shape.length)),N.assertAxesAreInnerMostDims("argMax",[i[0]],l.shape.length);let u=h8(r,l,i[0],"max");return d.forEach(p=>r.disposeIntermediateTensorInfo(p)),u}var Tte={kernelName:Hs,backendName:"webgl",kernelFunc:Ste};function Cte(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{axis:s}=a,i=w.parseAxisParam(s,n.shape),o=N.getAxesPermutation(i,n.shape.length),l=n,d=[];o!=null&&(l=Dr({inputs:{x:n},backend:r,attrs:{perm:o}}),d.push(l),i=N.getInnerMostAxes(i.length,l.shape.length)),N.assertAxesAreInnerMostDims("argMin",[i[0]],l.shape.length);let u=h8(r,l,i[0],"min");return d.forEach(p=>r.disposeIntermediateTensorInfo(p)),u}var Nte={kernelName:Ru,backendName:"webgl",kernelFunc:Cte},Ete=Ka+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return asin(x);
|
|
`,Rte=it({opSnippet:Ete}),Fte={kernelName:Fu,backendName:"webgl",kernelFunc:Rte},Mte=Ka+"return log(x + sqrt(x * x + 1.0));",$te=it({opSnippet:Mte}),Pte={kernelName:Mu,backendName:"webgl",kernelFunc:$te},Ote=Ka+`
|
|
return atan(x);
|
|
`,zte=it({opSnippet:Ote}),Dte={kernelName:$u,backendName:"webgl",kernelFunc:zte},_te=jee+`
|
|
return atan(a, b);
|
|
`,Lte=`
|
|
vec4 result = atan(a, b);
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+Hee+`
|
|
return result;
|
|
`,Bte=Ar({opSnippet:_te,packedOpSnippet:Lte}),Wte={kernelName:Ou,backendName:"webgl",kernelFunc:Bte},Vte=Ka+`
|
|
if ((x < -1.0) || (x > 1.0)) return NAN;
|
|
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,Ute=it({opSnippet:Vte}),Gte={kernelName:Pu,backendName:"webgl",kernelFunc:Ute},zp=class{constructor(e,t,r,a=!1,n=!1){if(this.variableNames=["x"],t==="avg"&&r)throw new Error("Cannot compute positions for average pool.");let s=e.filterWidth,i=e.strideHeight,o=e.strideWidth,l=e.dilationHeight,d=e.dilationWidth,u=e.effectiveFilterHeight,p=e.effectiveFilterWidth,h=e.padInfo.top,c=e.padInfo.left;this.outputShape=e.outShape;let f=t==="avg",m=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`,y="0.0";if(f||(y="-1.0 / 1e-20"),r){let T=">=";this.userCode=`
|
|
const ivec2 strides = ivec2(${i}, ${o});
|
|
const ivec2 pads = ivec2(${h}, ${c});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d = coords[3];
|
|
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// max/min x(?, ?, d) to get y(yR, yC, d).
|
|
// ? = to be determined
|
|
float minMaxValue = 0.0;
|
|
float minMaxValueFound = 0.0;
|
|
int minMaxPosition = 0;
|
|
float avgValue = 0.0;
|
|
|
|
for (int wR = 0; wR < ${u};
|
|
wR += ${l}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${p};
|
|
wC += ${d}) {
|
|
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 ${T} currMinMaxValue) {
|
|
minMaxValue = value;
|
|
minMaxValueFound = 1.0;
|
|
minMaxPosition = ${a?n?m:g:`wR * ${p} + wC`};
|
|
}
|
|
}
|
|
}
|
|
setOutput(float(minMaxPosition));
|
|
}
|
|
`;return}let A="max",x=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(x="avgValue / count");let b=Math.floor(s/4)*4,v=s%4,C=`
|
|
if (${f}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${A}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec2 strides = ivec2(${i}, ${o});
|
|
const ivec2 pads = ivec2(${h}, ${c});
|
|
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 < ${u};
|
|
wR += ${l}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${b}; wC += 4) {
|
|
int xC = xCCorner + wC * ${d};
|
|
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${d}, d),
|
|
getValue(batch, xR, xC + 2 * ${d}, d),
|
|
getValue(batch, xR, xC + 3 * ${d}, d)
|
|
);
|
|
|
|
${C}
|
|
}
|
|
|
|
int xC = xCCorner + ${b};
|
|
if (${v===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${C}
|
|
} else if (${v===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${d}, d),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${C}
|
|
} else if (${v===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${d}, d),
|
|
getValue(batch, xR, xC + 2 * ${d}, d),
|
|
initializationValue
|
|
);
|
|
|
|
${C}
|
|
}
|
|
}
|
|
setOutput(${x});
|
|
}
|
|
`}},_x=class{constructor(e,t,r,a=!1,n=!1){if(this.variableNames=["x"],t==="avg"&&r)throw new Error("Cannot compute positions for average pool.");let s=e.filterWidth,i=e.strideDepth,o=e.strideHeight,l=e.strideWidth,d=e.dilationDepth,u=e.dilationHeight,p=e.dilationWidth,h=e.effectiveFilterDepth,c=e.effectiveFilterHeight,f=e.effectiveFilterWidth,m=e.padInfo.front,g=e.padInfo.top,y=e.padInfo.left;this.outputShape=e.outShape;let A=t==="avg",x="0.0";if(A||(x="-1.0 / 1e-20"),r){let R=">=";this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${i}, ${o}, ${l});
|
|
const ivec3 pads = ivec3(${m}, ${g}, ${y});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
|
|
int xDCorner = xCorner.x;
|
|
int xRCorner = xCorner.y;
|
|
int xCCorner = xCorner.z;
|
|
|
|
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
|
|
// ? = to be determined
|
|
float minMaxValue = 0.0;
|
|
float minMaxValueFound = 0.0;
|
|
int minMaxPosition = 0;
|
|
|
|
for (int wD = 0; wD < ${h};
|
|
wD += ${d}) {
|
|
int xD = xDCorner + wD;
|
|
|
|
if (xD < 0 || xD >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${c};
|
|
wR += ${u}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${f};
|
|
wC += ${p}) {
|
|
int xC = xCCorner + wC;
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
float value = getX(batch, xD, xR, xC, ch);
|
|
|
|
// If a min / max value has already been found, use it. If not,
|
|
// use the current value.
|
|
float currMinMaxValue = mix(
|
|
value, minMaxValue, minMaxValueFound);
|
|
if (value ${R} currMinMaxValue) {
|
|
minMaxValue = value;
|
|
minMaxValueFound = 1.0;
|
|
minMaxPosition = ${a?n?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${c} * ${f} +
|
|
wR * ${f} + wC`};
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(float(minMaxPosition));
|
|
}
|
|
`;return}let b="max",v=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(v="avgValue / count");let C=Math.floor(s/4)*4,T=s%4,E=`
|
|
if (${A}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${b}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${i}, ${o}, ${l});
|
|
const ivec3 pads = ivec3(${m}, ${g}, ${y});
|
|
const float initializationValue = ${x};
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float count = 0.0;
|
|
|
|
float getValue(int batch, int 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(${x});
|
|
float avgValue = 0.0;
|
|
count = 0.0;
|
|
|
|
for (int wD = 0; wD < ${h};
|
|
wD += ${d}) {
|
|
int xD = xDCorner + wD;
|
|
|
|
if (xD < 0 || xD >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${c};
|
|
wR += ${u}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${C}; wC += 4) {
|
|
int xC = xCCorner + wC * ${p};
|
|
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${p}, ch),
|
|
getValue(batch, xD, xR, xC + 2 * ${p}, ch),
|
|
getValue(batch, xD, xR, xC + 3 * ${p}, ch)
|
|
);
|
|
|
|
${E}
|
|
}
|
|
|
|
int xC = xCCorner + ${C};
|
|
if (${T===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${E}
|
|
} else if (${T===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${p}, ch),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${E}
|
|
} else if (${T===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${p}, ch),
|
|
getValue(batch, xD, xR, xC + 2 * ${p}, ch),
|
|
initializationValue
|
|
);
|
|
|
|
${E}
|
|
}
|
|
}
|
|
setOutput(${v});
|
|
}
|
|
}
|
|
`}};function jte(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t;hd(n,"avgPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,d=1;w.assert(N.eitherStridesOrDilationsAreOne(i,d),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${d}'`);let u=N.computePool2DInfo(n.shape,s,i,d,o,l);if(u.filterWidth===1&&u.filterHeight===1&&w.arraysEqual(u.inShape,u.outShape))return ha({inputs:{x:n},backend:r});let p=new zp(u,"avg",!1);return r.runWebGLProgram(p,[n],"float32")}var Hte={kernelName:qs,backendName:"webgl",kernelFunc:jte};function qte(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:d}=a,u=[1,1,1],p=N.computePool3DInfo(n.shape,s,i,u,o,l,d),h=new _x(p,"avg",!1);return r.runWebGLProgram(h,[n],"float32")}var Kte={kernelName:_p,backendName:"webgl",kernelFunc:qte},Xte=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterHeight,r=e.filterWidth,a=e.strideHeight,n=e.strideWidth,s=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterHeight,l=e.effectiveFilterWidth,d=o-1-e.padInfo.top,u=l-1-e.padInfo.left,p=1/(t*r);this.userCode=`
|
|
const ivec2 pads = ivec2(${d}, ${u});
|
|
const float avgMultiplier = float(${p});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
|
|
ivec2 dyRCCorner = coords.yz - pads;
|
|
int dyRCorner = dyRCCorner.x;
|
|
int dyCCorner = dyRCCorner.y;
|
|
|
|
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < ${o};
|
|
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 < ${l};
|
|
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(b, idyR, idyC, d);
|
|
|
|
dotProd += dyValue * avgMultiplier;
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},Zte=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterDepth,r=e.filterHeight,a=e.filterWidth,n=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,d=e.dilationWidth,u=e.effectiveFilterDepth,p=e.effectiveFilterHeight,h=e.effectiveFilterWidth,c=u-1-e.padInfo.front,f=p-1-e.padInfo.top,m=h-1-e.padInfo.left,g=1/(t*r*a);this.userCode=`
|
|
const ivec3 pads = ivec3(${c}, ${f}, ${m});
|
|
const float avgMultiplier = float(${g});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
|
|
int dyDCorner = dyCorner.x;
|
|
int dyRCorner = dyCorner.y;
|
|
int dyCCorner = dyCorner.z;
|
|
|
|
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
|
|
// dx(xD, xR, xC, ch).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
|
|
for (int wD = 0; wD < ${u};
|
|
wD += ${o}) {
|
|
float dyD = float(dyDCorner + wD) / ${n}.0;
|
|
|
|
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyD = int(dyD);
|
|
|
|
for (int wR = 0; wR < ${p};
|
|
wR += ${l}) {
|
|
float dyR = float(dyRCorner + wR) / ${s}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
|
|
fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${h};
|
|
wC += ${d}) {
|
|
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 Yte(e){let{inputs:t,backend:r,attrs:a}=e,{dy:n,input:s}=t,i=s,{filterSize:o,strides:l,pad:d,dimRoundingMode:u}=a,p=[1,1,1],h=N.computePool3DInfo(i.shape,o,l,p,d,u),c=new Zte(h);return r.runWebGLProgram(c,[n],i.dtype)}var Jte={kernelName:Cf,backendName:"webgl",kernelFunc:Yte};function Qte(e){let{inputs:t,backend:r,attrs:a}=e,{dy:n,input:s}=t,i=s;hd([n,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:d}=a,u=N.computePool2DInfo(i.shape,o,l,1,d),p=new Xte(u);return r.runWebGLProgram(p,[n],i.dtype)}var ere={kernelName:Tf,backendName:"webgl",kernelFunc:Qte};function tre(e){let{inputs:t,backend:r,attrs:a}=e,{a:n,b:s}=t,{transposeA:i,transposeB:o}=a;return Af({a:n,b:s,transposeA:i,transposeB:o,backend:r})}var rre={kernelName:Ks,backendName:"webgl",kernelFunc:tre},are=class{constructor(e,t,r,a,n,s){this.outputShape=[],this.variableNames=["x","mean","variance"],N.assertAndGetBroadcastShape(e,t),N.assertAndGetBroadcastShape(e,r);let i="0.0";a!=null&&(N.assertAndGetBroadcastShape(e,a),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="1.0";n!=null&&(N.assertAndGetBroadcastShape(e,n),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)));
|
|
}
|
|
`}},nre=class{constructor(e,t,r,a,n,s){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],N.assertAndGetBroadcastShape(e,t),N.assertAndGetBroadcastShape(e,r);let i="vec4(0.0)";a!=null&&(N.assertAndGetBroadcastShape(e,a),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="vec4(1.0)";n!=null&&(N.assertAndGetBroadcastShape(e,n),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);
|
|
}
|
|
`}},sre=({inputs:e,backend:t,attrs:r})=>{let{x:a,mean:n,variance:s,offset:i,scale:o}=e;w.assert(n.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),w.assert(i==null||n.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),w.assert(o==null||n.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:l}=r;l==null&&(l=.001);let d=[a,n,s],u=null;i!=null&&(u=i.shape,d.push(i));let p=null;o!=null&&(p=o.shape,d.push(o));let h=Y().getBool("WEBGL_PACK_NORMALIZATION")?new nre(a.shape,n.shape,s.shape,u,p,l):new are(a.shape,n.shape,s.shape,u,p,l);return t.runWebGLProgram(h,d,d[0].dtype)},ire={kernelName:oi,backendName:"webgl",kernelFunc:sre},ore=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=vt(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let r=lre(this.rank),a,n=e.map((s,i)=>`sourceLoc.${vy[i]} = start[${i}] + coords.${vy[i]};`);a=`
|
|
${t} sourceLoc;
|
|
${t} coords = getOutputCoords();
|
|
${n.join(`
|
|
`)}
|
|
`,this.userCode=`
|
|
void main() {
|
|
${a}
|
|
setOutput(getSource(${r}));
|
|
}
|
|
`}},vy=["x","y","z","w","u","v"];function lre(e){if(e===1)return"sourceLoc";if(e<=6)return vy.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}var ure=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=vt(this.rank),r=$r("coords",this.rank),a=$r("sourceLoc",this.rank),n=this.rank===1?"sourceLoc":`vec2(${a.slice(-2).join()})`,s=`getChannel(getSource(${a.join()}), ${n})`,i=`
|
|
result.x = ${s};
|
|
if (++${r[this.rank-1]} < ${e[this.rank-1]}) {
|
|
++${a[this.rank-1]};
|
|
result.y = ${s};
|
|
--${a[this.rank-1]};
|
|
}
|
|
`,o=this.rank===1?"":`
|
|
--${r[this.rank-1]};
|
|
if (++${r[this.rank-2]} < ${e[this.rank-2]}) {
|
|
++${a[this.rank-2]};
|
|
result.z = ${s};
|
|
if (++${r[this.rank-1]} < ${e[this.rank-1]}) {
|
|
++${a[this.rank-1]};
|
|
result.w = ${s};
|
|
}
|
|
}
|
|
`,l=this.rank<=4?`sourceLoc = coords +
|
|
${t}(${e.map((d,u)=>`start[${u}]`).join()});`:e.map((d,u)=>`${a[u]} = ${r[u]} + start[${u}];`).join(`
|
|
`);this.userCode=`
|
|
void main() {
|
|
${t} coords = getOutputCoords();
|
|
${t} sourceLoc;
|
|
${l}
|
|
vec4 result = vec4(0.);
|
|
${i}
|
|
${o}
|
|
setOutput(result);
|
|
}
|
|
`}};function dre(e,t,r,a){let n=a.texData.get(e.dataId),s=a.makeTensorInfo(r,e.dtype),i=a.texData.get(s.dataId);Object.assign(i,n),i.refCount=1,i.shape=r,i.dtype=e.dtype;let o=Ot.computeFlatOffset(t,w.computeStrides(e.shape));n.slice&&(o+=n.slice.flatOffset),i.slice={flatOffset:o,origDataId:n.slice&&n.slice.origDataId||e.dataId};let l=a.dataRefCount.get(i.slice.origDataId)||1;return a.dataRefCount.set(i.slice.origDataId,l+1),s}function Ad(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{begin:s,size:i}=a,[o,l]=Ot.parseSliceParams(n,s,i);if(Ot.assertParamsValid(n,o,l),w.sizeFromShape(l)===0)return r.makeTensorInfo(l,n.dtype,[]);if(r.shouldExecuteOnCPU([n])||n.dtype==="string"){let p=r.texData.get(n.dataId),h=QQ(p.values,o,l,n.shape,n.dtype);return r.makeTensorInfo(l,n.dtype,h)}let{isPacked:d}=r.texData.get(n.dataId),u=Ot.isSliceContinous(n.shape,o,l);if(d||!u){let p=Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new ure(l):new ore(l),h=[o];return r.runWebGLProgram(p,[n],n.dtype,h)}return r.uploadToGPU(n.dataId),dre(n,o,l,r)}var pre={kernelName:il,backendName:"webgl",kernelFunc:Ad},hre=e=>{let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{blockShape:s,crops:i}=a;w.assert(n.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let o=s.reduce((A,x)=>A*x),l=N.getReshaped(n.shape,s,o),d=N.getPermuted(l.length,s.length),u=N.getReshapedPermuted(n.shape,s,o),p=N.getSliceBeginCoords(i,s.length),h=N.getSliceSize(u,i,s.length),c=[],f=ve({inputs:{x:n},backend:r,attrs:{shape:l}}),m=Dr({inputs:{x:f},backend:r,attrs:{perm:d}}),g=ve({inputs:{x:m},backend:r,attrs:{shape:u}}),y=Ad({inputs:{x:g},backend:r,attrs:{begin:p,size:h}});return c.push(f),c.push(m),c.push(g),c.forEach(A=>r.disposeIntermediateTensorInfo(A)),y},cre={kernelName:Mo,backendName:"webgl",kernelFunc:hre};function fre(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,weights:s}=t,{size:i}=a,o=r.readSync(n.dataId),l=r.readSync(s.dataId),d=ZI(o,l,s.dtype,s.shape,i);return r.makeTensorInfo([i],s.dtype,d)}var mre={kernelName:Nf,backendName:"webgl",kernelFunc:fre};function gre(e){let{inputs:t,backend:r}=e,{s0:a,s1:n}=t,s=r.readSync(a.dataId),i=r.readSync(n.dataId),o=N.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return r.makeTensorInfo([o.length],"int32",Int32Array.from(o))}var yre={kernelName:Ef,backendName:"webgl",kernelFunc:gre},Are="return float(a != b);",c8=Ar({opSnippet:Are,cpuKernelImpl:KQ,dtype:"bool"}),xre={kernelName:Ko,backendName:"webgl",kernelFunc:c8};function Rh(e){let{inputs:t,backend:r}=e,{input:a}=t,n=r.texData.get(a.dataId);return ha({inputs:{x:n.complexTensorInfos.real},backend:r})}var bre={kernelName:Kp,backendName:"webgl",kernelFunc:Rh},vre="return float(int(x));";function wre(e,t){let r=new Gn(e.shape,vre),a=t.runWebGLProgram(r,[e],"int32");return{dataId:a.dataId,shape:a.shape,dtype:a.dtype}}function wy(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{dtype:s}=a;if(s==="complex64"){if(n.dtype==="complex64")return ha({inputs:{x:n},backend:r});let i=Vt(n.shape),o=wy({inputs:{x:n},backend:r,attrs:{dtype:"float32"}}),l=Bi({inputs:{real:o,imag:i},backend:r});return i.dispose(),r.disposeIntermediateTensorInfo(o),l}if(n.dtype==="complex64"){let i=Rh({inputs:{input:n},backend:r}),o=wy({inputs:{x:i},backend:r,attrs:{dtype:s}});return r.disposeIntermediateTensorInfo(i),o}if(!w.hasEncodingLoss(n.dtype,s)){let i=ha({inputs:{x:n},backend:r});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(s==="int32")return wre(n,r);if(s==="bool"){let i=r.makeTensorInfo([],"bool",w.getTypedArrayFromDType("bool",1)),o=c8({inputs:{a:n,b:i},backend:r});return r.disposeIntermediateTensorInfo(i),o}throw new Error(`Error in Cast: failed to cast ${n.dtype} to ${s}`)}var kre={kernelName:Xs,backendName:"webgl",kernelFunc:wy},Q3="return ceil(x);",Ire=it({opSnippet:Q3,packedOpSnippet:Q3,cpuKernelImpl:EQ}),Sre={kernelName:Zs,backendName:"webgl",kernelFunc:Ire},Tre=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));
|
|
}
|
|
`}},Cre=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 Nre(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{clipValueMin:s,clipValueMax:i}=a,o;Y().getBool("WEBGL_PACK_CLIP")?o=new Cre(n.shape):o=new Tre(n.shape);let l=[[s],[i]];return r.runWebGLProgram(o,[n],n.dtype,l)}var Ere={kernelName:Kn,backendName:"webgl",kernelFunc:Nre},Rre=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 ev(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}function Fre(e){let{inputs:t,backend:r}=e,{x:a}=t,n=r.texData.get(a.dataId),s=new Rre(a.shape),i=[ev(a,n.complexTensorInfos.real),ev(a,n.complexTensorInfos.imag)];return r.runWebGLProgram(s,i,i[0].dtype)}var Mre={kernelName:Bp,backendName:"webgl",kernelFunc:Fre},$re=class{constructor(e){this.outputShape=[],this.outputShape=N.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 r=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let s=1;s<t.length;s++){let i=t[s-1];r.push(`else if (yC < ${t[s]}) setOutput(getT${s}(yR, yC-${i}));`)}let a=t.length,n=t[t.length-1];r.push(`else setOutput(getT${a}(yR, yC-${n}));`),this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int yR = coords.x;
|
|
int yC = coords.y;
|
|
|
|
${r.join(`
|
|
`)}
|
|
}
|
|
`}},Pre=class{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=N.computeOutShape(e,t);let r=this.outputShape,a=r.length,n=vt(a),s=$r("coords",a),i=["x","y","z","w","u","v"].slice(0,a);this.variableNames=e.map((f,m)=>`T${m}`);let o=new Array(e.length-1);o[0]=e[0][t];for(let f=1;f<o.length;f++)o[f]=o[f-1]+e[f][t];let l=i[t],d=i.slice(-2),u=i.join(),p=`if (${l} < ${o[0]}) {
|
|
return getChannel(
|
|
getT0(${u}), vec2(${d.join()}));
|
|
}`;for(let f=1;f<o.length;f++){let m=o[f-1];p+=`
|
|
if (${l} < ${o[f]} && ${l} >= ${o[f-1]}) {
|
|
return getChannel(
|
|
getT${f}(${Pc(i,l,m)}),
|
|
vec2(${Pc(d,l,m)}));
|
|
}`}let h=o.length,c=o[o.length-1];p+=`
|
|
return getChannel(
|
|
getT${h}(${Pc(i,l,c)}),
|
|
vec2(${Pc(d,l,c)}));`,this.userCode=`
|
|
float getValue(${i.map(f=>"int "+f)}) {
|
|
${p}
|
|
}
|
|
|
|
void main() {
|
|
${n} coords = getOutputCoords();
|
|
vec4 result = vec4(getValue(${s}), 0., 0., 0.);
|
|
|
|
${s[a-1]} = ${s[a-1]} + 1;
|
|
if (${s[a-1]} < ${r[a-1]}) {
|
|
result.g = getValue(${s});
|
|
}
|
|
|
|
${s[a-2]} = ${s[a-2]} + 1;
|
|
if (${s[a-2]} < ${r[a-2]}) {
|
|
result.a = getValue(${s});
|
|
}
|
|
|
|
${s[a-1]} = ${s[a-1]} - 1;
|
|
if (${s[a-2]} < ${r[a-2]} &&
|
|
${s[a-1]} < ${r[a-1]}) {
|
|
result.b = getValue(${s});
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}};function Pc(e,t,r){let a=e.indexOf(t);return e.map((n,s)=>s===a?`${n} - ${r}`:n).join()}function r0(e){let{inputs:t,backend:r}=e,{input:a}=t,n=r.texData.get(a.dataId);return ha({inputs:{x:n.complexTensorInfos.imag},backend:r})}var Ore={kernelName:Gp,backendName:"webgl",kernelFunc:r0};function au(e,t,r){let a=e[0].dtype;if(a==="complex64"){let u=e.map(m=>Rh({inputs:{input:m},backend:r})),p=e.map(m=>r0({inputs:{input:m},backend:r})),h=au(u,t,r),c=au(p,t,r),f=Bi({inputs:{real:h,imag:c},backend:r});return u.forEach(m=>r.disposeIntermediateTensorInfo(m)),p.forEach(m=>r.disposeIntermediateTensorInfo(m)),r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(c),f}let n=r.shouldExecuteOnCPU(e);if(a==="string"&&(n=!0),n){let u=e.map(y=>{let A=w.sizeFromShape(y.shape.slice(t));return ve({inputs:{x:y},backend:r,attrs:{shape:[-1,A]}})}),p=u.map(y=>({vals:r.readSync(y.dataId),shape:y.shape})),h=N.computeOutShape(u.map(y=>y.shape),1),c=u[0].shape[0]===1,f=RQ(p,h,a,c),m=N.computeOutShape(e.map(y=>y.shape),t),g=r.makeTensorInfo(m,a,f);return u.forEach(y=>r.disposeIntermediateTensorInfo(y)),g}if(e.length>Y().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let u=Math.floor(e.length/2),p=au(e.slice(0,u),t,r),h=au(e.slice(u),t,r),c=au([p,h],t,r);return r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(h),c}if(Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].shape.length>1){let u=new Pre(e.map(p=>p.shape),t);return r.runWebGLProgram(u,e,a)}let{tensors2D:s,outShape:i}=zre(e,t,r),o=new $re(s.map(u=>u.shape)),l=r.runWebGLProgram(o,s,a);s.forEach(u=>r.disposeIntermediateTensorInfo(u));let d=ve({inputs:{x:l},attrs:{shape:i},backend:r});return r.disposeIntermediateTensorInfo(l),d}function zre(e,t,r){let a=N.computeOutShape(e.map(n=>n.shape),t);return{tensors2D:e.map(n=>ve({inputs:{x:n},attrs:{shape:[-1,w.sizeFromShape(n.shape.slice(t))]},backend:r})),outShape:a}}function f8(e){let{inputs:t,backend:r,attrs:a}=e,{axis:n}=a,s=w.parseAxisParam(n,t[0].shape)[0],i=N.computeOutShape(t.map(d=>d.shape),s);if(w.sizeFromShape(i)===0)return r.makeTensorInfo(i,t[0].dtype,[]);let o=t.filter(d=>w.sizeFromShape(d.shape)>0);if(o.length===1)return ha({inputs:{x:o[0]},backend:r});let l=o.map(d=>d.shape);return N.assertParamsConsistent(l,s),au(o,s,r)}var Dre={kernelName:$o,backendName:"webgl",kernelFunc:f8},m8=class{constructor(e,t=!1,r=null,a=!1,n=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let s=e.padInfo.top,i=e.padInfo.left,o=e.strideHeight,l=e.strideWidth,d=e.dilationHeight,u=e.dilationWidth,p=e.filterHeight,h=e.filterWidth,c=Math.floor(e.inChannels/4)*4,f=e.inChannels%4,m=e.dataFormat==="channelsLast",g=m?1:2,y=m?2:3,A=m?3:1,x="",b="";r&&(a?x=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${r}
|
|
}`:n?x=`float activation(float a) {
|
|
float b = getLeakyreluAlphaAtOutCoords();
|
|
${r}
|
|
}`:x=`
|
|
float activation(float x) {
|
|
${r}
|
|
}
|
|
`,b="result = activation(result);");let v=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),n&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${x}
|
|
|
|
const ivec2 strides = ivec2(${o}, ${l});
|
|
const ivec2 pads = ivec2(${s}, ${i});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d2 = coords[${A}];
|
|
|
|
ivec2 xRCCorner =
|
|
ivec2(coords[${g}], coords[${y}]) * strides - pads;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < ${p}; wR++) {
|
|
int xR = xRCorner + wR * ${d};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${h}; wC++) {
|
|
int xC = xCCorner + wC * ${u};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int d1 = 0; d1 < ${c}; d1 += 4) {
|
|
vec4 wValues = vec4(
|
|
getW(wR, wC, d1, d2),
|
|
getW(wR, wC, d1 + 1, d2),
|
|
getW(wR, wC, d1 + 2, d2),
|
|
getW(wR, wC, d1 + 3, d2)
|
|
);
|
|
|
|
if (${m}) {
|
|
vec4 xValues = vec4(
|
|
getX(batch, xR, xC, d1),
|
|
getX(batch, xR, xC, d1 + 1),
|
|
getX(batch, xR, xC, d1 + 2),
|
|
getX(batch, xR, xC, d1 + 3)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec4 xValues = vec4(
|
|
getX(batch, d1, xR, xC),
|
|
getX(batch, d1 + 1, xR, xC),
|
|
getX(batch, d1 + 2, xR, xC),
|
|
getX(batch, d1 + 3, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
}
|
|
|
|
if (${f===1}) {
|
|
|
|
if (${m}) {
|
|
dotProd +=
|
|
getX(batch, xR, xC, ${c}) *
|
|
getW(wR, wC, ${c}, d2);
|
|
} else {
|
|
dotProd +=
|
|
getX(batch, ${c}, xR, xC) *
|
|
getW(wR, wC, ${c}, d2);
|
|
}
|
|
|
|
} else if (${f===2}) {
|
|
vec2 wValues = vec2(
|
|
getW(wR, wC, ${c}, d2),
|
|
getW(wR, wC, ${c} + 1, d2)
|
|
);
|
|
|
|
if (${m}) {
|
|
vec2 xValues = vec2(
|
|
getX(batch, xR, xC, ${c}),
|
|
getX(batch, xR, xC, ${c} + 1)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec2 xValues = vec2(
|
|
getX(batch, ${c}, xR, xC),
|
|
getX(batch, ${c} + 1, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
} else if (${f===3}) {
|
|
vec3 wValues = vec3(
|
|
getW(wR, wC, ${c}, d2),
|
|
getW(wR, wC, ${c} + 1, d2),
|
|
getW(wR, wC, ${c} + 2, d2)
|
|
);
|
|
|
|
if (${m}) {
|
|
vec3 xValues = vec3(
|
|
getX(batch, xR, xC, ${c}),
|
|
getX(batch, xR, xC, ${c} + 1),
|
|
getX(batch, xR, xC, ${c} + 2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec3 xValues = vec3(
|
|
getX(batch, ${c}, xR, xC),
|
|
getX(batch, ${c} + 1, xR, xC),
|
|
getX(batch, ${c} + 2, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
|
|
float result = dotProd;
|
|
${v}
|
|
${b}
|
|
setOutput(result);
|
|
}
|
|
`}},_re=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let t=e.padInfo.front,r=e.padInfo.top,a=e.padInfo.left,n=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,d=e.dilationWidth,u=e.filterDepth,p=e.filterHeight,h=e.filterWidth,c=Math.floor(e.inChannels/4)*4,f=e.inChannels%4;this.userCode=`
|
|
const ivec3 strides = ivec3(${n}, ${s}, ${i});
|
|
const ivec3 pads = ivec3(${t}, ${r}, ${a});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int d2 = coords.u;
|
|
|
|
ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
|
|
int xFCorner = xFRCCorner.x;
|
|
int xRCorner = xFRCCorner.y;
|
|
int xCCorner = xFRCCorner.z;
|
|
|
|
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
|
|
// y(yF, yR, yC, d2). ? = to be determined. : = across all
|
|
// values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wF = 0; wF < ${u}; wF++) {
|
|
int xF = xFCorner + wF * ${o};
|
|
|
|
if (xF < 0 || xF >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${p}; wR++) {
|
|
int xR = xRCorner + wR * ${l};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${h}; wC++) {
|
|
int xC = xCCorner + wC * ${d};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int d1 = 0; d1 < ${c}; d1 += 4) {
|
|
vec4 xValues = vec4(
|
|
getX(batch, xF, xR, xC, d1),
|
|
getX(batch, xF, xR, xC, d1 + 1),
|
|
getX(batch, xF, xR, xC, d1 + 2),
|
|
getX(batch, xF, xR, xC, d1 + 3)
|
|
);
|
|
vec4 wValues = vec4(
|
|
getW(wF, wR, wC, d1, d2),
|
|
getW(wF, wR, wC, d1 + 1, d2),
|
|
getW(wF, wR, wC, d1 + 2, d2),
|
|
getW(wF, wR, wC, d1 + 3, d2)
|
|
);
|
|
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
if (${f===1}) {
|
|
dotProd +=
|
|
getX(batch, xF, xR, xC, ${c}) *
|
|
getW(wF, wR, wC, ${c}, d2);
|
|
} else if (${f===2}) {
|
|
vec2 xValues = vec2(
|
|
getX(batch, xF, xR, xC, ${c}),
|
|
getX(batch, xF, xR, xC, ${c} + 1)
|
|
);
|
|
vec2 wValues = vec2(
|
|
getW(wF, wR, wC, ${c}, d2),
|
|
getW(wF, wR, wC, ${c} + 1, d2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else if (${f===3}) {
|
|
vec3 xValues = vec3(
|
|
getX(batch, xF, xR, xC, ${c}),
|
|
getX(batch, xF, xR, xC, ${c} + 1),
|
|
getX(batch, xF, xR, xC, ${c} + 2)
|
|
);
|
|
vec3 wValues = vec3(
|
|
getW(wF, wR, wC, ${c}, d2),
|
|
getW(wF, wR, wC, ${c} + 1, d2),
|
|
getW(wF, wR, wC, ${c} + 2, d2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},Lre=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"},{name:"pad",type:"ivec2"},{name:"stride",type:"ivec2"},{name:"dilation",type:"ivec2"},{name:"inChannels",type:"int"},{name:"itemsPerBlockRow",type:"int"},{name:"outWidth",type:"int"}],this.outputShape=e,this.enableShapeUniforms=sa(this.outputShape.length);let{dataFormat:r}=t,a=Br(),n=r==="channelsLast",s=n?0:1,i=n?1:2,o=this.enableShapeUniforms?"if(blockIndex < outShape[1] && pos < outShape[0]) {":`if(blockIndex < ${e[1]} && pos < ${e[0]}) {`,l="";for(let d=0;d<=1;d++)for(let u=0;u<=1;u++)l+=`
|
|
blockIndex = rc.y + ${u};
|
|
pos = rc.x + ${d};
|
|
|
|
${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 (${n}) {
|
|
innerDims = vec2(d1, ch);
|
|
result[${d*2+u}] = getChannel(
|
|
getA(d0, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
} else {
|
|
innerDims = vec2(d0, d1);
|
|
result[${d*2+u}] = getChannel(
|
|
getA(ch, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
`;this.userCode=`
|
|
void main() {
|
|
ivec2 rc = getOutputCoords();
|
|
|
|
vec4 result = vec4(0);
|
|
|
|
int blockIndex, pos, offsetY, d0, offsetX, d1, ch;
|
|
vec2 innerDims;
|
|
|
|
${l}
|
|
|
|
${a.output} = result;
|
|
}
|
|
`}};function g8({x:e,filter:t,convInfo:r,backend:a,bias:n=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let l=e.shape,d=a.texData.get(e.dataId),u=r.inChannels,p=l[0]*l[1]*l[2],h=r.outChannels,c=r.dataFormat==="channelsLast",f=!1,m=!1,g,y=[];if(!((p===1||h===1)&&u>u8)&&d.isPacked&&c&&d.texture!=null&&l[2]%2!==0&&w.arraysEqual(d.shape.slice(-3),l.slice(-3))){let A=l[0]*l[1]*(l[2]+1),x={dataId:e.dataId,shape:[1,A,r.inChannels],dtype:e.dtype},b=d.shape;d.shape=d.shape.slice(),d.shape[d.shape.length-2]++,w.assert(Op(d.shape,x.shape),()=>`packed reshape ${d.shape} to ${x.shape} isn't free`);let v=ve({inputs:{x:t},backend:a,attrs:{shape:[1,r.inChannels,r.outChannels]}});y.push(v);let C=Af({a:x,b:v,backend:a,transposeA:f,transposeB:m,bias:n,activation:o,preluActivationWeights:s,leakyreluAlpha:i}),T=a.texData.get(C.dataId);w.assert(T.isPacked,()=>"batchMatMul result is expected to be packed"),d.shape=b,T.shape=r.outShape,g=ha({inputs:{x:C},backend:a}),g.shape=r.outShape,y.push(C)}else{let A=c?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],x=ve({inputs:{x:e},backend:a,attrs:{shape:[1,A,r.inChannels]}}),b=ve({inputs:{x:t},backend:a,attrs:{shape:[1,r.inChannels,r.outChannels]}}),v=Af({a:x,b,transposeA:f,transposeB:m,backend:a,bias:n,activation:o,preluActivationWeights:s,leakyreluAlpha:i});g=ve({inputs:{x:v},backend:a,attrs:{shape:r.outShape}}),y.push(x),y.push(b),y.push(v)}for(let A of y)a.disposeIntermediateTensorInfo(A);return g}function y8({x:e,filter:t,convInfo:r,backend:a,bias:n=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let{filterWidth:l,filterHeight:d,inChannels:u,outWidth:p,outHeight:h,dataFormat:c}=r,f=c==="channelsLast",m=l*d*u,g=h*p,y=[m,g],A=!0,x=!1,b=[],v=ve({inputs:{x:e},backend:a,attrs:{shape:e.shape.slice(1)}}),C=ve({inputs:{x:t},backend:a,attrs:{shape:[1,m,w.sizeFromShape(t.shape)/m]}});b.push(v),b.push(C);let T=new Lre(y,r),E=[v.shape,[r.padInfo.top,r.padInfo.left],[r.strideHeight,r.strideWidth],[r.dilationHeight,r.dilationWidth],[r.inChannels],[r.filterWidth*r.inChannels],[r.outWidth]],R=a.runWebGLProgram(T,[v],"float32",E),z=ve({inputs:{x:R},backend:a,attrs:{shape:[1,y[0],y[1]]}});b.push(R),b.push(z);let M=n!=null,I=s!=null,D=o==="leakyrelu",O=o?Qm(o,!0):null,j=new l8(z.shape,C.shape,[1,g,r.outChannels],A,x,M,O,I,D),X=[z,C];if(n&&X.push(n),I&&X.push(s),D){let ee=a.makeTensorInfo([],"float32",w.createScalarValue(i,"float32"));X.push(ee),b.push(ee)}let _=a.runWebGLProgram(j,X,"float32"),K=f?[1,h,p,r.outChannels]:[1,r.outChannels,h,p],W=ve({inputs:{x:_},backend:a,attrs:{shape:K}});b.push(_);for(let ee of b)a.disposeIntermediateTensorInfo(ee);return W}function Bre(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:d,dimRoundingMode:u}=a,p=N.convertConv2DDataFormat(l),h=N.computeConv2DInfo(n.shape,s.shape,i,d,o,u,!1,p),c;if(h.filterHeight===1&&h.filterWidth===1&&h.dilationHeight===1&&h.dilationWidth===1&&h.strideHeight===1&&h.strideWidth===1&&(h.padInfo.type==="SAME"||h.padInfo.type==="VALID"))c=g8({x:n,filter:s,convInfo:h,backend:r});else if(Y().getBool("WEBGL_CONV_IM2COL")&&n.shape[0]===1)c=y8({x:n,filter:s,convInfo:h,backend:r});else{let m=new m8(h);c=r.runWebGLProgram(m,[n,s],"float32")}let f=ve({inputs:{x:c},backend:r,attrs:{shape:h.outShape}});return r.disposeIntermediateTensorInfo(c),f}var Wre={kernelName:Ys,backendName:"webgl",kernelFunc:Bre},Vre=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,r=e.strideWidth,a=e.padInfo.top,n=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} - ${a};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${r} - ${n};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
if (${s}) {
|
|
float dyValue = getDy(b, yR, yC, d2);
|
|
float xValue = getX(b, xR, xC, d1);
|
|
dotProd += (xValue * dyValue);
|
|
} else {
|
|
float dyValue = getDy(b, d2, yR, yC);
|
|
float xValue = getX(b, d1, xR, xC);
|
|
dotProd += (xValue * dyValue);
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},Ure=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,r=e.filterWidth,a=e.strideHeight,n=e.strideWidth,s=e.dataFormat==="channelsLast",i=t-1-e.padInfo.top,o=r-1-e.padInfo.left,l=s?1:2,d=s?2:3,u=s?3:1;this.userCode=`
|
|
const ivec2 pads = ivec2(${i}, ${o});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d1 = coords[${u}];
|
|
|
|
ivec2 dyCorner = ivec2(coords[${l}], coords[${d}]) - 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) / ${a}.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 < ${r}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${n}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
int wCPerm = ${r} - 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);
|
|
}
|
|
`}},Gre=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideDepth,r=e.strideHeight,a=e.strideWidth,n=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} - ${n};
|
|
|
|
if (xF < 0 || xF >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yR = 0; yR < ${e.outHeight}; yR++) {
|
|
int xR = wR + yR * ${r} - ${s};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${a} - ${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);
|
|
}
|
|
`}},jre=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterDepth,r=e.filterHeight,a=e.filterWidth,n=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=t-1-e.padInfo.front,l=r-1-e.padInfo.top,d=a-1-e.padInfo.left;this.userCode=`
|
|
const ivec3 pads = ivec3(${o}, ${l}, ${d});
|
|
|
|
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) / ${n}.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 < ${r}; 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 = ${r} - 1 - wR;
|
|
|
|
for (int wC = 0; wC < ${a}; 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 = ${a} - 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 Hre(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,dy:s}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:d,filterShape:u}=a,p=N.convertConv2DDataFormat(l),h=N.computeConv2DInfo(n.shape,u,i,1,o,d,!1,p),c=new Vre(h);return r.runWebGLProgram(c,[n,s],"float32")}var qre={kernelName:Rf,backendName:"webgl",kernelFunc:Hre};function Kre(e){let{inputs:t,backend:r,attrs:a}=e,{dy:n,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:d,dimRoundingMode:u}=a,p=N.convertConv2DDataFormat(d),h=N.computeConv2DInfo(i,s.shape,o,1,l,u,!1,p),c=new Ure(h);return r.runWebGLProgram(c,[n,s],"float32")}var Xre={kernelName:Js,backendName:"webgl",kernelFunc:Kre};function Zre(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,filter:s}=t,{strides:i,pad:o,dilations:l}=a,d=N.computeConv3DInfo(n.shape,s.shape,i,l,o),u=new _re(d);return r.runWebGLProgram(u,[n,s],"float32")}var Yre={kernelName:Wp,backendName:"webgl",kernelFunc:Zre};function Jre(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,dy:s}=t,{strides:i,pad:o,filterShape:l}=a,d=N.computeConv3DInfo(n.shape,l,i,1,o),u=new Gre(d);return r.runWebGLProgram(u,[n,s],"float32")}var Qre={kernelName:Ff,backendName:"webgl",kernelFunc:Jre};function eae(e){let{inputs:t,backend:r,attrs:a}=e,{dy:n,filter:s}=t,{pad:i,strides:o,inputShape:l}=a,d=N.computeConv3DInfo(l,s.shape,o,1,i),u=new jre(d);return r.runWebGLProgram(u,[n,s],"float32")}var tae={kernelName:Mf,backendName:"webgl",kernelFunc:eae},rae=yd+`
|
|
return cos(x);
|
|
`,aae=it({opSnippet:rae}),nae={kernelName:Qs,backendName:"webgl",kernelFunc:aae},sae=`
|
|
float e2x = exp(-x);
|
|
return (e2x + 1.0 / e2x) / 2.0;
|
|
`,iae=it({opSnippet:sae}),oae={kernelName:ei,backendName:"webgl",kernelFunc:iae},lae=class{constructor(e,t,r,a,n){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[s,i,o,l]=e,[d]=t,[u,p]=r;this.outputShape=[d,u,p,l];let h=a==="bilinear"?1:0,[c,f]=[`${i-1}.0`,`${o-1}.0`],[m,g,y]=u>1?[`${(i-1)/(u-1)}`,"(y2-y1) * height_ratio",`y1*${c} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${c}`],[A,x,b]=p>1?[`${(o-1)/(p-1)}`,"(x2-x1) * width_ratio",`x1*${f} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${f}`];this.userCode=`
|
|
const float height_ratio = float(${m});
|
|
const float width_ratio = float(${A});
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int y = coords[1];
|
|
int x = coords[2];
|
|
int d = coords[3];
|
|
|
|
// get box vals
|
|
float y1 = getBoxes(b,0);
|
|
float x1 = getBoxes(b,1);
|
|
float y2 = getBoxes(b,2);
|
|
float x2 = getBoxes(b,3);
|
|
|
|
// get image in batch index
|
|
int bInd = round(getBoxInd(b));
|
|
if(bInd < 0 || bInd >= ${s}) {
|
|
return;
|
|
}
|
|
|
|
float height_scale = ${g};
|
|
float width_scale = ${x};
|
|
|
|
float in_y = ${y};
|
|
if( in_y < 0.0 || in_y > ${c} ) {
|
|
setOutput(float(${n}));
|
|
return;
|
|
}
|
|
float in_x = ${b};
|
|
if( in_x < 0.0 || in_x > ${f} ) {
|
|
setOutput(float(${n}));
|
|
return;
|
|
}
|
|
|
|
vec2 sourceFracIndexCR = vec2(in_x,in_y);
|
|
if(${h} == 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);
|
|
}
|
|
}
|
|
`}},uae=e=>{let{inputs:t,backend:r,attrs:a}=e,{image:n,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:d}=a,u=new lae(n.shape,s.shape,o,l,d);return r.runWebGLProgram(u,[n,s,i],"float32")},dae={kernelName:Oo,backendName:"webgl",kernelFunc:uae},tv=class{constructor(e,t,r){this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}],this.outputShape=e;let a=e.length,n=t?"0.0":`getX(${rv(a,"coords")})`,s=e[e.length-1],i="",o="";t?(i=r?`end != ${s-1}`:"end != 0",o=r?"end + 1":"end - 1"):(i=r?`end + pow2 < ${s}`:"end >= pow2",o=r?"end + pow2":"end - pow2"),this.userCode=`
|
|
void main() {
|
|
${vt(a)} coords = getOutputCoords();
|
|
int end = ${av(a,"coords")};
|
|
float val = ${n};
|
|
int pow2 = int(pow(2.0, index));
|
|
if (${i}) {
|
|
int idx = ${o};
|
|
${av(a,"coords")} = idx;
|
|
val += getX(${rv(a,"coords")});
|
|
}
|
|
setOutput(val);
|
|
}
|
|
`}};function rv(e,t){if(e===1)return`${t}`;if(e===2)return`${t}.x, ${t}.y`;if(e===3)return`${t}.x, ${t}.y, ${t}.z`;if(e===4)return`${t}.x, ${t}.y, ${t}.z, ${t}.w`;throw Error(`Cumulative sum for rank ${e} is not yet supported`)}function av(e,t){if(e===1)return`${t}`;if(e===2)return`${t}.y`;if(e===3)return`${t}.z`;if(e===4)return`${t}.w`;throw Error(`Cumulative sum for rank ${e} is not yet supported`)}function pae(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{axis:s,exclusive:i,reverse:o}=a,l=n.shape.length,d=N.getAxesPermutation([s],l),u=n;d!=null&&(u=Dr({inputs:{x:n},backend:r,attrs:{perm:d}}));let p=N.getInnerMostAxes(1,l)[0];if(p!==l-1)throw new Error(`WebGL cumsum shader expects an inner-most axis=${n.shape.length-1} but got axis=${s}`);let h=u.shape[p],c=ha({inputs:{x:u},backend:r});for(let f=0;f<=Math.ceil(Math.log2(h))-1;f++){let m=new tv(u.shape,!1,o),g=[[f]],y=c;c=r.runWebGLProgram(m,[c],c.dtype,g),r.disposeIntermediateTensorInfo(y)}if(i){let f=new tv(u.shape,i,o),m=c;c=r.runWebGLProgram(f,[c],c.dtype),r.disposeIntermediateTensorInfo(m)}if(d!=null){let f=N.getUndoAxesPermutation(d),m=Dr({inputs:{x:c},backend:r,attrs:{perm:f}});return r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(u),m}return c}var hae={kernelName:Po,backendName:"webgl",kernelFunc:pae};function cae(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,weights:s}=t,{size:i,binaryOutput:o}=a;if(n.shape.length===1){let l=r.readSync(n.dataId),d=r.readSync(s.dataId),u=ZI(l,d,s.dtype,s.shape,i);return r.makeTensorInfo([i],s.dtype,u)}else if(n.shape.length===2){let l=r.bufferSync(n),d=r.bufferSync(s),u=NQ(l,d,i,o);return r.makeTensorInfo(u.shape,s.dtype,u.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${n.shape.length}.`)}var fae={kernelName:$f,backendName:"webgl",kernelFunc:cae},mae=class{constructor(e,t,r){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=r,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 gae(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{blockSize:s,dataFormat:i}=a,o=n.shape[0],l=i==="NHWC"?n.shape[1]:n.shape[2],d=i==="NHWC"?n.shape[2]:n.shape[3],u=i==="NHWC"?n.shape[3]:n.shape[1],p=l*s,h=d*s,c=u/(s*s),f=i==="NHWC"?[o,p,h,c]:[o,c,p,h],m=new mae(f,s,i);return r.runWebGLProgram(m,[n],n.dtype)}var yae={kernelName:zo,backendName:"webgl",kernelFunc:gae},A8=class{constructor(e,t=!1,r=null,a=!1,n=!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=sa(this.outputShape.length);let s=e.filterHeight,i=e.filterWidth,o=e.outChannels/e.inChannels,l="",d="";r&&(a?l=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${r}
|
|
}`:n?l=`float activation(float a) {
|
|
float b = getLeakyreluAlphaAtOutCoords();
|
|
${r}
|
|
}`:l=`
|
|
float activation(float x) {
|
|
${r}
|
|
}
|
|
`,d="result = activation(result);");let u=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),n&&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;
|
|
${u}
|
|
${d}
|
|
setOutput(result);
|
|
}
|
|
`}},x8=class{constructor(e,t=!1,r=null,a=!1,n=!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=sa(this.outputShape.length);let s=e.outChannels/e.inChannels,i=e.padInfo.left,o=e.strideWidth,l=e.dilationWidth,d=e.filterHeight,u=e.filterWidth,p=u,h=`
|
|
int xR; int xC; int xCOffset;
|
|
vec4 wTexel; vec4 previous; vec4 final;`;for(let g=0;g<u;g++)h+=`
|
|
vec4 xTexelC${g*2};
|
|
int xTexelC${g*2}Ready;
|
|
vec4 xTexelC${g*2+1};
|
|
int xTexelC${g*2+1}Ready;
|
|
vec4 xC${g};`;h+=`
|
|
for (int r = 0; r < ${d}; r++) {
|
|
`;for(let g=0;g<u;g++)h+=`
|
|
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);`;h+=`
|
|
xR = xRCorner + r * dilations[0];
|
|
if (xR >=0 && xR < inDims[0]) {
|
|
`;for(let g=0;g<(p+1)/2;g++){let y=g*2;if(h+=`
|
|
xC = xCCorner + ${y*l};
|
|
`,o===1){if(y<u&&(i%2===1?(h+=`
|
|
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?h+=`
|
|
xC${y} = vec4(xTexelC${y-2}.zw, xTexelC${y}.xy);
|
|
`:h+=`
|
|
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);
|
|
}
|
|
`):h+=`
|
|
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<u)){let A=i%2===0?w.nearestLargerEven(l):l;l%2===0&&i%2===1||l%2!==0&&i%2!==1?(h+=`
|
|
xCOffset = xC + imod(pads[1], 2) + ${A};
|
|
|
|
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&&(h+=`
|
|
xCOffset -= 2;
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) {
|
|
xTexelC${y} = getX(batch, xR, xCOffset, d1);
|
|
xTexelC${y}Ready = 1;
|
|
}
|
|
`),h+=`
|
|
xC${y+1} = vec4(xTexelC${y}.zw, xTexelC${y+1}.xy);
|
|
`):A===1?h+=`
|
|
xC${y+1} = xTexelC${y};
|
|
`:h+=`
|
|
xCOffset = xC + ${A};
|
|
|
|
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<u&&(i%2===1?(h+=`
|
|
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<u&&(h+=`
|
|
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);
|
|
`)):(h+=`
|
|
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<u&&(h+=`
|
|
xC${y+1} = vec4(xTexelC${y}.zw, xTexelC${y+1}.zw);
|
|
`)));y<u&&(h+=`
|
|
wTexel = getW(r, ${y}, d1, q);
|
|
dotProd += xC${y} * vec4(wTexel.xz, wTexel.xz);
|
|
`,y+1<u&&(h+=`
|
|
wTexel = getW(r, ${y+1}, d1, q);
|
|
dotProd += xC${y+1} * vec4(wTexel.xz, wTexel.xz);
|
|
`))}h+=`
|
|
}
|
|
`,h+=`
|
|
}
|
|
`;let c="",f="";r&&(a?c=`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${r}
|
|
}`:n?c=`vec4 activation(vec4 a) {
|
|
vec4 b = getLeakyreluAlphaAtOutCoords();
|
|
${r}
|
|
}`:c=`vec4 activation(vec4 x) {
|
|
${r}
|
|
}`,f="result = activation(result);");let m=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),n&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${c}
|
|
|
|
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);
|
|
|
|
${h}
|
|
|
|
vec4 result = dotProd - vec4(0.000000000000001);
|
|
${m}
|
|
${f}
|
|
setOutput(result);
|
|
}
|
|
`}};function Aae(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,filter:s}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:d}=a,u=l;u==null&&(u=[1,1]),w.assert(N.eitherStridesOrDilationsAreOne(i,u),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let p=N.computeConv2DInfo(n.shape,s.shape,i,u,o,d,!0),h;Y().getBool("WEBGL_PACK_DEPTHWISECONV")&&p.strideWidth<=2&&p.outChannels/p.inChannels===1?h=new x8(p):h=new A8(p);let c=[[p.padInfo.top,p.padInfo.left],[p.strideHeight,p.strideWidth],[p.dilationHeight,p.dilationWidth],[p.inHeight,p.inWidth]];return r.runWebGLProgram(h,[n,s],"float32",c)}var xae={kernelName:ti,backendName:"webgl",kernelFunc:Aae},bae=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,r=e.strideWidth,a=e.padInfo.top,n=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} - ${a};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${r} - ${n};
|
|
|
|
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);
|
|
}
|
|
`}},vae=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,r=e.filterWidth,a=e.strideHeight,n=e.strideWidth,s=t-1-e.padInfo.top,i=r-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) / ${a}.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 < ${r}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${n}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
int wCPerm = ${r} - 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 wae(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,dy:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:d,filterShape:u}=a,p=N.computeConv2DInfo(n.shape,u,i,o,l,d,!0),h=new bae(p);return r.runWebGLProgram(h,[n,s],"float32")}var kae={kernelName:Pf,backendName:"webgl",kernelFunc:wae};function Iae(e){let{inputs:t,backend:r,attrs:a}=e,{dy:n,filter:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:d,inputShape:u}=a,p=N.computeConv2DInfo(u,s.shape,i,o,l,d,!0),h=new vae(p);return r.runWebGLProgram(h,[n,s],"float32")}var Sae={kernelName:Of,backendName:"webgl",kernelFunc:Iae},Tae=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 Cae(e){let{inputs:t,backend:r}=e,{x:a}=t,n=[...a.shape,...a.shape],s=w.sizeFromShape(a.shape),i=ve({inputs:{x:a},backend:r,attrs:{shape:[s]}}),o=new Tae(s),l=r.runWebGLProgram(o,[i],i.dtype),d=ve({inputs:{x:l},backend:r,attrs:{shape:n}});return r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(l),d}var Nae={kernelName:zf,backendName:"webgl",kernelFunc:Cae},Eae=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let{inHeight:t,inWidth:r,padInfo:a,strideHeight:n,strideWidth:s,filterHeight:i,filterWidth:o,dilationHeight:l,dilationWidth:d}=e,{top:u,left:p}=a;this.userCode=`
|
|
const ivec2 strides = ivec2(${n}, ${s});
|
|
const ivec2 pads = ivec2(${u}, ${p});
|
|
const float neg_infinity = -3.4e38;
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int d1 = coords.w;
|
|
ivec2 outTopLeftCorner =
|
|
coords.yz * strides - pads;
|
|
int hBeg = outTopLeftCorner.x;
|
|
int wBeg = outTopLeftCorner.y;
|
|
|
|
float curVal = neg_infinity;
|
|
for (int h = 0; h < ${i}; h++) {
|
|
int hIn = hBeg + h * ${l};
|
|
|
|
if (hIn >= 0 && hIn < ${t}) {
|
|
for (int w = 0; w < ${o}; w++) {
|
|
int wIn = wBeg + w * ${d};
|
|
|
|
if (wIn >= 0 && wIn < ${r}) {
|
|
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 Rae(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,filter:s}=t,{strides:i,pad:o,dilations:l}=a,d=N.computeDilation2DInfo(n.shape,s.shape,i,o,"NHWC",l),u,p=new Eae(d);u=r.runWebGLProgram(p,[n,s],"float32");let h=ve({inputs:{x:u},backend:r,attrs:{shape:d.outShape}});return r.disposeIntermediateTensorInfo(u),h}var Fae={kernelName:Vp,backendName:"webgl",kernelFunc:Rae};function Mae(e){let{inputs:t,backend:r,attrs:a}=e,{equation:n}=a,s=t,{allDims:i,summedDims:o,idDims:l}=N.decodeEinsumEquation(n,s.length);N.checkEinsumDimSizes(i.length,l,s);let{path:d,steps:u}=N.getEinsumComputePath(o,l),p=u.length,h=null,c=i.length,f=[];for(let m=0;m<p;++m){for(let g of u[m]){let{permutationIndices:y,expandDims:A}=N.getEinsumPermutation(c,l[g]),x;N.isIdentityPermutation(y)?x=s[g]:(x=Dr({inputs:{x:s[g]},backend:r,attrs:{perm:y}}),f.push(x));let b=x.shape.slice();for(let v=0;v<A.length;++v)b.splice(A[v],0,1);w.arraysEqual(x.shape,b)||(x=ve({inputs:{x},backend:r,attrs:{shape:b}}),f.push(x)),h===null?h=x:(h=Dx({inputs:{a:x,b:h},backend:r}),f.push(h))}m<p-1&&(d[m]>=0&&(h=t0({inputs:{x:h},backend:r,attrs:{axis:d[m]-(i.length-c),keepDims:!1}}),f.push(h)),c--)}for(let m of f)m!==h&&r.disposeIntermediateTensorInfo(m);return h}var $ae={kernelName:Up,backendName:"webgl",kernelFunc:Mae},Pae="return (x >= 0.0) ? x : (exp(x) - 1.0);",Oae=`
|
|
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;
|
|
`,zae=it({opSnippet:Pae,packedOpSnippet:Oae}),Dae={kernelName:ai,backendName:"webgl",kernelFunc:zae},_ae="return (b >= 1.0) ? a : a * (b + 1.0);",Lae=`
|
|
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
|
|
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
|
|
`,Bae=e=>{let{inputs:t,backend:r}=e,{dy:a,y:n}=t,s=Y().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Eh(Lae,a.shape,n.shape):new wu(_ae,a.shape,n.shape);return r.runWebGLProgram(s,[a,n],a.dtype)},Wae={kernelName:Df,backendName:"webgl",kernelFunc:Bae},Vae=`
|
|
return vec4(equal(a, b));
|
|
`,Uae="return float(a == b);",Gae=Ar({opSnippet:Uae,packedOpSnippet:Vae,dtype:"bool",cpuKernelImpl:FQ}),jae={kernelName:Do,backendName:"webgl",kernelFunc:Gae},Hae=`
|
|
// Error function is calculated approximately with elementary function.
|
|
// See "Handbook of Mathematical Functions with Formulas,
|
|
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
|
|
float p = ${N.ERF_P};
|
|
float a1 = ${N.ERF_A1};
|
|
float a2 = ${N.ERF_A2};
|
|
float a3 = ${N.ERF_A3};
|
|
float a4 = ${N.ERF_A4};
|
|
float a5 = ${N.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));
|
|
`,qae=it({opSnippet:Hae}),Kae={kernelName:zu,backendName:"webgl",kernelFunc:qae},Xae=yd+`
|
|
return exp(x);
|
|
`,Zae=`
|
|
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;
|
|
`,b8=it({opSnippet:Xae,packedOpSnippet:Zae,cpuKernelImpl:MQ,dtype:"float32"}),Yae={kernelName:ni,backendName:"webgl",kernelFunc:b8};function ky(e){let{inputs:t,attrs:r,backend:a}=e,{dim:n}=r,{input:s}=t,i=s.shape.length,o=s.shape.slice(),l=n;return n<0&&(w.assert(-(i+1)<=n,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+n+1),o.splice(l,0,1),ve({inputs:{x:s},backend:a,attrs:{shape:o}})}var Jae={kernelName:_o,backendName:"webgl",kernelFunc:ky},nv="return exp(x) - 1.0;",Qae=it({opSnippet:nv,packedOpSnippet:nv,cpuKernelImpl:$Q}),ene={kernelName:Lo,backendName:"webgl",kernelFunc:Qae},sv=class{constructor(e,t,r){this.variableNames=["real","imag"];let a=t[1];this.outputShape=t;let n=r?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,s=r?`${a}.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 = ${n};
|
|
|
|
float unaryOpComplex(float real, float expR, float imag, float expI) {
|
|
${i}
|
|
}
|
|
|
|
float mulMatDFT(int batch, int index) {
|
|
float indexRatio = float(index) / float(${a});
|
|
float exponentMultiplierTimesIndexRatio =
|
|
exponentMultiplier * indexRatio;
|
|
|
|
float result = 0.0;
|
|
|
|
for (int i = 0; i < ${a}; 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 v8(e,t,r){let a=r.texData.get(e.dataId),n=w.sizeFromShape(e.shape),s=e.shape[e.shape.length-1],i=n/s,o=ve({inputs:{x:e},backend:r,attrs:{shape:[i,s]}}),l=o.shape,d=new sv("real",l,t),u=new sv("imag",l,t),p=[{dataId:a.complexTensorInfos.real.dataId,dtype:a.complexTensorInfos.real.dtype,shape:l},{dataId:a.complexTensorInfos.imag.dataId,dtype:a.complexTensorInfos.imag.dtype,shape:l}],h=r.runWebGLProgram(d,p,"float32"),c=r.runWebGLProgram(u,p,"float32"),f=Bi({inputs:{real:h,imag:c},backend:r});r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(c);let m=ve({inputs:{x:f},backend:r,attrs:{shape:e.shape}});return r.disposeIntermediateTensorInfo(o),r.disposeIntermediateTensorInfo(f),m}function tne(e){let{inputs:t,backend:r}=e,{input:a}=t;return v8(a,!1,r)}var rne={kernelName:_f,backendName:"webgl",kernelFunc:tne},ane=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 Fh(e){let{backend:t,attrs:r}=e,{shape:a,value:n}=r,{dtype:s}=r;if(s=s||w.inferDtype(n),s==="string"){let i=w.getArrayFromDType(s,w.sizeFromShape(a));return i.fill(n),t.makeTensorInfo(a,s,i)}else{let i=new ane(a,n),o=[[n]];return t.runWebGLProgram(i,[],s,o)}}var nne={kernelName:Du,backendName:"webgl",kernelFunc:Fh},sne=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);
|
|
}
|
|
`}},ine={kernelName:Bo,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{let{image:r}=e,a=t,n=new sne(r.shape);return a.runWebGLProgram(n,[r],r.dtype)}},iv="return floor(x);",one=it({opSnippet:iv,packedOpSnippet:iv,cpuKernelImpl:PQ}),lne={kernelName:si,backendName:"webgl",kernelFunc:one},une=`
|
|
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;
|
|
}
|
|
`,dne=`
|
|
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);
|
|
`,pne=Ar({opSnippet:une,packedOpSnippet:dne,dtype:"int32"}),hne={kernelName:ii,backendName:"webgl",kernelFunc:pne},cne=class{constructor(e){this.variableNames=["A"];let t=Br(),[r,a]=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(${a}.0, ${r}.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));
|
|
}
|
|
`}},fne=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=Br(),[r,a]=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(${a}.0, ${r}.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;
|
|
}
|
|
`}},mne={kernelName:Ip,backendName:"webgl",kernelFunc:gne},Yl;function gne(e){let{inputs:t,backend:r,attrs:a}=e,{pixels:n}=t,{numChannels:s}=a,i=typeof HTMLVideoElement!="undefined"&&n instanceof HTMLVideoElement,o=typeof HTMLImageElement!="undefined"&&n instanceof HTMLImageElement,[l,d]=i?[n.videoWidth,n.videoHeight]:[n.width,n.height],u=[d,l],p=[d,l,s];(o||i)&&(Yl==null&&(Yl=document.createElement("canvas").getContext("2d")),Yl.canvas.width=l,Yl.canvas.height=d,Yl.drawImage(n,0,0,l,d),n=Yl.canvas);let h=r.makeTensorInfo(u,"int32");r.texData.get(h.dataId).usage=2,r.gpgpu.uploadPixelDataToTexture(r.getTexture(h.dataId),n);let c=Y().getBool("WEBGL_PACK")?new fne(p):new cne(p),f=r.runWebGLProgram(c,[h],"int32");return r.disposeData(h.dataId),f}function yne(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:d,dataFormat:u,dilations:p,dimRoundingMode:h,activation:c,leakyreluAlpha:f}=a,m=N.convertConv2DDataFormat(u),g=N.computeConv2DInfo(n.shape,s.shape,l,p,d,h,!1,m),y,A=[];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=g8({x:n,filter:s,convInfo:g,backend:r,bias:i,activation:c,preluActivationWeights:o,leakyreluAlpha:f});else if(Y().getBool("WEBGL_CONV_IM2COL")&&n.shape[0]===1)y=y8({x:n,filter:s,convInfo:g,backend:r,bias:i,activation:c,preluActivationWeights:o,leakyreluAlpha:f});else{let b=i!=null,v=o!=null,C=c==="leakyrelu",T=c?Qm(c,!1):null,E=new m8(g,b,T,v,C),R=[n,s];if(i&&R.push(i),o&&R.push(o),C){let z=r.makeTensorInfo([],"float32",w.createScalarValue(f,"float32"));R.push(z),A.push(z)}y=r.runWebGLProgram(E,R,"float32")}let x=ve({inputs:{x:y},backend:r,attrs:{shape:g.outShape}});return A.push(y),A.forEach(b=>r.disposeIntermediateTensorInfo(b)),x}var Ane={kernelName:Fs,backendName:"webgl",kernelFunc:yne};function xne(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:d,dilations:u,dimRoundingMode:p,activation:h,leakyreluAlpha:c}=a,f=[],m=u;m==null&&(m=[1,1]),w.assert(N.eitherStridesOrDilationsAreOne(l,m),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${m}'`);let g=N.computeConv2DInfo(n.shape,s.shape,l,m,d,p,!0),y=Y().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels===1,A=h?Qm(h,y):null,x=[n,s],b=i!=null,v=o!=null,C=h==="leakyrelu";if(b&&x.push(i),v&&x.push(o),C){let z=r.makeTensorInfo([],"float32",w.createScalarValue(c,"float32"));x.push(z),f.push(z)}let T;y?T=new x8(g,b,A,v,C):T=new A8(g,b,A,v,C);let E=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],R=r.runWebGLProgram(T,x,"float32",E);return f.forEach(z=>r.disposeIntermediateTensorInfo(z)),R}var bne={kernelName:Ms,backendName:"webgl",kernelFunc:xne},vne=class{constructor(e,t,r){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=r;let a=vt(t.length),n=vt(r.length),s=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
|
|
${a} strides = ${a}(${this.strides});
|
|
void main() {
|
|
${n} coords = getOutputCoords();
|
|
int flattenIndex = 0;
|
|
for (int j = 0; j < ${this.sliceDim}; j++) {
|
|
int index = round(getIndices(coords[0], j));
|
|
flattenIndex += index * ${s};
|
|
}
|
|
setOutput(getX(flattenIndex, coords[1]));
|
|
}
|
|
`}};function wne(e){let{inputs:t,backend:r}=e,{params:a,indices:n}=t,s=n.shape,i=s[s.length-1],o=w.sizeFromShape(a.shape),[l,d,u,p]=N.prepareAndValidate(a,n),h=ve({inputs:{x:n},backend:r,attrs:{shape:[d,i]}}),c=ve({inputs:{x:a},backend:r,attrs:{shape:[w.sizeFromShape(a.shape)/u,u]}});if(r.shouldExecuteOnCPU([a,n])||a.dtype==="string"){let y=r.readSync(n.dataId),A=r.bufferSync(a),x=OQ(y,A,a.dtype,d,i,u,p,a.shape,o);return r.makeTensorInfo(l,a.dtype,x.values)}let f=new vne(i,p,[d,u]),m=r.runWebGLProgram(f,[c,h],c.dtype),g=ve({inputs:{x:m},backend:r,attrs:{shape:l}});return r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(m),g}var kne={kernelName:Vo,backendName:"webgl",kernelFunc:wne},Ine=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let r=vt(this.rank),a=Sne(e,2);this.userCode=`
|
|
void main() {
|
|
${r} resRC = getOutputCoords();
|
|
int index = int(getIndices(resRC.x, resRC.z));
|
|
float inBounds = (index >= 0) && (index < ${e[2]}) ? 1.0 : 0.0;
|
|
setOutput(inBounds * getA(${a}));
|
|
}
|
|
`}};function Sne(e,t){let r=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[];for(let n=0;n<e.length;n++)n===2?a.push("index"):a.push(`${r[n]}`);return a.join()}function w8(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,indices:s}=t,{axis:i,batchDims:o}=a,l=w.parseAxisParam(i,n.shape)[0];if(Y().get("DEBUG")){let A=r.readSync(s.dataId),x=n.shape[l];for(let b=0;b<A.length;++b){let v=A[b];w.assert(v<=x-1&&v>=0,()=>`GatherV2: the index value ${v} is not in [0, ${x-1}]`)}}let d=N.segment_util.collectGatherOpShapeInfo(n,s,l,o),u=w.sizeFromShape(s.shape),p=[],h=ve({inputs:{x:n},backend:r,attrs:{shape:[d.batchSize,d.outerSize,d.dimSize,d.sliceSize]}}),c=ve({inputs:{x:s},backend:r,attrs:{shape:[d.batchSize,u/d.batchSize]}});p.push(h),p.push(c);let f=[d.batchSize,d.outerSize,u/d.batchSize,d.sliceSize];if(r.shouldExecuteOnCPU([n,s])||n.dtype==="string"){let A=r.bufferSync(c),x=r.bufferSync(h),b=zQ(x,A,f);return p.forEach(v=>r.disposeIntermediateTensorInfo(v)),r.makeTensorInfo(d.outputShape,b.dtype,b.values)}let m=new Ine(h.shape,f),g=r.runWebGLProgram(m,[h,c],h.dtype);p.push(g);let y=ve({inputs:{x:g},backend:r,attrs:{shape:d.outputShape}});return p.forEach(A=>r.disposeIntermediateTensorInfo(A)),y}var Tne={kernelName:Wo,backendName:"webgl",kernelFunc:w8},Cne="return float(a > b);",Nne=`
|
|
return vec4(greaterThan(a, b));
|
|
`,Ene=Ar({opSnippet:Cne,packedOpSnippet:Nne,cpuKernelImpl:DQ,dtype:"bool"}),Rne={kernelName:Uo,backendName:"webgl",kernelFunc:Ene},Fne="return float(a >= b);",Mne=`
|
|
return vec4(greaterThanEqual(a, b));
|
|
`,$ne=Ar({opSnippet:Fne,packedOpSnippet:Mne,dtype:"bool",cpuKernelImpl:_Q}),Pne={kernelName:li,backendName:"webgl",kernelFunc:$ne};function One(e){let{inputs:t,backend:r}=e,{input:a}=t;return v8(a,!0,r)}var zne={kernelName:Lf,backendName:"webgl",kernelFunc:One},Dne="return float(!isnan(x) && !isinf(x));",_ne=it({opSnippet:Dne,dtype:"bool"}),Lne={kernelName:_u,backendName:"webgl",kernelFunc:_ne},Bne="return float(isinf(x));",Wne=it({opSnippet:Bne,dtype:"bool"}),Vne={kernelName:Lu,backendName:"webgl",kernelFunc:Wne},Une="return float(isnan(x));",Gne=it({opSnippet:Une,dtype:"bool"}),jne={kernelName:Bu,backendName:"webgl",kernelFunc:Gne},Hne="return float(a < b);",qne=`
|
|
return vec4(lessThan(a, b));
|
|
`,Kne=Ar({opSnippet:Hne,packedOpSnippet:qne,cpuKernelImpl:LQ,dtype:"bool"}),Xne={kernelName:Go,backendName:"webgl",kernelFunc:Kne},Zne="return float(a <= b);",Yne=`
|
|
return vec4(lessThanEqual(a, b));
|
|
`,Jne=Ar({opSnippet:Zne,packedOpSnippet:Yne,cpuKernelImpl:BQ,dtype:"bool"}),Qne={kernelName:jo,backendName:"webgl",kernelFunc:Jne};function ese(e){let{backend:t,attrs:r}=e,{start:a,stop:n,num:s}=r,i=WQ(a,n,s);return t.makeTensorInfo([i.length],"float32",i)}var tse={kernelName:Bf,backendName:"webgl",kernelFunc:ese},rse=yd+`
|
|
return x < 0.0 ? 0./0. : log(x);
|
|
`,ase=`
|
|
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;
|
|
`,nse=it({opSnippet:rse,packedOpSnippet:ase,cpuKernelImpl:VQ}),sse={kernelName:pi,backendName:"webgl",kernelFunc:nse},ise=yd+`
|
|
return log(1.0 + x);
|
|
`,ose=it({opSnippet:ise}),lse={kernelName:Wu,backendName:"webgl",kernelFunc:ose},use="return float(a >= 1.0 && b >= 1.0);",dse=`
|
|
return vec4(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) *
|
|
vec4(greaterThanEqual(b, vec4(1.0))));
|
|
`,pse=Ar({opSnippet:use,packedOpSnippet:dse,dtype:"bool"}),hse={kernelName:Ho,backendName:"webgl",kernelFunc:pse},cse="return float(!(x >= 1.0));",fse=it({opSnippet:cse}),mse={kernelName:Vu,backendName:"webgl",kernelFunc:fse},gse="return float(a >= 1.0 || b >= 1.0);",yse=`
|
|
return min(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) +
|
|
vec4(greaterThanEqual(b, vec4(1.0))),
|
|
vec4(1.0));
|
|
`,Ase=Ar({opSnippet:gse,packedOpSnippet:yse,dtype:"bool"}),xse={kernelName:jp,backendName:"webgl",kernelFunc:Ase},bse=class{constructor(e,t,r,a,n){this.variableNames=["x"],this.outputShape=[];let s=t,i=e[3]-1;this.outputShape=e;let o,l=`float(${r}) + float(${a}) * sum`;n===.5?o=`inversesqrt(${l})`:n===1?o=`1.0/(${l})`:o=`exp(log(${l}) * float(-${n}));`,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);
|
|
}
|
|
`}},vse=class{constructor(e,t,r,a,n){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(${r}) + float(${a}) * sum`;n===.5?o=`inversesqrt(${l})`:n===1?o=`1.0/(${l})`:o=`exp(log(${l}) * float(-${n}));`,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);
|
|
}
|
|
`}},wse=e=>{let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=a,d=Y().getBool("WEBGL_PACK_NORMALIZATION")?new vse(n.shape,s,i,o,l):new bse(n.shape,s,i,o,l);return r.runWebGLProgram(d,[n],n.dtype)},kse={kernelName:Hp,backendName:"webgl",kernelFunc:wse},Ise=class{constructor(e,t,r,a,n){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=r,this.alpha=a,this.beta=n,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(${a}) * norm + float(${r});
|
|
|
|
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(${a})
|
|
* float(${n})
|
|
* getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)
|
|
/ norm;
|
|
if (k == d) {
|
|
dyi += pow(norm, -1.0 * ${n});
|
|
}
|
|
if (k == coords[3]) {
|
|
dyi *= getDy(b, r, c, d);
|
|
result += dyi;
|
|
}
|
|
}
|
|
else {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}},Sse=e=>{let{inputs:t,backend:r,attrs:a}=e,{x:n,y:s,dy:i}=t,{depthRadius:o,bias:l,alpha:d,beta:u}=a,p=new Ise(n.shape,o,l,d,u);return r.runWebGLProgram(p,[n,s,i],n.dtype)},Tse={kernelName:Wf,backendName:"webgl",kernelFunc:Sse};function Cse(e,t,r,a){let n=w.sizeFromShape(t),s=w.sizeFromShape(e.shape)/n,i=ve({inputs:{x:e},attrs:{shape:[s,n]},backend:a}),o=Cl(i,e.dtype,"max",a),l=ve({inputs:{x:o},attrs:{shape:r},backend:a});return a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(o),l}function k8(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{reductionIndices:s,keepDims:i}=a,o=n.shape.length,l=w.parseAxisParam(s,n.shape),d=l,u=N.getAxesPermutation(d,o),p=u!=null,h=r.shouldExecuteOnCPU([n]),c=n;if(p){if(h){let A=r.texData.get(c.dataId).values,x=new Array(o);for(let C=0;C<x.length;C++)x[C]=n.shape[u[C]];let b=zx(A,n.shape,n.dtype,u,x);c=r.makeTensorInfo(x,n.dtype);let v=r.texData.get(c.dataId);v.values=b}else c=e0(n,u,r);d=N.getInnerMostAxes(d.length,o)}N.assertAxesAreInnerMostDims("max",d,o);let[f,m]=N.computeOutAndReduceShapes(c.shape,d),g=f;i&&(g=N.expandShapeToKeepDim(f,l));let y;if(h){let A=r.texData.get(c.dataId).values,x=UQ(A,w.sizeFromShape(m),g,n.dtype);y=r.makeTensorInfo(g,n.dtype);let b=r.texData.get(y.dataId);b.values=x}else y=Cse(c,m,g,r);return p&&r.disposeIntermediateTensorInfo(c),y}var Nse={kernelName:hi,backendName:"webgl",kernelFunc:k8},Ese=a8+`
|
|
return max(a, b);
|
|
`,Rse=`
|
|
vec4 result = vec4(max(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+Jm+`
|
|
return result;
|
|
`,Fse=Ar({opSnippet:Ese,packedOpSnippet:Rse,cpuKernelImpl:GQ}),Mse={kernelName:ci,backendName:"webgl",kernelFunc:Fse};function $se(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t;hd(n,"maxPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,d=1;w.assert(N.eitherStridesOrDilationsAreOne(i,d),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${d}'`);let u=N.computePool2DInfo(n.shape,s,i,d,o,l);if(u.filterWidth===1&&u.filterHeight===1&&w.arraysEqual(u.inShape,u.outShape))return ha({inputs:{x:n},backend:r});let p=new zp(u,"max",!1);return r.runWebGLProgram(p,[n],n.dtype)}var Pse={kernelName:fi,backendName:"webgl",kernelFunc:$se};function Ose(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{filterSize:s,strides:i,pad:o,dataFormat:l,dimRoundingMode:d}=a,u=[1,1,1],p=N.computePool3DInfo(n.shape,s,i,u,o,d,l),h=new _x(p,"max",!1);return r.runWebGLProgram(h,[n],n.dtype)}var zse={kernelName:qp,backendName:"webgl",kernelFunc:Ose},Dse=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideHeight,r=e.strideWidth,a=e.dilationHeight,n=e.effectiveFilterHeight,s=e.effectiveFilterWidth,i=n-1-e.padInfo.top,o=s-1-e.padInfo.left,l=n*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 < ${n};
|
|
wR += ${a}) {
|
|
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) / ${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);
|
|
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);
|
|
}
|
|
`}},_se=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideDepth,r=e.strideHeight,a=e.strideWidth,n=e.dilationDepth,s=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterDepth,l=e.effectiveFilterHeight,d=e.effectiveFilterWidth,u=o-1-e.padInfo.front,p=l-1-e.padInfo.top,h=d-1-e.padInfo.left,c=o*l*d-1;this.userCode=`
|
|
const ivec3 pads = ivec3(${u}, ${p}, ${h});
|
|
|
|
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 += ${n}) {
|
|
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) / ${r}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
|
|
fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${d};
|
|
wC += ${i}) {
|
|
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(batch, idyD, idyR, idyC, ch);
|
|
int maxPosValue = ${c} -
|
|
int(getMaxPos(batch, idyD, idyR, idyC, ch));
|
|
|
|
// Get the current value, check it against the value from the
|
|
// position matrix.
|
|
int curPosValue =
|
|
wD * ${l} * ${d} +
|
|
wR * ${d} + wC;
|
|
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
|
|
|
|
dotProd += dyValue * mask;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function Lse(e){let{inputs:t,backend:r,attrs:a}=e,{dy:n,input:s}=t,i=s,{filterSize:o,strides:l,pad:d,dimRoundingMode:u}=a,p=[1,1,1],h=N.computePool3DInfo(i.shape,o,l,p,d,u),c=new _x(h,"max",!0),f=r.runWebGLProgram(c,[i],i.dtype),m=new _se(h),g=r.runWebGLProgram(m,[n,f],i.dtype);return r.disposeIntermediateTensorInfo(f),g}var Bse={kernelName:Uf,backendName:"webgl",kernelFunc:Lse};function Wse(e){let{inputs:t,backend:r,attrs:a}=e,{dy:n,input:s,output:i}=t,o=s;hd([s,i],"maxPoolGrad");let{filterSize:l,strides:d,pad:u,dimRoundingMode:p}=a,h=N.computePool2DInfo(o.shape,l,d,1,u,p),c=!0,f=new zp(h,"max",c),m=r.runWebGLProgram(f,[o],o.dtype),g=new Dse(h),y=r.runWebGLProgram(g,[n,m],o.dtype);return r.disposeIntermediateTensorInfo(m),y}var Vse={kernelName:Vf,backendName:"webgl",kernelFunc:Wse};function Use(e,t,r,a){let n=new zp(r,"max",!1),s=a.runWebGLProgram(n,[e],"float32");n=new zp(r,"max",!0,!0,t);let i=a.runWebGLProgram(n,[e],"float32");return[s,i]}var Gse={kernelName:Gf,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{x:a}=e,{filterSize:n,strides:s,pad:i,includeBatchInIndex:o}=t,l=r;w.assert(a.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${a.shape.length}.`);let d=[1,1];w.assert(N.eitherStridesOrDilationsAreOne(s,d),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${d}'`);let u=N.computePool2DInfo(a.shape,n,s,d,i),[p,h]=Use(a,o,u,l);return[p,h]}};function jse(e,t,r,a){let n=w.sizeFromShape(t),s=w.sizeFromShape(e.shape)/n,i=ve({inputs:{x:e},attrs:{shape:[s,n]},backend:a}),o=Cl(i,"float32","mean",a),l=ve({inputs:{x:o},attrs:{shape:r},backend:a});return a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(o),l}var Hse={kernelName:mi,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{x:a}=e,{keepDims:n,axis:s}=t,i=r,o=a.shape.length,l=w.parseAxisParam(s,a.shape),d=l,u=N.getAxesPermutation(d,o),p=u!=null,h=i.shouldExecuteOnCPU([a]),c=[],f=a;if(p){if(h){let x=i.texData.get(f.dataId).values,b=new Array(o);for(let T=0;T<b.length;T++)b[T]=a.shape[u[T]];let v=zx(x,a.shape,a.dtype,u,b);f=i.makeTensorInfo(b,a.dtype);let C=i.texData.get(f.dataId);C.values=v}else f=e0(a,u,i);c.push(f),d=N.getInnerMostAxes(d.length,o)}N.assertAxesAreInnerMostDims("sum",d,o);let[m,g]=N.computeOutAndReduceShapes(f.shape,d),y=m;n&&(y=N.expandShapeToKeepDim(m,l));let A=jse(f,g,y,i);for(let x of c)i.disposeIntermediateTensorInfo(x);return A}};function qse(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{axis:s,keepDims:i}=a,o=n.shape.length,l=w.parseAxisParam(s,n.shape),d=l,u=N.getAxesPermutation(d,o),p=n;u!=null&&(p=Dr({inputs:{x:n},backend:r,attrs:{perm:u}}),d=N.getInnerMostAxes(d.length,n.shape.length)),N.assertAxesAreInnerMostDims("min",d,o);let[h,c]=N.computeOutAndReduceShapes(p.shape,d),f=w.sizeFromShape(c),m=ve({inputs:{x:p},backend:r,attrs:{shape:[-1,f]}}),g=Cl(m,m.dtype,"min",r),y;if(i){let A=N.expandShapeToKeepDim(h,l);y=ve({inputs:{x:g},backend:r,attrs:{shape:A}})}else y=ve({inputs:{x:g},backend:r,attrs:{shape:h}});return r.disposeIntermediateTensorInfo(m),r.disposeIntermediateTensorInfo(g),u!=null&&r.disposeIntermediateTensorInfo(p),y}var Kse={kernelName:gi,backendName:"webgl",kernelFunc:qse},Xse=a8+`
|
|
return min(a, b);
|
|
`,Zse=`
|
|
vec4 result = vec4(min(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+Jm+`
|
|
return result;
|
|
`,Yse=Ar({opSnippet:Xse,packedOpSnippet:Zse,cpuKernelImpl:jQ}),Jse={kernelName:yi,backendName:"webgl",kernelFunc:Yse},Qse=class{constructor(e,t,r){this.variableNames=["x"],this.outputShape=t.map((d,u)=>d[0]+e[u]+d[1]);let a=e.length,n=vt(a),s=t.map(d=>d[0]).join(","),i=t.map((d,u)=>d[0]+e[u]).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,a),l=r==="reflect"?0:1;if(a===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=`
|
|
${n} start = ${n}(${s});
|
|
${n} end = ${n}(${i});
|
|
|
|
void main() {
|
|
${n} outC = getOutputCoords();
|
|
for (int i = 0; i < ${a}; 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};
|
|
}
|
|
}
|
|
${n} coords = outC - start;
|
|
setOutput(getX(${o}));
|
|
}
|
|
`}},eie=class{constructor(e,t,r){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((c,f)=>c[0]+e[f]+c[1]);let a=e.length,n=vt(a),s=t.map(c=>c[0]).join(","),i=t.map((c,f)=>c[0]+e[f]).join(","),o=$r("rc",a),l=$r("source",a),d=`${o[a-1]} < ${this.outputShape[a-1]}`,u=a===1?"source":`vec2(${l.slice(-2).join()})`,p=r==="reflect"?0:1,h="";if(a===1){let c=`
|
|
${n} source = rc;
|
|
if (source < start) {
|
|
source = start * 2 - source - ${p};
|
|
} else if (source >= end) {
|
|
source = (end - 1) * 2 - source + ${p};
|
|
}
|
|
source -= start;
|
|
`;h=`
|
|
${n} rc = outputLoc;
|
|
${c}
|
|
result[0] = getChannel(getX(${l.join()}), ${u});
|
|
${o[a-1]} += 1;
|
|
if(${d}) {
|
|
${c}
|
|
result[1] = getChannel(getX(${l.join()}), ${u});
|
|
}
|
|
`}else{let c=`
|
|
${n} source = rc;
|
|
${n} lt = ${n}(lessThan(source, start));
|
|
${n} gte = ${n}(greaterThanEqual(source, end));
|
|
${n} orig = 1 - (lt + gte);
|
|
source = orig * source +
|
|
lt * (start * 2 - source - ${p}) +
|
|
gte * ((end - 1) * 2 - source + ${p});
|
|
source -= start;
|
|
`;h=`
|
|
${n} rc = outputLoc;
|
|
${c}
|
|
result[0] = getChannel(getX(${l.join()}), ${u});
|
|
${o[a-1]} += 1;
|
|
if(${d}) {
|
|
${c}
|
|
result[1] = getChannel(getX(${l.join()}), ${u});
|
|
}
|
|
rc = outputLoc;
|
|
${o[a-2]} += 1;
|
|
if(${o[a-2]} < ${this.outputShape[a-2]}) {
|
|
${c}
|
|
result[2] = getChannel(getX(${l.join()}), ${u});
|
|
${o[a-1]} += 1;
|
|
if(${d}) {
|
|
${c}
|
|
result[3] = getChannel(getX(${l.join()}), ${u});
|
|
}
|
|
}
|
|
`}this.userCode=`
|
|
const ${n} start = ${n}(${s});
|
|
const ${n} end = ${n}(${i});
|
|
|
|
void main() {
|
|
${n} outputLoc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
${h}
|
|
setOutput(result);
|
|
}
|
|
`}},tie=({inputs:e,backend:t,attrs:r})=>{let{x:a}=e,{paddings:n,mode:s}=r,i=Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new eie(a.shape,n,s):new Qse(a.shape,n,s);return t.runWebGLProgram(i,[a],a.dtype)},rie={kernelName:Ai,backendName:"webgl",kernelFunc:tie},aie=`if (b == 0.0) return NAN;
|
|
return mod(a, b);`,nie=`
|
|
vec4 result = mod(a, b);
|
|
vec4 isNaN = vec4(equal(b, vec4(0.0)));
|
|
`+Jm+`
|
|
return result;
|
|
`,sie=Ar({opSnippet:aie,packedOpSnippet:nie}),iie={kernelName:Uu,backendName:"webgl",kernelFunc:sie},oie=class{constructor(e,t,r){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[e,r],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}));
|
|
}
|
|
`}},lie=`
|
|
if (a == b) {
|
|
return 1.0;
|
|
};
|
|
return a / b;`,uie=`
|
|
// 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;
|
|
`,I8=Ar({opSnippet:lie,packedOpSnippet:uie,checkOutOfBounds:!0}),die={kernelName:ri,backendName:"webgl",kernelFunc:I8},ov="return a - b;",S8=Ar({opSnippet:ov,packedOpSnippet:ov,supportsComplex:!0,cpuKernelImpl:oee}),pie={kernelName:$i,backendName:"webgl",kernelFunc:S8};function T8(e){let{inputs:t,backend:r,attrs:a}=e,{logits:n}=t,{dim:s}=a,i=w.parseAxisParam([s],n.shape),o=k8({inputs:{x:n},backend:r,attrs:{reductionIndices:i,keepDims:!1}}),l=N.expandShapeToKeepDim(o.shape,i),d=ve({inputs:{x:o},backend:r,attrs:{shape:l}}),u=S8({inputs:{a:n,b:d},backend:r}),p=b8({inputs:{x:u},backend:r}),h=t0({inputs:{x:p},backend:r,attrs:{axis:i,keepDims:!1}}),c=ve({inputs:{x:h},backend:r,attrs:{shape:l}}),f=I8({inputs:{a:p,b:c},backend:r});return r.disposeIntermediateTensorInfo(o),r.disposeIntermediateTensorInfo(d),r.disposeIntermediateTensorInfo(u),r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(c),f}var hie={kernelName:Fi,backendName:"webgl",kernelFunc:T8};function cie(e){let{inputs:t,backend:r,attrs:a}=e,{logits:n}=t,{numSamples:s,seed:i,normalized:o}=a,l=o?n:T8({inputs:{logits:n},backend:r,attrs:{dim:n.shape.length-1}}),d=l.shape[0],u=l.shape[1],p=new oie(d,u,s),h=[[i]],c=r.runWebGLProgram(p,[l],"int32",h);return o||r.disposeIntermediateTensorInfo(l),c}var fie={kernelName:jf,backendName:"webgl",kernelFunc:cie},mie=Ka+`
|
|
return -x;
|
|
`,gie=`
|
|
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 yie(e){let{inputs:t,backend:r}=e,{x:a}=t;if(r.shouldExecuteOnCPU([a])){let s=r.texData.get(a.dataId),[i,o]=qQ(s.values,a.shape,a.dtype);return r.makeTensorInfo(o,a.dtype,i)}let n;return Y().getBool("WEBGL_PACK_UNARY_OPERATIONS")?n=new co(a.shape,gie):n=new Gn(a.shape,mie),r.runWebGLProgram(n,[a],a.dtype)}var Aie={kernelName:qo,backendName:"webgl",kernelFunc:yie},xie=Ha.nonMaxSuppressionV3Impl;function bie(e){N.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:r,attrs:a}=e,{boxes:n,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=a,d=r.readSync(n.dataId),u=r.readSync(s.dataId),{selectedIndices:p}=xie(d,u,i,o,l);return r.makeTensorInfo([p.length],"int32",new Int32Array(p))}var vie={kernelName:Xo,backendName:"webgl",kernelFunc:bie},wie=Ha.nonMaxSuppressionV4Impl;function kie(e){N.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:r,attrs:a}=e,{boxes:n,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:d}=a,u=r.readSync(n.dataId),p=r.readSync(s.dataId),{selectedIndices:h,validOutputs:c}=wie(u,p,i,o,l,d);return[r.makeTensorInfo([h.length],"int32",new Int32Array(h)),r.makeTensorInfo([],"int32",new Int32Array([c]))]}var Iie={kernelName:Gu,backendName:"webgl",kernelFunc:kie},Sie=Ha.nonMaxSuppressionV5Impl;function Tie(e){N.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:r,attrs:a}=e,{boxes:n,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:d}=a,u=r.readSync(n.dataId),p=r.readSync(s.dataId),h=i,c=o,f=l,m=d,{selectedIndices:g,selectedScores:y}=Sie(u,p,h,c,f,m);return[r.makeTensorInfo([g.length],"int32",new Int32Array(g)),r.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var Cie={kernelName:Zo,backendName:"webgl",kernelFunc:Tie},Nie=class{constructor(e,t,r,a){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int index = round(getIndices(coords.x));
|
|
setOutput(mix(float(${a}), float(${r}),
|
|
float(index == coords.y)));
|
|
}
|
|
`}},Eie=e=>{let{inputs:t,backend:r,attrs:a}=e,{indices:n}=t,{depth:s,onValue:i,offValue:o}=a,l=w.sizeFromShape(n.shape),d=new Nie(l,s,i,o),u=ve({inputs:{x:n},backend:r,attrs:{shape:[l]}}),p=r.runWebGLProgram(d,[u],n.dtype);r.disposeIntermediateTensorInfo(u);let h=[...n.shape,s],c=ve({inputs:{x:p},backend:r,attrs:{shape:h}});return r.disposeIntermediateTensorInfo(p),c},Rie={kernelName:Jo,backendName:"webgl",kernelFunc:Eie};function xf(e){let{inputs:t,backend:r}=e,{x:a}=t;if(a.dtype==="complex64"){let n=Rh({inputs:{input:a},backend:r}),s=xf({inputs:{x:n},backend:r}),i=r0({inputs:{input:a},backend:r}),o=xf({inputs:{x:i},backend:r}),l=Bi({inputs:{real:s,imag:o},backend:r});return r.disposeIntermediateTensorInfo(n),r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(o),l}else return Fh({attrs:{shape:a.shape,dtype:a.dtype,value:a.dtype==="string"?"":0},backend:r})}var Fie={kernelName:ml,backendName:"webgl",kernelFunc:xf};function C8(e){let{inputs:t,backend:r}=e,{x:a}=t;if(a.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(a.dtype==="complex64"){let n=Rh({inputs:{input:a},backend:r}),s=C8({inputs:{x:n},backend:r}),i=r0({inputs:{input:a},backend:r}),o=xf({inputs:{x:i},backend:r}),l=Bi({inputs:{real:s,imag:o},backend:r});return r.disposeIntermediateTensorInfo(n),r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(o),l}else return Fh({attrs:{shape:a.shape,dtype:a.dtype,value:1},backend:r})}var Mie={kernelName:Yo,backendName:"webgl",kernelFunc:C8};function $ie(e){let{inputs:t,backend:r,attrs:a}=e,{axis:n}=a;if(t.length===1)return ky({inputs:{input:t[0]},backend:r,attrs:{dim:n}});let s=t[0].shape,i=t[0].dtype;t.forEach(u=>{w.assertShapesMatch(s,u.shape,"All tensors passed to stack must have matching shapes"),w.assert(i===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(u=>{let p=ky({inputs:{input:u},backend:r,attrs:{dim:n}});return o.push(p),p}),d=f8({inputs:l,backend:r,attrs:{axis:n}});return o.forEach(u=>r.disposeIntermediateTensorInfo(u)),d}var Pie={kernelName:Qo,backendName:"webgl",kernelFunc:$ie},Oie=class{constructor(e,t,r){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((l,d)=>l[0]+e[d]+l[1]);let a=e.length,n=vt(a),s=t.map(l=>l[0]).join(","),i=t.map((l,d)=>l[0]+e[d]).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,a);if(a===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=`
|
|
${n} start = ${n}(${s});
|
|
${n} end = ${n}(${i});
|
|
|
|
void main() {
|
|
${n} outC = getOutputCoords();
|
|
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
|
|
setOutput(value);
|
|
} else {
|
|
${n} coords = outC - start;
|
|
setOutput(getX(${o}));
|
|
}
|
|
}
|
|
`}},zie=class{constructor(e,t,r){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((f,m)=>f[0]+e[m]+f[1]);let a=e.length,n=vt(a),s=t.map(f=>f[0]).join(","),i=t.map((f,m)=>f[0]+e[m]).join(","),o=$r("rc",a),l=$r("source",a),d=`${o[a-1]} < ${this.outputShape[a-1]}`,u=a===1?"source":`vec2(${l.slice(-2).join()})`,p=[`${n} rc = outputLoc;`,`${o[a-1]} += 1;
|
|
if(${d}) {
|
|
`,a===1?"":`}
|
|
rc = outputLoc;
|
|
${o[a-2]} += 1;
|
|
if(${o[a-2]} < ${this.outputShape[a-2]}) {`,a===1?"":` ${o[a-1]} += 1;
|
|
if(${d}) {`],h=a===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",c="";for(let f=0,m=a===1?2:4;f<m;f++)c+=`
|
|
${p[f]}
|
|
if (${h}) {
|
|
result[${f}] = float(value);
|
|
} else {
|
|
${n} source = rc - start;
|
|
result[${f}] = getChannel(getX(${l.join()}), ${u});
|
|
}
|
|
`;c+=a===1?"} ":"}}",this.userCode=`
|
|
const ${n} start = ${n}(${s});
|
|
const ${n} end = ${n}(${i});
|
|
|
|
void main() {
|
|
${n} outputLoc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
${c}
|
|
setOutput(result);
|
|
}
|
|
`}},N8=e=>{let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{paddings:s,constantValue:i}=a;if(w.sizeFromShape(n.shape)===0){let d=s.map((u,p)=>u[0]+n.shape[p]+u[1]);return Fh({backend:r,attrs:{shape:d,value:i,dtype:n.dtype}})}let o=Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new zie(n.shape,s,i):new Oie(n.shape,s,i),l=[[i]];return r.runWebGLProgram(o,[n],n.dtype,l)},Die={kernelName:bi,backendName:"webgl",kernelFunc:N8},_ie=`
|
|
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);
|
|
`,Lie=`
|
|
// isModRound1 has 1 for components with round(mod(b, 2.0)) == 1, 0 otherwise.
|
|
vec4 isModRound1 = vec4(equal(round(mod(b, 2.0)), ivec4(1)));
|
|
vec4 multiplier = sign(a) * isModRound1 + (vec4(1.0) - isModRound1);
|
|
vec4 result = multiplier * pow(abs(a), b);
|
|
|
|
// Ensure that a^0 = 1, including 0^0 = 1 as this correspond to TF and JS
|
|
bvec4 isExpZero = equal(b, vec4(0.0));
|
|
result.r = isExpZero.r ? 1.0 : result.r;
|
|
result.g = isExpZero.g ? 1.0 : result.g;
|
|
result.b = isExpZero.b ? 1.0 : result.b;
|
|
result.a = isExpZero.a ? 1.0 : result.a;
|
|
|
|
vec4 isNaN = vec4(lessThan(a, vec4(0.0))) * vec4(lessThan(floor(b), b));
|
|
`+Jm+`
|
|
return result;
|
|
`,Bie=Ar({opSnippet:_ie,packedOpSnippet:Lie}),Wie={kernelName:vi,backendName:"webgl",kernelFunc:Bie};function Vie(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{axis:s,keepDims:i}=a,o=n.shape.length,l=[],d=w.parseAxisParam(s,n.shape),u=d,p=N.getAxesPermutation(u,o),h=n;p!=null&&(h=Dr({inputs:{x:n},backend:r,attrs:{perm:p}}),u=N.getInnerMostAxes(u.length,o),l.push(h)),N.assertAxesAreInnerMostDims("prod",u,o);let c;if(r.shouldExecuteOnCPU([h])){let f=r.texData.get(h.dataId).values,{outVals:m,outShape:g,outDtype:y}=XQ(h.shape,h.dtype,f,u);c=r.makeTensorInfo(g,y,m)}else{let[f,m]=N.computeOutAndReduceShapes(h.shape,u),g=w.sizeFromShape(m),y=ve({inputs:{x:h},backend:r,attrs:{shape:[-1,g]}}),A=ah(n.dtype),x=Cl(y,A,"prod",r);c=ve({inputs:{x},backend:r,attrs:{shape:f}}),l.push(y),l.push(x)}if(i){l.push(c);let f=N.expandShapeToKeepDim(c.shape,d);c=ve({inputs:{x:c},backend:r,attrs:{shape:f}})}return l.forEach(f=>r.disposeIntermediateTensorInfo(f)),c}var Uie={kernelName:el,backendName:"webgl",kernelFunc:Vie},E8=e=>{let{backend:t,attrs:r}=e,{start:a,stop:n,step:s,dtype:i}=r,o=ZQ(a,n,s,i);return t.makeTensorInfo([o.length],i,o)},Gie={kernelName:ju,backendName:"webgl",kernelFunc:E8},jie="return 1.0 / x;",Hie=it({opSnippet:jie}),qie={kernelName:Hu,backendName:"webgl",kernelFunc:Hie},Kie=Ka+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,Xie=`
|
|
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;
|
|
`,Zie=it({opSnippet:Kie,packedOpSnippet:Xie}),Yie={kernelName:ki,backendName:"webgl",kernelFunc:Zie},Jie=Ka+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,Qie=`
|
|
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;
|
|
`,eoe=it({opSnippet:Jie,packedOpSnippet:Qie}),toe={kernelName:Si,backendName:"webgl",kernelFunc:eoe},roe=class{constructor(e,t,r,a,n){this.variableNames=["A"],this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,r,l];let d=[a&&t>1?i-1:i,a&&r>1?o-1:o],u=[a&&t>1?t-1:t,a&&r>1?r-1:r],p;n?p="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":p="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec2 effectiveInputOverOutputRatioRC = vec2(
|
|
${d[0]/u[0]},
|
|
${d[1]/u[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 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);
|
|
}
|
|
`}},aoe=class{constructor(e,t,r,a,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,r,l];let d=[a&&t>1?i-1:i,a&&r>1?o-1:o],u=[a&&t>1?t-1:t,a&&r>1?r-1:r],p;n?p="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":p="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec3 effectiveInputOverOutputRatioRC = vec3(
|
|
${d[0]/u[0]},
|
|
${d[1]/u[1]},
|
|
${d[1]/u[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 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 < ${r-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 noe(e){let{inputs:t,backend:r,attrs:a}=e,{images:n}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a,[l,d]=o,u=Y().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new aoe(n.shape,l,d,s,i):new roe(n.shape,l,d,s,i);return r.runWebGLProgram(u,[n],"float32")}var soe={kernelName:Ii,backendName:"webgl",kernelFunc:noe},ioe=class{constructor(e,t,r){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,a,n]=t,[,s,i]=e,o=[r&&s>1?a-1:a,r&&i>1?n-1:n],l=[r&&s>1?s-1:s,r&&i>1?i-1:i],d=o[0]/l[0],u=o[1]/l[1],p=1/d,h=1/u,c=Math.ceil(p)*2+2,f=Math.ceil(h)*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(${d});
|
|
const float widthScale = float(${u});
|
|
|
|
const float invHeightScale = float(${p});
|
|
const float invWidthScale = float(${h});
|
|
|
|
const int winHeight = int(${c});
|
|
const int winWidth = int(${f});
|
|
|
|
// Compute bounds for where in dy we will look
|
|
float startRLerp = floor(float(r) * invHeightScale);
|
|
int startDyR = int(startRLerp - float(winHeight / 2));
|
|
|
|
float startCLerp = floor(float(c) * invWidthScale);
|
|
int startDyC = int(startCLerp - float(winWidth / 2));
|
|
|
|
// Loop over dy
|
|
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
|
|
int dyR = dyROffset + startDyR;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyR < 0 || dyR >= ${s}) {
|
|
continue;
|
|
}
|
|
|
|
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
|
|
int dyC = dyCOffset + startDyC;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyC < 0 || dyC >= ${i}) {
|
|
continue;
|
|
}
|
|
|
|
float dxR = float(dyR) * heightScale;
|
|
int topDxRIndex = int(floor(dxR));
|
|
int bottomDxRIndex = int(min(ceil(dxR), ${a-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), ${n-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 ooe(e){let{inputs:t,backend:r,attrs:a}=e,{images:n,dy:s}=t,{alignCorners:i}=a,o=new ioe(s.shape,n.shape,i);return r.runWebGLProgram(o,[s],s.dtype)}var loe={kernelName:qf,backendName:"webgl",kernelFunc:ooe},uoe=class{constructor(e,t,r,a,n){this.variableNames=["A"],this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,r,l];let d=[a&&t>1?i-1:i,a&&r>1?o-1:o],u=[a&&t>1?t-1:t,a&&r>1?r-1:r],p=a?"0.5":"0.0",h;n?h="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":h="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec2 effectiveInputOverOutputRatioRC = vec2(
|
|
${d[0]/u[0]},
|
|
${d[1]/u[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 = ${h};
|
|
|
|
// Compute the coordinators of nearest neighbor point.
|
|
ivec2 sourceNearestRC = ivec2(
|
|
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${p})));
|
|
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
|
|
|
|
setOutput(newValue);
|
|
}
|
|
`}},doe=class{constructor(e,t,r,a,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,r,l];let d=[a&&t>1?i-1:i,a&&r>1?o-1:o],u=[a&&t>1?t-1:t,a&&r>1?r-1:r],p=a?"0.5":"0.0",h;n?h="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":h="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec3 effectiveInputOverOutputRatioRC = vec3(
|
|
${d[0]/u[0]},
|
|
${d[1]/u[1]},
|
|
${d[1]/u[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 = ${h};
|
|
|
|
// Compute the coordinators of nearest neighbor point.
|
|
ivec3 sourceNearestRC = ivec3(
|
|
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${p})));
|
|
|
|
// Should we calculate next column and row elements in 2x2 packed cell.
|
|
bool hasNextCol = d < ${l-1};
|
|
bool hasNextRow = coords.z < ${r-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 poe(e){let{inputs:t,backend:r,attrs:a}=e,{images:n}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a,[l,d]=o,u=Y().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new doe(n.shape,l,d,s,i):new uoe(n.shape,l,d,s,i);return r.runWebGLProgram(u,[n],n.dtype)}var hoe={kernelName:qu,backendName:"webgl",kernelFunc:poe},coe=class{constructor(e,t,r){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,a,n]=t,[,s,i]=e,o=[r&&s>1?a-1:a,r&&i>1?n-1:n],l=[r&&s>1?s-1:s,r&&i>1?i-1:i],d=o[0]/l[0],u=o[1]/l[1],p=1/d,h=1/u,c=Math.ceil(p)*2+2,f=Math.ceil(h)*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(${d});
|
|
const float widthScale = float(${u});
|
|
|
|
const float invHeightScale = float(${p});
|
|
const float invWidthScale = float(${h});
|
|
|
|
const int winHeight = int(${c});
|
|
const int winWidth = int(${f});
|
|
|
|
// Compute bounds for where in dy we will look
|
|
float startRLerp = floor(float(r) * invHeightScale);
|
|
int startDyR = int(floor(startRLerp - float(winHeight / 2)));
|
|
|
|
float startCLerp = floor(float(c) * invWidthScale);
|
|
int startDyC = int(floor(startCLerp - float(winWidth / 2)));
|
|
|
|
// Loop over dy
|
|
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
|
|
int dyR = dyROffset + startDyR;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyR < 0 || dyR >= ${s}) {
|
|
continue;
|
|
}
|
|
|
|
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
|
|
int dyC = dyCOffset + startDyC;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyC < 0 || dyC >= ${i}) {
|
|
continue;
|
|
}
|
|
|
|
float sourceFracRow =
|
|
float(${o[0]}) *
|
|
(float(dyR) / float(${l[0]}));
|
|
|
|
float sourceFracCol =
|
|
float(${o[1]}) *
|
|
(float(dyC) / float(${l[1]}));
|
|
|
|
int sourceNearestRow = int(min(
|
|
float(int(${a}) - 1),
|
|
${r} ? float(round(sourceFracRow)) :
|
|
float(floor(sourceFracRow))));
|
|
|
|
int sourceNearestCol = int(min(
|
|
float(int(${n}) - 1),
|
|
${r} ? float(round(sourceFracCol)) :
|
|
float(floor(sourceFracCol))));
|
|
|
|
if (r == sourceNearestRow && c == sourceNearestCol) {
|
|
accumulator += getDy(b, dyR, dyC, d);
|
|
}
|
|
}
|
|
}
|
|
// End loop over dy
|
|
|
|
setOutput(accumulator);
|
|
}
|
|
`}};function foe(e){let{inputs:t,backend:r,attrs:a}=e,{images:n,dy:s}=t,{alignCorners:i}=a,o=new coe(s.shape,n.shape,i);return r.runWebGLProgram(o,[s],s.dtype)}var moe={kernelName:Hf,backendName:"webgl",kernelFunc:foe},goe=class{constructor(e,t){this.variableNames=["x"];let r=e.length;if(r>4)throw new Error(`WebGL backend: Reverse of rank-${r} tensor is not yet supported`);if(this.outputShape=e,r===1){this.userCode=`
|
|
void main() {
|
|
int coord = getOutputCoords();
|
|
setOutput(getX(${e[0]} - coord - 1));
|
|
}
|
|
`;return}let a=i=>t.indexOf(i)!==-1&&e[i]!==1?`${e[i]} - coords[${i}] - 1`:`coords[${i}]`,n=e.map((i,o)=>a(o)).join(","),s=vt(r);this.userCode=`
|
|
void main() {
|
|
${s} coords = getOutputCoords();
|
|
setOutput(getX(${n}));
|
|
}
|
|
`}},yoe=class{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;let r=e.length;if(r>4)throw new Error(`WebGL backend: Reverse of rank-${r} tensor is not yet supported`);this.outputShape=e;let a=$r("rc",r),n=`${a[r-1]} + 1 < ${this.outputShape[r-1]}`,s=`${a[r-2]} + 1 < ${this.outputShape[r-2]}`,i=vt(r);r===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(${n}){
|
|
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(a.slice())};
|
|
if(${n}){
|
|
result.g = ${l(a.slice())};
|
|
}
|
|
if(${s}) {
|
|
result.b = ${d(a.slice())};
|
|
if(${n}) {
|
|
result.a = ${u(a.slice())};
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`;function o(c){return p(c)}function l(c){return c[r-1]="("+c[r-1]+" + 1)",p(c)}function d(c){return c[r-2]="("+c[r-2]+" + 1)",p(c)}function u(c){return c[r-1]="("+c[r-1]+" + 1)",c[r-2]="("+c[r-2]+" + 1)",p(c)}function p(c){let f=e.map((y,A)=>h(A,c)),m=f.join(","),g=f.slice(-2).join(",");return`getChannel(getX(${m}), vec2(${g}))`}function h(c,f){return t.indexOf(c)!==-1&&e[c]!==1?`${e[c]} - ${f[c]} - 1`:`${f[c]}`}}};function Aoe(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{dims:s}=a,i=n.shape.length,o=w.parseAxisParam(s,n.shape);if(i===0)return ha({inputs:{x:n},backend:r});let l=Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new yoe(n.shape,o):new goe(n.shape,o);return r.runWebGLProgram(l,[n],n.dtype)}var xoe={kernelName:rl,backendName:"webgl",kernelFunc:Aoe},boe=class{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];let r=e[1],a=e[2];this.outputShape=e;let n="";typeof t=="number"?n=`float outputValue = ${t.toFixed(2)};`:n=`
|
|
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]));
|
|
${n}
|
|
if(coordX >= 0 && coordX < ${a} && coordY >= 0 && coordY < ${r}) {
|
|
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
|
|
}
|
|
setOutput(outputValue);
|
|
}
|
|
`}},voe={kernelName:gl,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{image:a}=e,{radians:n,fillValue:s,center:i}=t,o=r,l=new boe(a.shape,s),[d,u]=N.getImageCenter(i,a.shape[1],a.shape[2]),p=[[d,u,Math.sin(n),Math.cos(n)]];return o.runWebGLProgram(l,[a],a.dtype,p)}},woe=`
|
|
// 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;
|
|
}
|
|
}
|
|
`,koe=it({opSnippet:woe}),Ioe={kernelName:al,backendName:"webgl",kernelFunc:koe},Soe="return inversesqrt(x);",Toe=it({opSnippet:Soe,cpuKernelImpl:YQ}),Coe={kernelName:Ti,backendName:"webgl",kernelFunc:Toe},R8=class{constructor(e,t,r,a,n,s,i=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=s;let o=vt(n.length),l=vt(s.length),d="";r===1?d="i":r===2&&(d="i, j");let u=`getIndices(${d})`,p="";a===1?p="i":a===2&&(p="i, coords[1]");let h=`getUpdates(${p})`,c=t>1?"strides[j]":"strides";this.userCode=`
|
|
${o} strides = ${o}(${n});
|
|
|
|
void main() {
|
|
${l} coords = getOutputCoords();
|
|
float sum = 0.0;
|
|
bool found = false;
|
|
for (int i = 0; i < ${e}; i++) {
|
|
int flattenedIndex = 0;
|
|
for (int j = 0; j < ${t}; j++) {
|
|
int index = round(${u});
|
|
flattenedIndex += index * ${c};
|
|
}
|
|
if (flattenedIndex == coords[0]) {
|
|
sum += ${h};
|
|
found = true;
|
|
}
|
|
}
|
|
setOutput(mix(getDefaultValue(), sum, float(found)));
|
|
}
|
|
`}};function Noe(e){let{inputs:t,backend:r,attrs:a}=e,{indices:n,updates:s}=t,{shape:i}=a,{sliceRank:o,numUpdates:l,sliceSize:d,strides:u,outputSize:p}=N.calculateShapes(s,n,i),h=[p/d,d];if(p===0)return r.makeTensorInfo(i,n.dtype);let c=ve({inputs:{x:n},backend:r,attrs:{shape:[l,o]}}),f=ve({inputs:{x:s},backend:r,attrs:{shape:[l,d]}}),m=r.makeTensorInfo([],"float32",new Float32Array([0])),g=new R8(l,o,c.shape.length,f.shape.length,u,h),y=r.runWebGLProgram(g,[f,c,m],f.dtype),A=ve({inputs:{x:y},backend:r,attrs:{shape:i}});return r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(f),r.disposeIntermediateTensorInfo(y),r.disposeIntermediateTensorInfo(m),A}var Eoe={kernelName:nl,backendName:"webgl",kernelFunc:Noe},Roe=class{constructor(e,t,r){this.variableNames=["c","a","b"],this.outputShape=t;let a,n;if(r>4)throw Error(`Where for rank ${r} is not yet supported`);if(r===1)n="resRC",a="resRC";else{let i=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],l=[];for(let d=0;d<t.length;d++)l.push(`${i[d]}`),d<e&&o.push(`${i[d]}`);a=o.join(),n=l.join()}let s=vt(r);this.userCode=`
|
|
void main() {
|
|
${s} resRC = getOutputCoords();
|
|
float cVal = getC(${a});
|
|
if (cVal >= 1.0) {
|
|
setOutput(getA(${n}));
|
|
} else {
|
|
setOutput(getB(${n}));
|
|
}
|
|
}
|
|
`}};function Foe(e){let{inputs:t,backend:r}=e,{condition:a,t:n,e:s}=t,i=new Roe(a.shape.length,n.shape,n.shape.length);return r.runWebGLProgram(i,[a,n,s],Or(n.dtype,s.dtype))}var Moe={kernelName:sl,backendName:"webgl",kernelFunc:Foe},$oe=`
|
|
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
|
|
// see: https://arxiv.org/abs/1706.02515
|
|
float scaleAlpha = ${N.SELU_SCALEALPHA};
|
|
float scale = ${N.SELU_SCALE};
|
|
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
|
|
`,Poe=it({opSnippet:$oe}),Ooe={kernelName:Ku,backendName:"webgl",kernelFunc:Poe},zoe=yd+`
|
|
return 1.0 / (1.0 + exp(-1.0 * x));
|
|
`,Doe=`
|
|
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;
|
|
`,_oe=it({opSnippet:zoe,packedOpSnippet:Doe,cpuKernelImpl:JQ}),Loe={kernelName:Ni,backendName:"webgl",kernelFunc:_oe},Boe=`
|
|
if (isnan(x)) { return 0.0; }
|
|
return sign(x);
|
|
`,Woe=it({opSnippet:Boe}),Voe={kernelName:Xu,backendName:"webgl",kernelFunc:Woe},Uoe=yd+`
|
|
return sin(x);
|
|
`,Goe=it({opSnippet:Uoe}),joe={kernelName:Ci,backendName:"webgl",kernelFunc:Goe},Hoe=`
|
|
float e2x = exp(x);
|
|
return (e2x - 1.0 / e2x) / 2.0;
|
|
`,qoe=it({opSnippet:Hoe}),Koe={kernelName:ol,backendName:"webgl",kernelFunc:qoe},Xoe=`
|
|
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;
|
|
`,Zoe=it({opSnippet:Xoe}),Yoe={kernelName:Zu,backendName:"webgl",kernelFunc:Zoe},Joe=e=>{let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{blockShape:s,paddings:i}=a;w.assert(n.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let o=s.reduce((y,A)=>y*A),l=[[0,0]];l.push(...i);for(let y=1+s.length;y<n.shape.length;++y)l.push([0,0]);let d=[],u=N8({inputs:{x:n},backend:r,attrs:{paddings:l,constantValue:0}}),p=N.getReshaped(u.shape,s,o,!1),h=N.getPermuted(p.length,s.length,!1),c=N.getReshapedPermuted(u.shape,s,o,!1),f=ve({inputs:{x:u},backend:r,attrs:{shape:p}}),m=Dr({inputs:{x:f},backend:r,attrs:{perm:h}}),g=ve({inputs:{x:m},backend:r,attrs:{shape:c}});return d.push(u),d.push(f),d.push(m),d.forEach(y=>r.disposeIntermediateTensorInfo(y)),g},Qoe={kernelName:ll,backendName:"webgl",kernelFunc:Joe};function ele(e){let{inputs:t,backend:r}=e,{indices:a,values:n,denseShape:s,defaultValue:i}=t;if(s.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
|
|
${s.shape}`);if(a.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
|
|
${a.shape}`);if(n.shape.length!==1)throw new Error(`Values must be a vector, saw:
|
|
${n.shape}`);if(i.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
|
|
${i.shape}`);let o=r.readSync(a.dataId),l=r.readSync(n.dataId),d=r.readSync(s.dataId),u=r.readSync(i.dataId)[0],[p,h,c,f,m]=eee(o,a.shape,a.dtype,l,n.dtype,d,u);return[r.makeTensorInfo(h,a.dtype,p),r.makeTensorInfo([h[0]],n.dtype,c),r.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),r.makeTensorInfo([m.length],a.dtype,new Int32Array(m))]}var tle={kernelName:Xp,backendName:"webgl",kernelFunc:ele};function rle(e){let{inputs:t,backend:r}=e,{inputIndices:a,inputShape:n,newShape:s}=t;if(a.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape ${a.shape}`);if(n.shape.length!==1)throw new Error(`Input shape should be a vector but received shape ${n.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=Array.from(r.readSync(n.dataId)),o=r.readSync(a.dataId),l=Array.from(r.readSync(s.dataId)),[d,u,p]=tee(o,a.shape,a.dtype,i,l);return[r.makeTensorInfo(u,a.dtype,d),r.makeTensorInfo([p.length],s.dtype,new Int32Array(p))]}var ale={kernelName:Yu,backendName:"webgl",kernelFunc:rle};function nle(e){let{inputs:t,backend:r}=e,{data:a,indices:n,segmentIds:s}=t;if(a.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(n.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${n.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${s.shape}`);let i=r.readSync(a.dataId),o=r.readSync(n.dataId),l=r.readSync(s.dataId),[d,u]=JI(i,a.shape,a.dtype,o,l,!0);return r.makeTensorInfo(u,a.dtype,d)}var sle={kernelName:Zp,backendName:"webgl",kernelFunc:nle};function ile(e){let{inputs:t,backend:r}=e,{data:a,indices:n,segmentIds:s}=t;if(a.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(n.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${n.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${s.shape}`);let i=r.readSync(a.dataId),o=r.readSync(n.dataId),l=r.readSync(s.dataId),[d,u]=JI(i,a.shape,a.dtype,o,l);return r.makeTensorInfo(u,a.dtype,d)}var ole={kernelName:Yp,backendName:"webgl",kernelFunc:ile};function lle(e){let{inputs:t,backend:r,attrs:a}=e,{sparseIndices:n,sparseValues:s,defaultValue:i}=t,{outputShape:o}=a,{sliceRank:l,numUpdates:d,strides:u,outputSize:p}=N.calculateShapes(s,n,o),h=!1,c=new R8(d,l,n.shape.length,s.shape.length,u,[p,1],h),f=r.runWebGLProgram(c,[s,n,i],s.dtype),m=ve({inputs:{x:f},backend:r,attrs:{shape:o}});return r.disposeIntermediateTensorInfo(f),m}var ule={kernelName:Jp,backendName:"webgl",kernelFunc:lle};function dle(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{numOrSizeSplits:s,axis:i}=a,o=w.parseAxisParam(i,n.shape)[0],l=N.prepareSplitSize(n,s,o),d=n.shape.length,u=new Array(d).fill(0),p=n.shape.slice();return l.map(h=>{let c=[...p];c[o]=h;let f=Ad({inputs:{x:n},backend:r,attrs:{begin:u,size:c}});return u[o]+=h,f})}var ple={kernelName:ul,backendName:"webgl",kernelFunc:dle},lv="return sqrt(x);",hle=it({opSnippet:lv,packedOpSnippet:lv,cpuKernelImpl:ree}),cle={kernelName:Ei,backendName:"webgl",kernelFunc:hle},fle="return x * x;",mle=it({opSnippet:fle}),gle={kernelName:Ju,backendName:"webgl",kernelFunc:mle},uv="return (a - b) * (a - b);",yle=Ar({opSnippet:uv,packedOpSnippet:uv}),Ale={kernelName:Mi,backendName:"webgl",kernelFunc:yle};function xle({inputs:e,attrs:t,backend:r}){let{x:a}=e,n=Ka+`
|
|
return x > 0.0 ? 1.0 : float(${t.alpha});
|
|
`,s=new Gn(a.shape,n);return r.runWebGLProgram(s,[a],a.dtype)}var ble={kernelName:zi,backendName:"webgl",kernelFunc:xle},vle=class{constructor(e,t,r){this.variableNames=["x"],this.outputShape=r;let a=r.length,n=vt(r.length),s=vt(r.length),i="";if(a===1)i="coords * strides + begin";else{let o=0;i=r.map((l,d)=>(o++,r.length===1?`coords * strides[${d}] + begin[${d}]`:`coords[${o-1}] * strides[${d}] + begin[${d}]`)).join(",")}this.userCode=`
|
|
${n} begin = ${n}(${e});
|
|
${n} strides = ${n}(${t});
|
|
|
|
void main() {
|
|
${s} coords = getOutputCoords();
|
|
setOutput(getX(${i}));
|
|
}
|
|
`}};function wle(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:d,ellipsisMask:u,newAxisMask:p,shrinkAxisMask:h}=a,{finalShapeSparse:c,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:A,end:x,strides:b}=Ot.sliceInfo(n.shape,s,i,o,l,d,u,p,h),v;if(m)v=ve({inputs:{x:n},backend:r,attrs:{shape:f}});else if(g||y){w.assert(n.shape.length>=1,()=>`Input must have rank at least 1, got: ${n.shape.length}`);let T=Ot.computeOutShape(A,x,b),E=Ad({inputs:{x:n},backend:r,attrs:{begin:A,size:T}});v=ve({inputs:{x:E},backend:r,attrs:{shape:f}}),r.disposeIntermediateTensorInfo(E)}else if(r.shouldExecuteOnCPU([n])){let T=r.readSync(n.dataId),E=Le(n.shape,n.dtype,T),R=aee(c,E,b,A);v=r.makeTensorInfo(f,n.dtype,R.values)}else{let T=new vle(A,b,c);v=r.runWebGLProgram(T,[n],n.dtype)}let C=ve({inputs:{x:v},backend:r,attrs:{shape:f}});return r.disposeIntermediateTensorInfo(v),C}var kle={kernelName:dl,backendName:"webgl",kernelFunc:wle};function Ile(e){let{inputs:t,backend:r,attrs:a}=e,{separator:n,nGramWidths:s,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:d}=a,{data:u,dataSplits:p}=t,h=r.readSync(u.dataId),c=r.readSync(p.dataId),[f,m]=nee(h,c,n,s,i,o,l,d);return[r.makeTensorInfo([f.length],"string",f),r.makeTensorInfo(p.shape,"int32",m)]}var Sle={kernelName:Qp,backendName:"webgl",kernelFunc:Ile};function Tle(e){let{inputs:t,backend:r,attrs:a}=e,{skipEmpty:n}=a,{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=r.readSync(s.dataId),l=r.readSync(i.dataId)[0],[d,u,p]=see(o,l,n),h=u.length;return[r.makeTensorInfo([h,2],"int32",d),r.makeTensorInfo([h],"string",u),r.makeTensorInfo([2],"int32",new Int32Array(p))]}var Cle={kernelName:Kf,backendName:"webgl",kernelFunc:Tle};function Nle(e){let{inputs:t,backend:r,attrs:a}=e,{numBuckets:n}=a,{input:s}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(n<=0)throw new Error("Number of buckets must be at least 1");let i=r.readSync(s.dataId),o=iee(i,n);return r.makeTensorInfo(s.shape,"int32",o)}var Ele={kernelName:Xf,backendName:"webgl",kernelFunc:Nle},Rle="return tan(x);",Fle=it({opSnippet:Rle}),Mle={kernelName:pl,backendName:"webgl",kernelFunc:Fle},$le=`
|
|
float e2x = exp(-2.0 * abs(x));
|
|
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
|
|
`,Ple=it({opSnippet:$le}),Ole={kernelName:Pi,backendName:"webgl",kernelFunc:Ple},zle=class{constructor(e,t){this.variableNames=["A"];let r=new Array(e.length);for(let s=0;s<r.length;s++)r[s]=e[s]*t[s];this.outputShape=r,this.rank=r.length;let a=vt(this.rank),n=Dle(e);this.userCode=`
|
|
void main() {
|
|
${a} resRC = getOutputCoords();
|
|
setOutput(getA(${n}));
|
|
}
|
|
`}};function Dle(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 r=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],a=[];for(let n=0;n<e.length;n++)a.push(`imod(${r[n]}, ${e[n]})`);return a.join()}function F8(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{reps:s}=a;if(n.dtype==="string"||n.shape.length>5){let o=r.readSync(n.dataId),l=n.dtype==="string"?o.map(p=>w.decodeString(p)):o,d=Le(n.shape,n.dtype,l),u=lee(d,s);return r.makeTensorInfo(u.shape,u.dtype,u.values)}let i=new zle(n.shape,s);return r.runWebGLProgram(i,[n],n.dtype)}var _le={kernelName:Xn,backendName:"webgl",kernelFunc:F8},Lle=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));
|
|
}
|
|
}
|
|
`}},Ble=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 ao(e,t){t!==null&&e.disposeIntermediateTensorInfo(t)}function dv(e){let t=1;for(;t<e;)t*=2;return t}function Wle(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{k:s,sorted:i}=a,o=Y().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),l=Y().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),d=n.shape,u=d[d.length-1];if(r.shouldExecuteOnCPU([n])||u<o||s>l){let R=r.readSync(n.dataId),[z,M]=uee(R,d,n.dtype,s,i);return[r.makeTensorInfo(z.shape,z.dtype,z.values),r.makeTensorInfo(M.shape,M.dtype,M.values)]}if(s===0)return d[d.length-1]=0,[r.makeTensorInfo(d,n.dtype,[]),r.makeTensorInfo(d,"int32",[])];if(u===1)return[n,Fh({attrs:{shape:d,dtype:"int32",value:0},backend:r})];let p=r.texData.get(n.dataId),h=p!==null&&p.isPacked,c=h?r.unpackTensor(n):n,f=w.sizeFromShape(d)/u,m=ve({inputs:{x:c},attrs:{shape:[f,u]},backend:r});h&&ao(r,c);let g=dv(s),y=dv(u),A=null,x=()=>A===null?[m,m]:[m,A],b=(R,z,M)=>{let I=x(),D=new Lle(M),O=[[u],[A===null?1:0],[Number.NEGATIVE_INFINITY],[R],[z]],j=A;A=r.runWebGLProgram(D,I,"int32",O),ao(r,j)};for(let R=1;R<g;R*=2){let z=R*2;for(let M=R;M>=1;M/=2)b(z,M,[f,y])}for(let R=y;R>g;R/=2){let z=x(),M=new Ble([f,R/2]),I=[[u],[A===null?1:0],[g]],D=A;A=r.runWebGLProgram(M,z,"int32",I),ao(r,D);let O=g/2,j=O*2;for(let X=O;X>=1;X/=2)b(j,X,A.shape)}let v=A;A=Ad({inputs:{x:A},backend:r,attrs:{begin:0,size:[f,s]}}),ao(r,v);let C=w8({inputs:{x:m,indices:A},backend:r,attrs:{axis:1,batchDims:1}});ao(r,m);let T=d.slice(0,-1);T.push(s),v=A,A=ve({inputs:{x:A},attrs:{shape:T},backend:r}),ao(r,v);let E=C;return C=ve({inputs:{x:C},attrs:{shape:T},backend:r}),ao(r,E),[C,A]}var Vle={kernelName:hl,backendName:"webgl",kernelFunc:Wle},Ule=class{constructor(e,t,r,a,n,s){this.variableNames=["Image","Transforms"],this.outputShape=s;let i=r==="nearest"?1:2,o;switch(a){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(${n});
|
|
}
|
|
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(${n});
|
|
} 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 Gle(e){let{inputs:t,backend:r,attrs:a}=e,{image:n,transforms:s}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:d}=a,[u,p,h,c]=n.shape,[f,m]=d!=null?d:[p,h],g=[u,f,m,c],y=new Ule(p,h,i,o,l,g);return r.runWebGLProgram(y,[n,s],"float32")}var jle={kernelName:cl,backendName:"webgl",kernelFunc:Gle};function Hle(e){let{inputs:t,attrs:r,backend:a}=e,{axis:n}=r,{x:s}=t;hd(s,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let i=a.readSync(s.dataId),{outputValues:o,outputShape:l,indices:d}=dee(i,n,s.shape,s.dtype);return[a.makeTensorInfo(l,s.dtype,o),a.makeTensorInfo([d.length],"int32",d)]}var qle={kernelName:Zf,backendName:"webgl",kernelFunc:Hle};function Kle(e){let{inputs:t,backend:r,attrs:a}=e,{value:n}=t,{axis:s}=a;s<0&&(s+=n.shape.length);let i=n,o=i.shape.length,l=n.shape[s],d=new Array(o-1),u=0;for(let m=0;m<o;m++)m!==s&&(d[u++]=i.shape[m]);let p=[],h=new Array(o).fill(0),c=i.shape.slice();c[s]=1;let f=new Array(l);for(let m=0;m<f.length;m++){h[s]=m;let g=Ad({inputs:{x:i},backend:r,attrs:{begin:h,size:c}}),y=ve({inputs:{x:g},backend:r,attrs:{shape:d}});f[m]=y,p.push(g)}return p.forEach(m=>r.disposeIntermediateTensorInfo(m)),f}var Xle={kernelName:fl,backendName:"webgl",kernelFunc:Kle},Zle=class{constructor(e,t){this.variableNames=["x","segmentIds"];let r=e.windowSize,a=e.batchSize,n=e.inSize,s=e.numSegments,i=s*Math.ceil(n/r);this.outputShape=[a,i];let o="0.0",l="sumValue",d=Math.floor(r/4)*4,u=r%4,p=`
|
|
sumValue += dot(values, segFilter);
|
|
`,h="";n%r>0&&(h=`
|
|
if (inIdx < 0 || inIdx >= ${n}) {
|
|
return initializationValue;
|
|
}
|
|
`);let c="";n%r>0&&(c=`
|
|
if (inIdx < 0 || inIdx >= ${n}) {
|
|
return -1.0;
|
|
}
|
|
`),this.userCode=`
|
|
const float initializationValue = ${o};
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
${h}
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
float getSegmentIdAtIndex(int inIdx) {
|
|
${c}
|
|
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(${r}));
|
|
int currentSeg = int(mod(float(outIdx), float(${s})));
|
|
|
|
float sumValue = 0.0;
|
|
|
|
for (int i = 0; i < ${d}; i += 4) {
|
|
int inIdx = inOffset + i;
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
|
|
);
|
|
|
|
${p}
|
|
}
|
|
|
|
int inIdx = inOffset + ${d};
|
|
if (${u===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
int inIdxSeg = int(getSegmentIdAtIndex(inIdx));
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
0,
|
|
0,
|
|
0
|
|
);
|
|
|
|
${p}
|
|
} else if (${u===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
|
|
0,
|
|
0
|
|
);
|
|
|
|
${p}
|
|
} else if (${u===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
initializationValue
|
|
);
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
|
|
0
|
|
);
|
|
|
|
${p}
|
|
}
|
|
setOutput(${l});
|
|
}
|
|
`}};function Yle(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,segmentIds:s}=t,{numSegments:i}=a,o=n.shape.length,l=[],d=0,u=N.getAxesPermutation([d],o),p=n;u!=null&&(p=Dr({inputs:{x:n},backend:r,attrs:{perm:u}}),l.push(p),d=N.getInnerMostAxes(1,o)[0]);let h=N.segment_util.computeOutShape(p.shape,d,i),c=w.sizeFromShape([p.shape[d]]),f=ve({inputs:{x:p},backend:r,attrs:{shape:[-1,c]}});l.push(f);let m=ah(n.dtype),g=(b,v,C,T,E)=>{let R=b.shape[0],z=b.shape[1],M=N.segment_util.segOpComputeOptimalWindowSize(z,E),I={windowSize:M,inSize:z,batchSize:R,numSegments:E},D=new Zle(I,v),O=r.compileAndRun(D,[b,C],T);if(l.push(O),O.shape[1]===E)return O;let j=E8({backend:r,attrs:{start:0,stop:E,step:1,dtype:"float32"}}),X=F8({inputs:{x:j},backend:r,attrs:{reps:[z/M]}});return l.push(j),l.push(X),g(O,v,X,T,E)},y=g(f,"unsortedSegmentSum",s,m,i),A=ve({inputs:{x:y},backend:r,attrs:{shape:h}}),x=A;if(u!=null){l.push(A);let b=N.getUndoAxesPermutation(u);x=Dr({inputs:{x},backend:r,attrs:{perm:b}})}return l.forEach(b=>r.disposeIntermediateTensorInfo(b)),x}var Jle={kernelName:eh,backendName:"webgl",kernelFunc:Yle},Qle=[ste,ote,dte,cte,mte,Ate,bte,wte,Tte,Nte,Fte,Pte,Dte,Wte,Gte,Hte,Kte,Jte,ere,rre,ire,cre,mre,yre,kre,Sre,Ere,Bee,Mre,Dre,Wre,qre,Xre,Yre,Qre,tae,nae,oae,dae,hae,fae,yae,xae,kae,Sae,Nae,Fae,$ae,Dae,Wae,jae,Kae,Yae,Jae,ene,rne,nne,ine,lne,hne,mne,Ane,bne,kne,Tne,Rne,Pne,Lee,zne,Ore,Lne,Vne,jne,Vee,Xne,Qne,tse,sse,lse,hse,mse,xse,kse,Tse,Nse,Mse,Pse,zse,Bse,Vse,Gse,Hse,Kse,Jse,rie,iie,fie,qee,Aie,vie,Iie,Cie,xre,Rie,Mie,Pie,Die,Wie,Gee,Uie,Gie,bre,die,qie,Yie,toe,Xee,soe,loe,hoe,moe,xoe,voe,Ioe,Coe,Eoe,Moe,Ooe,Loe,Voe,joe,Koe,pre,hie,Yoe,Qoe,tle,ale,sle,ole,ule,ple,cle,gle,Ale,ble,kle,Sle,Cle,Ele,pie,rte,Mle,Ole,_le,Vle,jle,ate,qle,Xle,Jle,Fie];for(let e of Qle)Ga(e);var Mn=Y();Mn.registerFlag("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE",()=>15);Mn.registerFlag("WEBGPU_CPU_FORWARD",()=>!0);Mn.registerFlag("WEBGPU_MATMUL_WORK_PER_THREAD",()=>4);Mn.registerFlag("WEBGPU_USE_NAIVE_CONV2D",()=>!1);Mn.registerFlag("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE",()=>!1);Mn.registerFlag("WEBGPU_CONV_SEPARATE_IM2COL_SHADER",()=>!1);Mn.registerFlag("WEBGPU_USE_LOW_POWER_GPU",()=>!1);Mn.registerFlag("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e3);Mn.registerFlag("WEBGPU_USE_PROFILE_TOOL",()=>!1);Mn.registerFlag("WEBGPU_USE_IMPORT",()=>!1);function eue(e,t){if(Math.max(...e)>3)throw new Error("Cannot symbolically compute strides for rank > 4 tensor.");let r=e.length,a=e.map(s=>`${t}[${s}]`),n=new Array(r-1);n[r-2]=a[r-1];for(let s=r-3;s>=0;--s)n[s]=`(${n[s+1]} * ${a[s+1]})`;return n}function cr(e){if(e<=1)return"i32";if(e===2)return"vec2<i32>";if(e===3)return"vec3<i32>";if(e===4)return"vec4<i32>";throw Error(`GPU for rank ${e} is not yet supported`)}function jc(e,t){return e==="float32"?t?"vec4<f32>":"f32":e==="int32"||e==="bool"?t?"vec4<i32>":"i32":e}function Lx(){return`
|
|
@stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)
|
|
`}function Wi(){return`
|
|
${Lx()}
|
|
fn main(@builtin(local_invocation_id) LocalId : vec3<u32>,
|
|
@builtin(global_invocation_id) GlobalId : vec3<u32>,
|
|
@builtin(num_workgroups) NumWorkgroups: vec3<u32>) {
|
|
localId = LocalId;
|
|
globalId = GlobalId;
|
|
numWorkgroups = NumWorkgroups;
|
|
`}function Je(){return`
|
|
${Wi()}
|
|
let index = getGlobalIndex();
|
|
`}function tue(e,t,r,a=!1){let n=[];if(n.push(`
|
|
let workGroupSizeX = ${r.workGroupSize[0]}u;
|
|
let workGroupSizeY = ${r.workGroupSize[1]}u;
|
|
let workGroupSizeZ = ${r.workGroupSize[2]}u;
|
|
|
|
var<private> localId: vec3<u32>;
|
|
var<private> globalId: vec3<u32>;
|
|
var<private> numWorkgroups: vec3<u32>;
|
|
|
|
// Only used when the y/z dimension of workgroup size is 1.
|
|
fn getGlobalIndex() -> i32 {
|
|
if (numWorkgroups.y == 1u && numWorkgroups.z == 1u) {
|
|
return i32(globalId.x);
|
|
}
|
|
|
|
let localInvocationIndex = localId.z * workGroupSizeX * workGroupSizeY +
|
|
localId.y * workGroupSizeX + localId.x;
|
|
let workGroupID = (globalId - localId)/vec3<u32>(
|
|
workGroupSizeX, workGroupSizeY, workGroupSizeZ);
|
|
|
|
return i32((workGroupID.z * numWorkgroups.x * numWorkgroups.y +
|
|
workGroupID.y * numWorkgroups.x + workGroupID.x) *
|
|
(workGroupSizeX * workGroupSizeY * workGroupSizeZ) +
|
|
localInvocationIndex);
|
|
}
|
|
`),a===!0)return n.push(`
|
|
struct Matrix0 {
|
|
numbers: array<${jc(t.dtype,r.isVec4)}>;
|
|
};
|
|
struct Uniform {
|
|
size : i32;
|
|
numChannels : i32;
|
|
outShapeStrides : vec2<i32>;
|
|
dispatchSize : vec3<u32>;
|
|
};
|
|
|
|
@group(0) @binding(0) var<storage, write> result : Matrix0;
|
|
@group(0) @binding(2) var<uniform> uniforms: Uniform;
|
|
`),[pv,n.join(`
|
|
`),hv(t.shape),r.getUserCode()].join(`
|
|
`);let s="struct Uniforms { NAN : f32; ";r.variableNames.forEach((u,p)=>{s+=`${u.charAt(0).toLowerCase()+u.slice(1)}Shape : ${cr(e[p].shape.length)}; `}),s+=`outShape : ${cr(t.shape.length)} ; `;let i=t.shape.length-1;s+=`
|
|
outShapeStrides: ${cr(i)}; `,r.size&&(s+="size : i32; "),r.uniforms&&(s+=r.uniforms),s+="};",n.push(s),r.atomic?n.push(`
|
|
struct Matrix0 {
|
|
numbers: array<atomic<i32>>;
|
|
};
|
|
|
|
@group(0) @binding(0) var<storage, read_write> result : Matrix0;
|
|
`):n.push(`
|
|
struct Matrix0 {
|
|
numbers: array<${jc(t.dtype,r.isVec4)}>;
|
|
};
|
|
|
|
@group(0) @binding(0) var<storage, write> result : Matrix0;
|
|
`),r.variableNames.forEach((u,p)=>{n.push(`
|
|
struct Matrix${1+p} {
|
|
numbers: array<${jc(e[p].dtype,r.isVec4)}>;
|
|
};
|
|
@group(0) @binding(${1+p}) var<storage, read> ${u} : Matrix${1+p};
|
|
`)}),s!==""&&n.push(`
|
|
@group(0) @binding(${1+r.variableNames.length}) var<uniform> uniforms : Uniforms;
|
|
`);let[o,l]=oue(t.shape,r.dispatchLayout),d=[pv,n.join(`
|
|
`),hv(t.shape),o,rue(t.shape.length)];if(r.atomic||d.push(aue(t.shape,t.dtype,r.isVec4)),l===t.shape.length){let u=e.map(p=>nue(p,t.shape,r.isVec4,r.dispatchLayout.x.length===t.shape.length)).join(`
|
|
`);d.push(u)}return d.push(r.getUserCode()),d.join(`
|
|
`)}var pv=`
|
|
// 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 idiv(a: i32, b: i32, sign: f32) -> i32 {
|
|
var res: i32 = a / b;
|
|
let mod: i32 = a % b;
|
|
if (sign < 0. && mod != 0) {
|
|
res = res - 1;
|
|
}
|
|
return res;
|
|
}
|
|
|
|
fn isNanCustom(val : f32) -> bool {
|
|
if (val > 0.0) {
|
|
return false;
|
|
}
|
|
if (val < 0.0) {
|
|
return false;
|
|
}
|
|
if (val == 0.0) {
|
|
return false;
|
|
}
|
|
return true;
|
|
}
|
|
fn isNanCustomVec4(val : vec4<f32>) -> vec4<bool> {
|
|
return vec4<bool>(isNanCustom(val[0]), isNanCustom(val[1]), isNanCustom(val[2]), isNanCustom(val[3]));
|
|
}
|
|
`;function rue(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;default:w.assert(!1,()=>`Unsupported ${e}D shape`);break}return t}function aue(e,t,r){let a=e.length,n=jc(t,r),s;if(r?s=`fn setOutputAtIndex(flatIndex : i32, value : vec4<f32>) {
|
|
result.numbers[flatIndex] = ${n}(value);
|
|
}
|
|
fn setOutputAtIndexI32(flatIndex : i32, value : vec4<i32>) {
|
|
result.numbers[flatIndex] = ${n}(value);
|
|
}`:s=`fn setOutputAtIndex(flatIndex : i32, value : f32) {
|
|
result.numbers[flatIndex] = ${n}(value);
|
|
}
|
|
fn setOutputAtIndexI32(flatIndex : i32, value : i32) {
|
|
result.numbers[flatIndex] = ${n}(value);
|
|
}`,a>=2){let i=["d0","d1","d2","d3"].slice(0,a),o=cr(a);r?s+=`
|
|
fn setOutputAtCoords(${i.map(l=>`${l} : i32`).join(", ")}, value : vec4<f32>) {
|
|
let flatIndex = getOutputIndexFromCoords(${o}(${i.join(", ")}));
|
|
setOutputAtIndex(flatIndex / 4, value);
|
|
}
|
|
fn setOutputAtCoordsI32(${i.map(l=>`${l} : i32`).join(", ")}, value : vec4<i32>) {
|
|
let flatIndex = getOutputIndexFromCoords(${o}(${i.join(", ")}));
|
|
setOutputAtIndexI32(flatIndex / 4, value);
|
|
}
|
|
`:s+=`
|
|
fn setOutputAtCoords(${i.map(l=>`${l} : i32`).join(", ")}, value : f32) {
|
|
let flatIndex = getOutputIndexFromCoords(${o}(${i.join(", ")}));
|
|
setOutputAtIndex(flatIndex, value);
|
|
}
|
|
fn setOutputAtCoordsI32(${i.map(l=>`${l} : i32`).join(", ")}, value : i32) {
|
|
let flatIndex = getOutputIndexFromCoords(${o}(${i.join(", ")}));
|
|
setOutputAtIndexI32(flatIndex, value);
|
|
}
|
|
`}return s}function nue(e,t,r,a){let n=sue(e,r);return e.shape.length<=t.length&&(n+=iue(e,t,r,a)),n}function sue(e,t){let r=e.name,a=e.shape.length,n=cr(a),s="get"+r.charAt(0).toUpperCase()+r.slice(1),i=["d0","d1","d2","d3"].slice(0,a),o=i.map(u=>`${u} : i32`).join(", ");if(a<1)return t?`
|
|
fn ${s}() -> vec4<f32> {
|
|
return vec4<f32>(${r}.numbers[0]);
|
|
}
|
|
`:`
|
|
fn ${s}() ->f32 {
|
|
return f32(${r}.numbers[0]);
|
|
}
|
|
`;let l=`uniforms.${r.charAt(0).toLowerCase()+r.slice(1)}Shape`,d=`${a}D`;return a===0&&(d="1D"),t?`
|
|
fn ${s}(${o}) -> vec4<f32> {
|
|
return vec4<f32>(${r}.numbers[getIndexFromCoords${d}(${n}(${i.join(",")}),
|
|
${l}) / 4]);
|
|
}
|
|
`:`
|
|
fn ${s}(${o}) -> f32 {
|
|
return f32(${r}.numbers[getIndexFromCoords${d}(${n}(${i.join(",")}),
|
|
${l})]);
|
|
}
|
|
`}function iue(e,t,r,a){let n=e.name,s=n.charAt(0).toUpperCase()+n.slice(1),i="get"+s+"ByOutput",o=e.shape.length,l=t.length,d=cr(l);if(w.arraysEqual(e.shape,t)&&a)return r?`
|
|
fn ${i}Index(globalIndex : i32) -> vec4<f32> {
|
|
return vec4<f32>(${n}.numbers[globalIndex]);
|
|
}
|
|
|
|
fn ${i}Coords(coords : ${d}) -> vec4<f32> {
|
|
return vec4<f32>(${n}.numbers[${l>1?"getOutputIndexFromCoords(coords)":"coords"} / 4]);
|
|
}
|
|
`:`
|
|
fn ${i}Index(globalIndex : i32) -> f32 {
|
|
return f32(${n}.numbers[globalIndex]);
|
|
}
|
|
|
|
fn ${i}Coords(coords : ${d}) -> f32 {
|
|
return f32(${n}.numbers[${l>1?"getOutputIndexFromCoords(coords)":"coords"}]);
|
|
}
|
|
`;let u=N.getBroadcastDims(e.shape,t),p=l-o,h="";if(o===0)return r?`
|
|
fn ${i}Index(globalIndex : i32) -> vec4<f32> {
|
|
return get${s}();
|
|
}
|
|
|
|
fn ${i}Coords(coords : ${d}) -> vec4<f32> {
|
|
return get${s}();
|
|
}
|
|
`:`
|
|
fn ${i}Index(globalIndex : i32) -> f32{
|
|
return get${s}();
|
|
}
|
|
|
|
fn ${i}Coords(coords : ${d}) -> f32{
|
|
return get${s}();
|
|
}
|
|
`;l<2&&u.length>=1?h="coords = 0;":h=u.map(g=>`coords[${g+p}] = 0;`).join(`
|
|
`);let c="";if(l<2&&o>0)c="coords";else if(l>1){let g=cr(o),y=e.shape.map((A,x)=>`coords[${x+p}]`).join(", ");c=`${g}(${y})`}else c="coords";let f=`uniforms.${n.charAt(0).toLowerCase()+n.slice(1)}Shape`,m=`${o}D`;return r?`
|
|
fn ${i}Index(globalIndex : i32) -> vec4<f32> {
|
|
var coords = getCoordsFromIndex(globalIndex);
|
|
${h}
|
|
return ${n}.numbers[getIndexFromCoords${m}(${c}, ${f}) / 4];
|
|
}
|
|
|
|
fn ${i}Coords(coordsIn : ${d}) -> vec4<f32> {
|
|
var coords = coordsIn;
|
|
${h}
|
|
return ${n}.numbers[getIndexFromCoords${m}(${c}, ${f}) / 4];
|
|
}
|
|
`:`
|
|
fn ${i}Index(globalIndex : i32) -> f32 {
|
|
var coords = getCoordsFromIndex(globalIndex);
|
|
${h}
|
|
return f32(${n}.numbers[getIndexFromCoords${m}(${c}, ${f})]);
|
|
}
|
|
|
|
fn ${i}Coords(coordsIn : ${d}) -> f32 {
|
|
var coords = coordsIn;
|
|
${h}
|
|
return f32(${n}.numbers[getIndexFromCoords${m}(${c}, ${f})]);
|
|
}
|
|
`}function oue(e,t){let{x:r,y:a=[],z:n=[]}=t,s=e.length;if(r.length===s)return[`fn getOutputCoords() -> ${cr(s)}{
|
|
let globalIndex = getGlobalIndex();
|
|
return getCoordsFromIndex(globalIndex);
|
|
}
|
|
`,s];let i="",o=[r,a,n],l=0;for(let h=0;h<o.length;h++){let c=o[h];if(c.length!==0)if(l+=c.length,c.length===1)i+=`let d${c[0]} = i32(globalId[${h}]);`;else{let f=eue(c,"uniforms.outShape");i+=`var index${h} = i32(globalId[${h}]);`;for(let m=0;m<f.length;m++)i+=`let d${c[m]} = index${h} / ${f[m]};`,m===f.length-1?i+=`let d${c[m+1]} = index${h} - d${c[m]} * ${f[m]};`:i+=`index${h} = index${h} - d${c[m]} * ${f[m]};`}}let d=[];for(let h=0;h<l;h++)d.push(`d${h}`);let u=cr(l),p=`fn getOutputCoords() -> ${u} {
|
|
${i}
|
|
`;return d.length===0?p+=`return ${u}(0); }`:p+=`return ${u}(${d.join(",")}); }`,[p,l]}function hv(e){let t=e.length;if(t<=1)return"fn getCoordsFromIndex(index : i32) -> i32 { return index; }";let r=w.computeStrides(e),a=cr(t),n=[];for(let i=0;i<t;i++)n.push(`d${i}`);if(r.length===1)return` fn getCoordsFromIndex(index : i32) -> vec2<i32> {
|
|
let d0 = index / uniforms.outShapeStrides; let d1 = index - d0 * uniforms.outShapeStrides;
|
|
return vec2<i32>(d0, d1);
|
|
}`;let s="var index2 = index;"+r.map((i,o)=>{let l=`let ${n[o]} = index2 / uniforms.outShapeStrides[${o}]`,d=o===r.length-1?`let ${n[o+1]} = index2 - ${n[o]} * uniforms.outShapeStrides[${o}]`:`index2 = index2 - ${n[o]} * uniforms.outShapeStrides[${o}]`;return`${l}; ${d};`}).join("");return`
|
|
fn getCoordsFromIndex(index : i32) -> ${a} {
|
|
${s}
|
|
return ${a}(${n.join(",")});
|
|
}
|
|
`}var M8={};De(M8,{ArrayBufferToTypedArray:()=>P8,GPUBytesPerElement:()=>Iy,computeDispatch:()=>ze,computeWorkGroupSizeForConv2d:()=>Bx,computeWorkGroupSizeForMatMul:()=>$8,computeWorkPerThreadForConv2d:()=>Wx,flatDispatchLayout:()=>He,isWebGPUSupported:()=>Vx,tilesFitEvenlyIntoShape:()=>Hn});var Jl=65535,yo=e=>{let t=1;for(let r=0;r<e.length;r++)t*=e[r];return t};function Hn(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((r,a)=>r%e[a]===0)}function ze(e,t,r=[1,1,1],a=[1,1,1]){let[n,s,i]=[Math.ceil(yo(e.x.map(l=>t[l]))/(r[0]*a[0])),e.y?Math.ceil(yo(e.y.map(l=>t[l]))/(r[1]*a[1])):1,e.z?Math.ceil(yo(e.z.map(l=>t[l]))/(r[2]*a[2])):1];if(n<=Jl&&s<=Jl&&i<=Jl)return[n,s,i];w.assert(n>Jl&&e.y===void 0&&e.z===void 0,()=>"Dispatch size exceeds WebGPU limits in Y or Z dimension.");let o=Math.ceil(Math.sqrt(n));return o>Jl?(o=Math.ceil(Math.cbrt(n)),w.assert(o<=Jl,()=>"Total dispatch size exceeds WebGPU maximum."),[o,o,o]):[o,o,1]}function Bx(e,t){let r=yo(e.x.map(n=>t[n])),a=yo(e.y.map(n=>t[n]));return r<=4?[4,16,1]:a<=4?[16,4,1]:[16,16,1]}function $8(e,t,r){return e===1?[32,1,1]:r===1?[1,32,1]:[8,8,1]}function Wx(e,t){let r=yo(e.x.map(n=>t[n])),a=yo(e.y.map(n=>t[n]));return r<=4?[1,2,1]:a<=4?[2,1,1]:[2,2,1]}function He(e){return{x:e.map((t,r)=>r)}}function Iy(e){if(e==="float32"||e==="int32"||e==="bool"||e==="string")return 4;if(e==="complex64")return 8;throw new Error(`Unknown dtype ${e}`)}function P8(e,t){if(t==="float32")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool"||t==="string")return Uint8Array.from(new Int32Array(e));throw new Error(`Unknown dtype ${t}`)}function Vx(){return(typeof window!="undefined"||typeof WorkerGlobalScope!="undefined")&&!!navigator.gpu}var lue="return a + b;",uue="return areal * breal - aimag * bimag;",due="return areal * bimag + aimag * breal;",pue="return a / b;",hue="return a * b;",cue="return (a - b) * (a - b);",fue="return a - b;",mue="return f32(a == b);",gue="return vec4<f32>(a == b);",yue="return f32(a > b);",Aue="return vec4<f32>(a > b);",xue="return f32(a >= b);",bue="return vec4<f32>(a >= b);",vue="return f32(a < b);",wue="return vec4<f32>(a < b);",kue="return f32(a <= b);",Iue="return vec4<f32>(a <= b);",Sue="return f32(f32(a) >= 1.0 && f32(b) >= 1.0);",Tue=`return (vec4<f32>(a >= vec4<f32>(1.0)) *
|
|
vec4<f32>(b >= vec4<f32>(1.0)));`,Cue=`
|
|
if (isNanCustom(a)) { return a; }
|
|
if (isNanCustom(b)) { return b; }
|
|
`,O8=`
|
|
if (isNaN.r) {
|
|
resultTemp.r = uniforms.NAN;
|
|
}
|
|
if (isNaN.g) {
|
|
resultTemp.g = uniforms.NAN;
|
|
}
|
|
if (isNaN.b) {
|
|
resultTemp.b = uniforms.NAN;
|
|
}
|
|
if (isNaN.a) {
|
|
resultTemp.a = uniforms.NAN;
|
|
}
|
|
`,Nue=`
|
|
let s = sign(a) * sign(b);
|
|
let ia = i32(round(a));
|
|
let ib = i32(round(b));
|
|
return f32(idiv(ia, ib, s));
|
|
`,Eue=`
|
|
let ia = vec4<i32>(round(a));
|
|
let ib = vec4<i32>(round(b));
|
|
let cond = ib != vec4<i32>(0);
|
|
var resultTemp = vec4<i32>(0);
|
|
let s = sign(a) * sign(b);
|
|
|
|
// Windows (D3D) wants guaranteed non-zero int division at compile-time.
|
|
if (cond[0]) {
|
|
resultTemp[0] = idiv(ia[0], ib[0], s[0]);
|
|
}
|
|
if (cond[1]) {
|
|
resultTemp[1] = idiv(ia[1], ib[1], s[1]);
|
|
}
|
|
if (cond[2]) {
|
|
resultTemp[2] = idiv(ia[2], ib[2], s[2]);
|
|
}
|
|
if (cond[3]) {
|
|
resultTemp[3] = idiv(ia[3], ib[3], s[3]);
|
|
}
|
|
return vec4<f32>(resultTemp);
|
|
`,Rue="return f32(a != b);",Fue="return vec4<f32>(a != b);",Mue=`
|
|
if(a < 0.0 && floor(b) < b) {
|
|
return uniforms.NAN;
|
|
}
|
|
if (b == 0.0) {
|
|
return 1.0;
|
|
}
|
|
if (round(abs(b) % 2.0) != 1.0) {
|
|
return pow(abs(a), b);
|
|
}
|
|
return sign(a) * pow(abs(a), b);
|
|
`,$ue=`
|
|
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;
|
|
${O8}
|
|
return resultTemp;
|
|
`,Pue="if (a < 0.0) { return b * a; } return a;",Oue=`
|
|
let aLessThanZero = vec4<f32>(a < vec4<f32>(0.0));
|
|
return (aLessThanZero * (b * a)) + ((vec4<f32>(1.0) - aLessThanZero) * a);
|
|
`;function cv(e,t){let r=t?O8:Cue;return t?`
|
|
var resultTemp = vec4<f32>(${e}(a, b));
|
|
let isNaN = isNanCustomVec4(a) | isNanCustomVec4(b);
|
|
`+r+`
|
|
return resultTemp;
|
|
`:r+`
|
|
return ${e}(a, b);
|
|
`}function Mh(e,t){switch(e){case 0:return hue;case 1:return lue;case 2:return fue;case 3:return pue;case 4:return t?gue:mue;case 5:return t?Aue:yue;case 6:return t?bue:xue;case 7:return t?wue:vue;case 8:return t?Iue:kue;case 9:return t?Tue:Sue;case 10:return t?Fue:Rue;case 11:return cue;case 12:return t?Eue:Nue;case 14:return t?Oue:Pue;case 15:return cv("max",t);case 16:return cv("min",t);case 13:return t?$ue:Mue;case 17:return uue;case 18:return due;default:throw new Error(`BinaryType ${e} is not implemented!`)}}var zue="return abs(a);",Due="return ceil(a);",_ue="return cos(a);",Lue=`
|
|
let e2x = exp(-a);
|
|
return (e2x + 1.0 / e2x) / 2.0;
|
|
`,Bue="return exp(a) - 1.0;",Wue="if (a >= 0.0) { return a; } return (exp(a) - 1.0);",Vue=`
|
|
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;
|
|
`,Uue="return exp(a);",Gue="return floor(a);",jue="return a;",Hue=`if (a < 0.0) { return 1.0/0.0; }
|
|
return log(a);`,que="return f32(!(a >= 1.0));",Kue="return -a;",Xue="return (a < 0.0) ? b * a : a;",Zue="if (a < 0.0) { return uniforms.alpha * a; } return a;",Yue="if(a < 0.0) { return 0.0; } return a;",Jue="return clamp(a, 0.0, 6.0);",Que="return clamp(a, vec4<f32>(0.0, 0.0, 0.0, 0.0), vec4<f32>(6.0, 6.0, 6.0, 6.0));",ede=`
|
|
var resFloat = a * vec4<f32>(a >= vec4<f32>(0.0));
|
|
let isNaN = isNanCustomVec4(a);
|
|
|
|
if (isNaN.r) {
|
|
resFloat.r = a.r;
|
|
}
|
|
if (isNaN.g) {
|
|
resFloat.g = a.g;
|
|
}
|
|
if (isNaN.b) {
|
|
resFloat.b = a.b;
|
|
}
|
|
if (isNaN.a) {
|
|
resFloat.a = a.a;
|
|
}
|
|
return resFloat;
|
|
`,tde="return 1.0/sqrt(a);",rde="return 1.0 / (1.0 + exp(-1.0 * a));",ade="return sin(a);",nde=`
|
|
let e2x = exp(a);
|
|
return (e2x - 1.0 / e2x) / 2.0;
|
|
`,sde="return sqrt(a);",ide="return a * a;",ode=`
|
|
let e2x = exp(-2.0 * abs(a));
|
|
return sign(a) * (1.0 - e2x) / (1.0 + e2x);
|
|
`,lde="return f32(i32((a)));";function nu(e,t){switch(e){case 0:return zue;case 2:return _ue;case 3:return Lue;case 1:return Due;case 4:return t?Vue:Wue;case 5:return Uue;case 6:return Bue;case 7:return Gue;case 8:return jue;case 9:return Hue;case 10:return que;case 11:return Kue;case 12:return Xue;case 15:return Zue;case 13:return t?ede:Yue;case 14:return t?Que:Jue;case 16:return tde;case 19:return rde;case 17:return ade;case 18:return nde;case 20:return sde;case 21:return ide;case 22:return ode;case 23:return lde;default:throw new Error(`BinaryType ${e} is not implemented!`)}}function ts(e,t=!1){if(e===null)return null;if(e==="linear")return nu(8);if(e==="relu")return nu(13,t);if(e==="elu")return nu(4,t);if(e==="relu6")return nu(14,t);if(e==="prelu")return Mh(14,t);if(e==="sigmoid")return nu(19);throw new Error(`Activation ${e} has not been implemented for the WebGPU backend.`)}function z8(e,t,r,a){return w.assert(a%4===0&&e[0]===4,()=>"tileInner must be divisible by 4. And ColPerThread must be 4"),`
|
|
var<workgroup> mm_Asub : array<array<vec4<f32>, ${a/e[0]}>, ${t}>;
|
|
var<workgroup> mm_Bsub : array<array<vec4<f32>, ${r/e[0]}>, ${a}>;
|
|
|
|
let RowPerThread = ${e[1]};
|
|
let ColPerThread = ${e[0]};
|
|
let TileInner = ${a};
|
|
|
|
${Wi()}
|
|
|
|
let tileRow = ${t===1?"0":"i32(localId.y) * RowPerThread"};
|
|
let tileCol = i32(localId.x);
|
|
|
|
let globalRow = ${t===1?"0":"i32(globalId.y) * RowPerThread"};
|
|
let globalCol = i32(globalId.x);
|
|
let numTiles = (uniforms.dimInner - 1) / TileInner + 1;
|
|
|
|
var acc: array<vec4<f32>, RowPerThread>;
|
|
var ACached : vec4<f32>;
|
|
var BCached : array<vec4<f32>, 4>;
|
|
|
|
// Loop over shared dimension.
|
|
var globalColA = tileCol;
|
|
let RowPerThreadB = TileInner / i32(workGroupSizeY);
|
|
let tileRowB = i32(localId.y) * RowPerThreadB;
|
|
for (var t = 0; t < numTiles; t = t + 1) {
|
|
// Load one tile of A into local memory.
|
|
for (var innerRow = 0; innerRow < RowPerThread; innerRow = innerRow + 1) {
|
|
let inputRow = tileRow + innerRow;
|
|
let inputCol = tileCol;
|
|
mm_Asub[inputRow][inputCol] = mm_readA(globalRow + innerRow, globalColA, globalId);
|
|
}
|
|
globalColA = globalColA + TileInner / ColPerThread;
|
|
|
|
// Load one tile of B into local memory.
|
|
for (var innerRow = 0; innerRow < RowPerThreadB; innerRow = innerRow + 1) {
|
|
let inputRow = tileRowB + innerRow;
|
|
let inputCol = tileCol;
|
|
mm_Bsub[inputRow][inputCol] = mm_readB(t * TileInner + inputRow, globalCol, globalId);
|
|
}
|
|
|
|
workgroupBarrier();
|
|
|
|
// Compute acc values for a single thread.
|
|
for (var k = 0; k < TileInner / ColPerThread; k = k + 1) {
|
|
BCached[0] = mm_Bsub[k * ColPerThread][tileCol];
|
|
BCached[1] = mm_Bsub[k * ColPerThread + 1][tileCol];
|
|
BCached[2] = mm_Bsub[k * ColPerThread + 2][tileCol];
|
|
BCached[3] = mm_Bsub[k * ColPerThread + 3][tileCol];
|
|
|
|
for (var i = 0; i < RowPerThread; i = i + 1) {
|
|
ACached = mm_Asub[tileRow + i][k];
|
|
acc[i] = BCached[0] * ACached.x + acc[i];
|
|
acc[i] = BCached[1] * ACached.y + acc[i];
|
|
acc[i] = BCached[2] * ACached.z + acc[i];
|
|
acc[i] = BCached[3] * ACached.w + acc[i];
|
|
}
|
|
}
|
|
|
|
workgroupBarrier();
|
|
}
|
|
|
|
for (var innerRow = 0; innerRow < RowPerThread; innerRow = innerRow + 1) {
|
|
mm_write(globalRow + innerRow,
|
|
globalCol,
|
|
acc[innerRow], globalId);
|
|
}
|
|
}`}var ude=class{constructor(e,t,r,a=null,n=null,s=null){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32; dimBOuter : i32; dimInner : i32;",this.workGroupSize=[8,8,1],this.isVec4=!0,this.outputShape=t,this.dispatchLayout={x:[2],y:[1],z:[0]},t[1]===1?this.elementsPerThread=[4,1,1]:this.elementsPerThread=[4,4,1],this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize,this.elementsPerThread);let i=a!=null,o=s!=null;i&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),this.tileAOuter=t[1]===1?1:this.workGroupSize[1]*this.elementsPerThread[1],this.tileBOuter=this.workGroupSize[0]*this.elementsPerThread[0],this.tileInner=this.tileBOuter,this.aShape=e,this.addBias=i,this.activation=n,this.hasPreluActivationWeights=o,[this.fitA,this.fitB]=this.getShapeFit(),this.shaderKey=`matMulPackedVec4_${this.activation}_${this.fitA}_${this.fitB}_${this.elementsPerThread}`}getShapeFit(){let e=this.aShape[2],t=this.outputShape[2],r=[this.outputShape[0],e,t],a=[this.tileAOuter,this.tileInner],n=[this.tileInner,this.tileBOuter];return[Hn(a,this.aShape.slice(1)),Hn(n,r.slice(1))]}getUserCode(){let e=this.fitA?"return A.numbers[batch * batchASize + row * uniforms.dimInner / 4 + col]":`if (coordsInBounds2D(vec2<i32>(row, col * 4), vec2<i32>(uniforms.dimAOuter, uniforms.dimInner))) {
|
|
return A.numbers[batch * batchASize + row * uniforms.dimInner / 4 + col];
|
|
}
|
|
return vec4<f32>(0.0)`,t=this.fitB?"return B.numbers[batch * batchBSize + row * uniforms.dimBOuter / 4 + col]":`if(coordsInBounds2D(vec2<i32>(row, col * 4), vec2<i32>(uniforms.dimInner, uniforms.dimBOuter))) {
|
|
return B.numbers[batch * batchBSize + row * uniforms.dimBOuter / 4 + col];
|
|
}
|
|
return vec4<f32>(0.0)`,r="",a="";if(this.activation){let s=ts(this.activation,this.isVec4);this.hasPreluActivationWeights?r=`fn activation(a : vec4<f32>, outCoord : vec3<i32>) -> vec4<f32> {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${s}
|
|
}`:r=`
|
|
fn activation(a : vec4<f32>, outCoord : vec3<i32>) -> vec4<f32> {
|
|
${s}
|
|
}`,a="value = activation(value, outCoord);"}let n=this.addBias?"value = value + getBiasByOutputCoords(outCoord);":"";return`
|
|
${r}
|
|
fn mm_readA(row : i32, col : i32, globalId : vec3<u32>) -> vec4<f32> {
|
|
let batchASize = uniforms.aShape[1] * uniforms.aShape[2] / 4;
|
|
let batch = i32(globalId.z);
|
|
${e};
|
|
}
|
|
|
|
fn mm_readB(row : i32, col : i32, globalId : vec3<u32>) -> vec4<f32> {
|
|
let batchBSize = uniforms.bShape[1] * uniforms.bShape[2] / 4;
|
|
let batch = i32(globalId.z);
|
|
${t};
|
|
}
|
|
|
|
fn mm_write(row : i32, col : i32, valueIn : vec4<f32>, globalId : vec3<u32>) {
|
|
if (row < uniforms.aShape[1] && col * 4 < uniforms.bShape[2])
|
|
{
|
|
var value = valueIn;
|
|
let batch = i32(globalId.z);
|
|
let outCoord = vec3<i32>(batch, row, col * 4);
|
|
${n}
|
|
${a}
|
|
setOutputAtCoords(outCoord[0], outCoord[1], outCoord[2], value);
|
|
}
|
|
}
|
|
${z8(this.elementsPerThread,this.tileAOuter,this.tileBOuter,this.tileInner)}
|
|
`}};function Ux(e,t){let r=t[1]*e[1],a=t[0]*e[0],n=r>a?r:a;return`
|
|
var<workgroup> mm_Asub : array<array<f32, ${n}>, ${r}>;
|
|
var<workgroup> mm_Bsub : array<array<f32, ${a}>, ${n}>;
|
|
${Wi()}
|
|
let tileRow = i32(localId.y) * ${e[1]};
|
|
let tileCol = i32(localId.x) * ${e[0]};
|
|
|
|
let globalRow = i32(globalId.y) * ${e[1]};
|
|
let globalCol = i32(globalId.x) * ${e[0]};
|
|
|
|
let numTiles = (uniforms.dimInner - 1) / ${n} + 1;
|
|
|
|
var acc : array<array<f32, ${e[0]}>, ${e[1]}>;
|
|
var ACached : f32;
|
|
var BCached : array<f32, ${e[0]}>;
|
|
|
|
// Without this initialization strange values show up in acc.
|
|
for (var innerRow = 0; innerRow < ${e[1]}; innerRow = innerRow + 1) {
|
|
for (var innerCol = 0; innerCol < ${e[0]}; innerCol = innerCol + 1) {
|
|
acc[innerRow][innerCol] = 0.0;
|
|
}
|
|
}
|
|
|
|
let ColPerThreadA = ${n} / ${t[0]};
|
|
let tileColA = i32(localId.x) * ColPerThreadA;
|
|
let RowPerThreadB = ${n} / ${t[1]};
|
|
let tileRowB = i32(localId.y) * RowPerThreadB;
|
|
|
|
// Loop over shared dimension.
|
|
for (var t = 0; t < numTiles; t = t + 1) {
|
|
// Load one tile of A into local memory.
|
|
for (var innerRow = 0; innerRow < ${e[1]}; innerRow = innerRow + 1) {
|
|
for (var innerCol = 0; innerCol < ColPerThreadA; innerCol = innerCol + 1) {
|
|
let inputRow = tileRow + innerRow;
|
|
let inputCol = tileColA + innerCol;
|
|
|
|
mm_Asub[inputRow][inputCol] = mm_readA(
|
|
globalRow + innerRow,
|
|
t * ${n} + inputCol, globalId);
|
|
}
|
|
}
|
|
// Load one tile of B into local memory.
|
|
for (var innerRow = 0; innerRow < RowPerThreadB; innerRow = innerRow + 1) {
|
|
for (var innerCol = 0; innerCol < ${e[0]}; innerCol = innerCol + 1) {
|
|
let inputRow = tileRowB + innerRow;
|
|
let inputCol = tileCol + innerCol;
|
|
|
|
mm_Bsub[inputRow][inputCol] = mm_readB(
|
|
t * ${n} + inputRow,
|
|
globalCol + innerCol, globalId);
|
|
}
|
|
}
|
|
|
|
workgroupBarrier();
|
|
|
|
// Compute acc values for a single thread.
|
|
for (var k = 0; k < ${n}; k = k + 1) {
|
|
for (var inner = 0; inner < ${e[0]}; inner = inner + 1) {
|
|
BCached[inner] = mm_Bsub[k][tileCol + inner];
|
|
}
|
|
|
|
for (var innerRow = 0; innerRow < ${e[1]}; innerRow = innerRow + 1) {
|
|
ACached = mm_Asub[tileRow + innerRow][k];
|
|
for (var innerCol = 0; innerCol < ${e[0]}; innerCol = innerCol + 1) {
|
|
acc[innerRow][innerCol] = acc[innerRow][innerCol] + ACached * BCached[innerCol];
|
|
}
|
|
}
|
|
}
|
|
|
|
workgroupBarrier();
|
|
}
|
|
|
|
for (var innerRow = 0; innerRow < ${e[1]}; innerRow = innerRow + 1) {
|
|
for (var innerCol = 0; innerCol < ${e[0]}; innerCol = innerCol + 1) {
|
|
|
|
if ((globalCol + innerCol) < uniforms.dimBOuter &&
|
|
(globalRow + innerRow) < uniforms.dimAOuter) {
|
|
mm_write(globalRow + innerRow,
|
|
globalCol + innerCol,
|
|
acc[innerRow][innerCol], globalId);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
`}function dde(e){return`
|
|
let TileSize = ${e[0]*4};
|
|
var<workgroup> mm_Asub : array<vec4<f32>, ${e[0]}>;
|
|
|
|
${Wi()}
|
|
let tileCol = i32(localId.x);
|
|
let globalCol = i32(globalId.x);
|
|
let globalRow = i32(globalId.y);
|
|
|
|
let numTiles = (uniforms.dimInner - 1) / TileSize + 1;
|
|
|
|
// Without this initialization strange values show up in acc.
|
|
var acc = 0.0;
|
|
|
|
// Loop over shared dimension.
|
|
for (var t = 0; t < numTiles; t = t + 1) {
|
|
// Load one tile of A into local memory.
|
|
let colA = t * TileSize + tileCol * 4;
|
|
mm_Asub[tileCol] = vec4<f32>(mm_readA(globalRow, colA, globalId),
|
|
mm_readA(globalRow, colA + 1, globalId),
|
|
mm_readA(globalRow, colA + 2, globalId),
|
|
mm_readA(globalRow, colA + 3, globalId));
|
|
workgroupBarrier();
|
|
|
|
// Compute acc values for a single thread.
|
|
for (var k = 0; k < TileSize / 4; k = k + 1) {
|
|
let rowB = t * TileSize + k * 4;
|
|
let BCached = vec4<f32>(mm_readB(rowB, globalCol, globalId),
|
|
mm_readB(rowB + 1, globalCol, globalId),
|
|
mm_readB(rowB + 2, globalCol, globalId),
|
|
mm_readB(rowB + 3, globalCol, globalId));
|
|
|
|
let ACached = mm_Asub[k];
|
|
acc = acc + dot(ACached, BCached);
|
|
}
|
|
|
|
workgroupBarrier();
|
|
}
|
|
|
|
if (globalRow < uniforms.dimAOuter && globalCol < uniforms.dimBOuter) {
|
|
mm_write(globalRow, globalCol, acc, globalId);
|
|
}
|
|
}
|
|
`}var D8=class{constructor(e,t,r,a=!1,n=!1,s=null,i=null,o=null){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32; dimBOuter : i32; dimInner : i32;",this.workGroupSize=[16,16,1],this.outputShape=t,this.dispatchLayout={x:[2],y:[1],z:[0]};let l=a?e[1]:e[2];this.workGroupSize=$8(t[1],l,t[2]),(t[1]===1||t[2]===1)&&(r=1),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize,[r,r,1]),w.arraysEqual(this.dispatch,[1,1,1])&&(r=1,this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize,[r,r,1]));let d=s!=null,u=o!=null;d&&this.variableNames.push("bias"),u&&this.variableNames.push("preluActivationWeights"),this.workPerThread=r,this.aShape=e,this.transposeA=a,this.transposeB=n,this.addBias=d,this.activation=i,this.hasPreluActivationWeights=u;let p=this.outputShape[2],h=this.transposeB?[this.outputShape[0],p,l]:[this.outputShape[0],l,p];[this.fitA,this.fitB]=this.getShapeFit(h),this.shaderKey=`matMulPacked_${this.workPerThread}_${a}_${n}_${this.activation}_${this.fitA}_${this.fitB}_${this.outputShape[1]>1}`}getShapeFit(e){let t=this.workGroupSize[1]*this.workPerThread,r=this.workGroupSize[0]*this.workPerThread,a=t>r?t:r;this.outputShape[1]===1&&(a*=4),w.assert(a%this.workGroupSize[0]===0&&a%this.workGroupSize[1]===0,()=>"tileInner must be multiple of workgroupsize.x and workgroupsize.y");let n=[t,a],s=[a,r];return[Hn(n,this.aShape.slice(1)),Hn(s,e.slice(1))]}getUserCode(){let e;this.transposeA===!1?e=this.fitA?"return A.numbers[batch * batchASize + row * uniforms.dimInner + col];":`if(coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimAOuter, uniforms.dimInner))) {
|
|
return A.numbers[batch * batchASize + row * uniforms.dimInner + col];
|
|
}
|
|
return 0.0;`:e=this.fitA?"return A.numbers[batch * batchASize + col * uniforms.dimAOuter + row];":`if(coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimAOuter, uniforms.dimInner))) {
|
|
return A.numbers[batch* batchASize + col * uniforms.dimAOuter + row];
|
|
}
|
|
return 0.0;`;let t;this.transposeB===!1?t=this.fitB?"return B.numbers[batch * batchBSize + row * uniforms.dimBOuter + col];":`if(coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimInner, uniforms.dimBOuter))) {
|
|
return B.numbers[batch * batchBSize + row * uniforms.dimBOuter + col];
|
|
}
|
|
return 0.0;`:t=this.fitB?"return B.numbers[batch * batchBSize + col * uniforms.dimInner + row];":`if(coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimInner, uniforms.dimBOuter))) {
|
|
return B.numbers[batch * batchBSize + col * uniforms.dimInner + row];
|
|
}
|
|
return 0.0;`;let r="",a="";if(this.activation){let s=ts(this.activation,!1);this.hasPreluActivationWeights?r=`fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${s}
|
|
}`:r=`
|
|
fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
|
|
${s}
|
|
}
|
|
`,a="value = activation(value, outCoord);"}let n=this.addBias?"value = value + getBiasByOutputCoords(outCoord);":"";return`
|
|
${r}
|
|
|
|
fn mm_readA(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
|
|
let batchASize = uniforms.aShape[1] * uniforms.aShape[2];
|
|
let batch = i32(globalId.z);
|
|
${e}
|
|
}
|
|
|
|
fn mm_readB(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
|
|
let batch = i32(globalId.z);
|
|
let batchBSize = uniforms.bShape[1] * uniforms.bShape[2];
|
|
${t}
|
|
}
|
|
|
|
fn mm_write(row : i32, col : i32, valueIn : f32, globalId : vec3<u32>) {
|
|
var value = valueIn;
|
|
let batch = i32(globalId.z);
|
|
let outCoord = vec3<i32>(batch, row, col);
|
|
${n}
|
|
${a}
|
|
setOutputAtCoords(batch, row, col, value);
|
|
}
|
|
${this.outputShape[1]>1?Ux([this.workPerThread,this.workPerThread,1],this.workGroupSize):dde(this.workGroupSize)}
|
|
`}};function pde(){return`
|
|
var<workgroup> sumValues : array<f32, workGroupSizeX>;
|
|
${Wi()}
|
|
let coords = getOutputCoords();
|
|
let batch = coords[0];
|
|
let row = coords[1];
|
|
let col = coords[2];
|
|
var sum = 0.0;
|
|
let Length = uniforms.dimInner;
|
|
for (var k = i32(localId.x); k < Length; k = k + i32(workGroupSizeX)) {
|
|
let dataA = mm_readA(batch, row, k);
|
|
let dataB = mm_readB(batch, k, col);
|
|
sum = sum + dataA * dataB;
|
|
}
|
|
sumValues[localId.x] = sum;
|
|
workgroupBarrier();
|
|
|
|
for(var currentSize = workGroupSizeX / 2u; currentSize > 1u;
|
|
currentSize = currentSize / 2u) {
|
|
if (localId.x < currentSize)
|
|
{
|
|
sumValues[localId.x] = sumValues[localId.x] + sumValues[localId.x + currentSize];
|
|
}
|
|
workgroupBarrier();
|
|
}
|
|
|
|
if (localId.x == 0u) {
|
|
sum = sumValues[0] + sumValues[1];
|
|
mm_write(batch, row, col, sum);
|
|
}
|
|
}
|
|
`}var hde=class{constructor(e,t=!1,r=!1,a=null,n=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=ze(this.dispatchLayout,this.outputShape,this.workGroupSize);let i=a!=null,o=s!=null;i&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),this.transposeA=t,this.transposeB=r,this.addBias=i,this.activation=n,this.hasPreluActivationWeights=o,this.shaderKey=`matMulReduce_${this.activation}_${t}_${r}`}getUserCode(){let e;this.transposeA===!1?e="return A.numbers[batch * batchASize + row * uniforms.dimInner + col];":e="return A.numbers[batch * batchASize + col * uniforms.dimAOuter + row];";let t;this.transposeB===!1?t="return B.numbers[batch * batchBSize + row * uniforms.dimBOuter + col];":t="return B.numbers[batch * batchBSize + col * uniforms.dimInner + row];";let r="",a="";if(this.activation){let s=ts(this.activation,!1);this.hasPreluActivationWeights?r=`fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${s}
|
|
}`:r=`
|
|
fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
|
|
${s}
|
|
}
|
|
`,a="value = activation(value, outCoord);"}let n=this.addBias?"value = value + getBiasByOutputCoords(outCoord);":"";return`
|
|
${r}
|
|
|
|
fn mm_readA(batch: i32, row : i32, col : i32) -> f32 {
|
|
let batchASize = uniforms.aShape[1] * uniforms.aShape[2];
|
|
${e}
|
|
}
|
|
|
|
fn mm_readB(batch: i32, row : i32, col : i32) -> f32 {
|
|
let batchBSize = uniforms.bShape[1] * uniforms.bShape[2];
|
|
${t}
|
|
}
|
|
|
|
fn mm_write(batch: i32, row : i32, col : i32, valueIn : f32) {
|
|
var value = valueIn;
|
|
let outCoord = vec3<i32>(batch, row, col);
|
|
${n}
|
|
${a}
|
|
setOutputAtCoords(batch, row, col, value);
|
|
}
|
|
${pde()}
|
|
`}};function cde(e){let t=e[1]/2,r=e[0],a=t>r?t:r;return`
|
|
var<workgroup> mm_Asub1 : array<array<f32, ${a}>, ${t}>;
|
|
var<workgroup> mm_Bsub1 : array<array<f32, ${r}>, ${a}>;
|
|
var<workgroup> mm_Asub2 : array<array<f32, ${a}>, ${t}>;
|
|
var<workgroup> mm_Bsub2 : array<array<f32, ${r}>, ${a}>;
|
|
|
|
// If the output size is small for matrix multiplication, avoid to use vec4
|
|
// and handle some elements per thread to optimally utilize the ALU.
|
|
// Introduces two shared memory buffers, some logical threads could handle
|
|
// arithmetic operations and others handle IO operations between barrier api,
|
|
// makes ALUs and load/store units work simultaneously, could improves
|
|
// the performance.
|
|
${Wi()}
|
|
let tileRow = i32(localId.y);
|
|
let tileCol = i32(localId.x);
|
|
let globalRow = i32(globalId.y);
|
|
let globalCol = i32(globalId.x);
|
|
|
|
// uniforms.dimInner should be greater than 0.
|
|
let numTiles = (uniforms.dimInner - 1) / ${a} + 1;
|
|
var acc = 0.0;
|
|
|
|
var globalColA = tileCol;
|
|
var globalRowB = tileRow;
|
|
for (var t = 0; t < numTiles; t = t + 1) {
|
|
if (t == 0) {
|
|
if (tileRow < ${t}) {
|
|
// Load one tile of A and B into local memory.
|
|
// globalRow is always greater than or equal tileRow.
|
|
mm_Asub1[tileRow][tileCol] =
|
|
mm_readA((globalRow - tileRow) / 2 + tileRow, globalColA, globalId);
|
|
globalColA = globalColA + ${a};
|
|
mm_Bsub1[tileRow][tileCol] = mm_readB(globalRowB, globalCol, globalId);
|
|
globalRowB = globalRowB + ${a};
|
|
}
|
|
} else {
|
|
if (tileRow < ${t}) {
|
|
// Load one tile of A and B into local memory.
|
|
// globalRow is always greater than or equal tileRow.
|
|
mm_Asub1[tileRow][tileCol] =
|
|
mm_readA((globalRow - tileRow) / 2 + tileRow, globalColA, globalId);
|
|
globalColA = globalColA + ${a};
|
|
mm_Bsub1[tileRow][tileCol] = mm_readB(globalRowB, globalCol, globalId);
|
|
globalRowB = globalRowB + ${a};
|
|
} else {
|
|
// Compute acc values for a single thread.
|
|
for (var k = 0; k < ${a}; k = k + 1) {
|
|
let subRow = tileRow - ${t};
|
|
if (subRow < 0) {
|
|
continue;
|
|
}
|
|
acc = acc + mm_Asub2[subRow][k] * mm_Bsub2[k][tileCol];
|
|
}
|
|
}
|
|
}
|
|
workgroupBarrier();
|
|
if (t != 0) {
|
|
t = t + 1;
|
|
}
|
|
|
|
if (t < numTiles) {
|
|
if (tileRow < ${t}) {
|
|
// Load one tile of A and B into local memory.
|
|
// globalRow is always greater than or equal tileRow.
|
|
mm_Asub2[tileRow][tileCol] =
|
|
mm_readA((globalRow - tileRow) / 2 + tileRow, globalColA, globalId);
|
|
globalColA = globalColA + ${a};
|
|
mm_Bsub2[tileRow][tileCol] = mm_readB(globalRowB, globalCol, globalId);
|
|
globalRowB = globalRowB + ${a};
|
|
} else {
|
|
// Compute acc values for a single thread.
|
|
for (var k = 0; k < ${a}; k = k + 1) {
|
|
let subRow = tileRow - ${t};
|
|
if (subRow < 0) {
|
|
continue;
|
|
}
|
|
acc = acc + mm_Asub1[subRow][k] * mm_Bsub1[k][tileCol];
|
|
}
|
|
}
|
|
}
|
|
workgroupBarrier();
|
|
}
|
|
let writeCol = (globalRow - tileRow) / 2 + tileRow - ${t};
|
|
if (tileRow >= ${t} && writeCol >= 0) {
|
|
mm_write(writeCol, globalCol, acc, globalId);
|
|
}
|
|
}
|
|
`}var fde=class{constructor(e,t,r,a=null,n=null,s=null){this.variableNames=["A","B"],this.uniforms="dimAOuter : i32; dimBOuter : i32; dimInner : i32;",this.workGroupSize=[8,16,1],w.assert(e[1]<=16||t[2]<=16,()=>"This program can be only used when A width or B Height are small"),this.outputShape=r,this.dispatchLayout={x:[2],y:[1],z:[0]},this.dispatch=[Math.ceil(r[2]/this.workGroupSize[0]),Math.ceil(r[1]*2/this.workGroupSize[1]),r[0]];let i=a!=null;i&&this.variableNames.push("bias");let o=s!=null;o&&this.variableNames.push("preluActivationWeights"),this.addBias=i,this.activation=n,this.hasPreluActivationWeights=o,this.shaderKey=`matMulSmallOutputSize_${this.activation}`}getUserCode(){let e=`if (coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimAOuter, uniforms.dimInner))) {
|
|
return A.numbers[batch * batchASize + row * uniforms.dimInner + col];
|
|
}
|
|
return 0.0;`,t=`if (coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimInner, uniforms.dimBOuter))) {
|
|
return B.numbers[batch * batchBSize + row * uniforms.dimBOuter + col];
|
|
}
|
|
return 0.0;`,r="",a="";if(this.activation){let s=ts(this.activation,!1);this.hasPreluActivationWeights?r=`fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${s}
|
|
}`:r=`fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
|
|
${s}
|
|
}`,a="value = activation(value, outCoord);"}let n=this.addBias?"value = value + getBiasByOutputCoords(outCoord);":"";return`
|
|
${r}
|
|
|
|
fn mm_readA(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
|
|
let batchASize = uniforms.aShape[1] * uniforms.aShape[2];
|
|
let batch = i32(globalId.z);
|
|
${e}
|
|
}
|
|
fn mm_readB(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
|
|
let batch = i32(globalId.z);
|
|
let batchBSize = uniforms.bShape[1] * uniforms.bShape[2];
|
|
${t}
|
|
}
|
|
fn mm_write(row : i32, col : i32, valueIn : f32, globalId : vec3<u32>) {
|
|
if (coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimAOuter, uniforms.dimBOuter))) {
|
|
let batch = i32(globalId.z);
|
|
let outCoord = vec3<i32>(batch, row, col);
|
|
var value = valueIn;
|
|
${n}
|
|
${a}
|
|
setOutputAtCoords(batch, row, col, value);
|
|
}
|
|
}
|
|
${cde(this.workGroupSize)}
|
|
`}};function Ge(e){let{inputs:t,attrs:r}=e,{x:a}=t,{shape:n}=r,s=w.sizeFromShape(a.shape),i=w.inferFromImplicitShape(n,s),o=w.sizeFromShape(i);return w.assert(s===o,()=>`The new shape (${i}) has ${o} elements and the old shape (${a.shape}) has ${s} elements. The new shape and old shape must have the same number of elements.`),e.backend.incRef(a.dataId),{dataId:a.dataId,shape:i,dtype:a.dtype}}var mde={kernelName:tl,backendName:"webgpu",kernelFunc:Ge};function Gx({a:e,b:t,transposeA:r,transposeB:a,backend:n,bias:s=null,preluActivationWeights:i=null,leakyreluAlpha:o=0,activation:l=null}){let d=e.shape.length,u=t.shape.length,p=r?e.shape[d-2]:e.shape[d-1],h=a?t.shape[u-1]:t.shape[u-2],c=r?e.shape[d-1]:e.shape[d-2],f=a?t.shape[u-2]:t.shape[u-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),y=w.sizeFromShape(m),A=w.sizeFromShape(g),x=yl.assertAndGetBroadcastShape(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([c,f]);w.assert(p===h,()=>`Error in matMul: inner shapes (${p}) and (${h}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${r} and transposeB=${a} must match.`);let b=r?[y,p,c]:[y,c,p],v=a?[A,f,h]:[A,h,f],C=Ge({inputs:{x:e},backend:n,attrs:{shape:b}}),T=Ge({inputs:{x:t},backend:n,attrs:{shape:v}}),E=[C,T],R=Math.max(y,A),z=p%4===0&&f%4===0&&!r&&!a&&f>=32,M;c*f<=32?M=new hde([R,c,f],r,a,s,l,i):!r&&!a&&(c<=16&&(f<=512||h>=2*f)||f<=16&&(c<=512||p>=2*c))?M=new fde(b,v,[R,c,f],s,l,i):z?M=new ude(b,[R,c,f],Y().get("WEBGPU_MATMUL_WORK_PER_THREAD"),s,l,i):M=new D8(b,[R,c,f],Y().get("WEBGPU_MATMUL_WORK_PER_THREAD"),r,a,s,l,i);let I=[C,T];s&&I.push(s),i&&I.push(i);let D=[{type:"int32",data:[c]},{type:"int32",data:[f]},{type:"int32",data:[p]}],O=n.runWebGPUProgram(M,I,e.dtype,D),j=Ge({inputs:{x:O},backend:n,attrs:{shape:x}});E.push(O);for(let X of E)n.disposeData(X.dataId);return j}function gde(e){let{inputs:t,backend:r,attrs:a}=e,{a:n,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:d,activation:u,leakyreluAlpha:p}=a;return Gx({a:n,b:s,transposeA:l,transposeB:d,backend:r,bias:i,preluActivationWeights:o,leakyreluAlpha:p,activation:u})}var yde={kernelName:Rs,backendName:"webgpu",kernelFunc:gde},fv=class{constructor(e,t,r){this.variableNames=["AReal","AImag","BReal","BImag"],this.workGroupSize=[128,1,1],this.size=!0,this.outputShape=N.assertAndGetBroadcastShape(t,r),this.dispatchLayout=He(this.outputShape),this.dispatch=ze(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 {
|
|
${Mh(this.op,!1)}
|
|
}
|
|
|
|
${Je()}
|
|
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));
|
|
}
|
|
}
|
|
`}},Ade=class{constructor(e,t,r,a){this.variableNames=["A","B"],this.size=!0;let n=256;this.workGroupSize=[n,1,1],this.outputShape=N.assertAndGetBroadcastShape(t,r),this.dispatchLayout=He(this.outputShape),this.lastDimensionSize=a?r[0]:t[0],this.lastDimensionSize<256?this.workPerThread=1:this.lastDimensionSize<512?this.workPerThread=2:this.workPerThread=4,this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.useSharedMemoryWithB=a,this.op=e,this.shaderKey=`binaryShared_${e}_${this.lastDimensionSize}_${this.useSharedMemoryWithB}`}getUserCode(){let e=this.lastDimensionSize>1?`coords[${this.outputShape.length-1}]`:"0",t=this.useSharedMemoryWithB?`let a = getAByOutputCoords(coords);
|
|
let b = sharedBuf[${e}];`:`let a = sharedBuf[${e}];
|
|
let b = getBByOutputCoords(coords);`;return`
|
|
fn binaryOperation(a : f32, b : f32) -> f32 {
|
|
${Mh(this.op,!1)}
|
|
}
|
|
var<workgroup> sharedBuf : array<f32, ${this.lastDimensionSize}>;
|
|
${Je()}
|
|
|
|
// Fill in the shared memory buffer. Here we need a loop to make sure
|
|
// that all data in A|B are uploaded when |sharedMemorySize| is larger
|
|
// than work group size.
|
|
for(var localIndex = i32(localId.x); localIndex < ${this.lastDimensionSize}; localIndex = localIndex + ${this.workGroupSize[0]}) {
|
|
sharedBuf[localIndex] = f32(${this.useSharedMemoryWithB?"B":"A"}.numbers[localIndex]);
|
|
}
|
|
workgroupBarrier();
|
|
|
|
for(var i = 0; i < ${this.workPerThread}; i = i + 1) {
|
|
let flatIndex = index * ${this.workPerThread} + i;
|
|
if(flatIndex < uniforms.size) {
|
|
let coords = getCoordsFromIndex(flatIndex);
|
|
|
|
${t}
|
|
setOutputAtIndex(flatIndex, binaryOperation(a, b));
|
|
}
|
|
}
|
|
}
|
|
`}},xde=class{constructor(e,t,r){this.variableNames=["A","B"],this.workPerThread=4,this.isVec4=!0,this.size=!0;let a=128;this.workGroupSize=[a,1,1],this.outputShape=N.assertAndGetBroadcastShape(t,r),this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.op=e,this.shaderKey=`binaryVec4_${e}`}getUserCode(){return`
|
|
fn binaryOperation(a : vec4<f32>, b : vec4<f32>) -> vec4<f32> {
|
|
${Mh(this.op,this.isVec4)}
|
|
}
|
|
${Je()}
|
|
if (index < uniforms.size) {
|
|
let a = getAByOutputIndex(index);
|
|
let b = getBByOutputIndex(index);
|
|
setOutputAtIndex(index, binaryOperation(a, b));
|
|
}
|
|
}
|
|
`}},_8=class{constructor(e,t,r){this.variableNames=["A","B"],this.size=!0;let a=128;this.workGroupSize=[a,1,1],this.outputShape=N.assertAndGetBroadcastShape(t,r),this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`binary_${e}`,this.op=e}getUserCode(){return`
|
|
fn binaryOperation(a : f32, b : f32) -> f32 {
|
|
${Mh(this.op,!1)}
|
|
}
|
|
${Je()}
|
|
if (index < uniforms.size) {
|
|
let a = getAByOutputIndex(index);
|
|
let b = getBByOutputIndex(index);
|
|
setOutputAtIndex(index, binaryOperation(a, b));
|
|
}
|
|
}
|
|
`}};function mv(e,t,r){if(w.arraysEqual(t,r)&&w.sizeFromShape(t)%4===0)return new xde(e,t,r);let a=t.length===1&&r.length>1&&t[0]<1024,n=r.length===1&&t.length>1&&r[0]<1024;return a||n?new Ade(e,t,r,n):new _8(e,t,r)}function Va(e){let{inputs:t}=e,{x:r}=t;return e.backend.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}var bde={kernelName:ui,backendName:"webgpu",kernelFunc:Va};function xd(e){let{inputs:t,backend:r}=e,{real:a,imag:n}=t,s=r.makeTensorInfo(a.shape,"complex64"),i=r.tensorMap.get(s.dataId),o=Va({inputs:{x:a},backend:r}),l=Va({inputs:{x:n},backend:r});return i.complexTensorInfos={real:o,imag:l},s}var vde={kernelName:Lp,backendName:"webgpu",kernelFunc:xd},$h=class{constructor(e,t){this.variableNames=["A"],this.size=!0;let r=128;this.workGroupSize=[r,1,1],this.outputShape=e,this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.op=t,this.shaderKey=`unary_${t}`}getUserCode(){return`
|
|
fn unaryOperation(a : f32) -> f32 {
|
|
${nu(this.op,!1)}
|
|
}
|
|
${Je()}
|
|
if (index < uniforms.size) {
|
|
let a = getAByOutputIndex(index);
|
|
setOutputAtIndex(index, unaryOperation(a));
|
|
}
|
|
}
|
|
`}};function xr({opType:e,cpuKernelImpl:t,dtype:r}){return({inputs:a,backend:n})=>{let{x:s}=a,i=n,o=r||s.dtype;if(i.shouldExecuteOnCPU([s])&&t!=null){let d=i.tensorMap.get(s.dataId),u=t(d.values,o);return i.makeTensorInfo(s.shape,o,u)}let l=new $h(s.shape,e);return i.runWebGPUProgram(l,[s],o)}}function Wr({opSnippet:e,cpuKernelImpl:t,supportsComplex:r=!1,dtype:a}){return({inputs:n,backend:s})=>{let{a:i,b:o}=n,l=s;if(r&&i.dtype==="complex64"){let p=l.tensorMap.get(i.dataId),h=l.tensorMap.get(o.dataId),c,f;if(e!==0)[c,f]=[[p.complexTensorInfos.real,h.complexTensorInfos.real],[p.complexTensorInfos.imag,h.complexTensorInfos.imag]].map(g=>{let[y,A]=g,x={dataId:y.dataId,dtype:y.dtype,shape:i.shape},b={dataId:A.dataId,dtype:A.dtype,shape:o.shape},v=mv(e,i.shape,o.shape);return l.runWebGPUProgram(v,[x,b],Or(y.dtype,A.dtype))});else{let g=new fv(17,i.shape,o.shape),y=new fv(18,i.shape,o.shape),A=[{dataId:p.complexTensorInfos.real.dataId,dtype:p.complexTensorInfos.real.dtype,shape:i.shape},{dataId:p.complexTensorInfos.imag.dataId,dtype:p.complexTensorInfos.imag.dtype,shape:i.shape},{dataId:h.complexTensorInfos.real.dataId,dtype:h.complexTensorInfos.real.dtype,shape:o.shape},{dataId:h.complexTensorInfos.imag.dataId,dtype:h.complexTensorInfos.imag.dtype,shape:o.shape}];c=l.runWebGPUProgram(g,A,"float32"),f=l.runWebGPUProgram(y,A,"float32")}let m=xd({inputs:{real:c,imag:f},backend:l});return l.disposeData(c.dataId),l.disposeData(f.dataId),m}let d=a||Or(i.dtype,o.dtype);if((i.dtype==="string"||o.dtype==="string"||l.shouldExecuteOnCPU([i,o]))&&t!=null){let p=l.tensorMap.get(i.dataId).values,h=l.tensorMap.get(o.dataId).values,c=i.dtype==="string"?N.fromUint8ToStringArray(p):p,f=i.dtype==="string"?N.fromUint8ToStringArray(h):h,[m,g]=t(i.shape,o.shape,c,f,d);return l.makeTensorInfo(g,d,m)}let u=mv(e,i.shape,o.shape);return l.runWebGPUProgram(u,[i,o],d)}}var{addImpl:wde,ceilImpl:kde,concatImpl:Ide,equalImpl:Sde,expImpl:Tde,expm1Impl:Cde,floorImpl:Nde,gatherNdImpl:Ede,gatherV2Impl:Rde,greaterEqualImpl:Fde,greaterImpl:Mde,lessEqualImpl:$de,lessImpl:Pde,logImpl:Ode,maxImpl:zde,maximumImpl:Dde,minimumImpl:_de,multiplyImpl:Lde,negImpl:Bde,notEqualImpl:Wde,prodImpl:Vde,rangeImpl:Ude,rsqrtImpl:Gde,simpleAbsImpl:jde,sliceImpl:Hde,stridedSliceImpl:qde,stringNGramsImpl:Kde,subImpl:Xde,tileImpl:Zde,topKImpl:Yde,transposeImpl:Jde,uniqueImpl:eAe}=Km,Qde=xr({opType:0,cpuKernelImpl:jde}),epe={kernelName:Fo,backendName:"webgpu",kernelFunc:Qde},tpe=Wr({opSnippet:1,cpuKernelImpl:wde,supportsComplex:!0}),rpe={kernelName:qn,backendName:"webgpu",kernelFunc:tpe},ape=class{constructor(e){this.workPerThread=4,this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e[0],this.variableNames=e.map((t,r)=>`T${r}`),this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.shaderKey="addN"}getUserCode(){let e=[];this.variableNames.forEach(r=>{e.push(`let v${r} = get${r}ByOutputCoords(coords);`)});let t=this.variableNames.map(r=>`v${r}`).join(" + ");return`
|
|
${Je()}
|
|
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 npe(e){let{inputs:t,backend:r}=e,a=t;if(a.length===1)return Va({inputs:{x:a[0]},backend:r});let n=a.map(o=>o.dtype).reduce((o,l)=>Or(o,l)),s=a.map(o=>o.shape),i=new ape(s);return r.runWebGPUProgram(i,a,n)}var spe={kernelName:js,backendName:"webgpu",kernelFunc:npe},L8=class{constructor(e,t,r){this.workGroupSize=[64,1,1],this.variableNames=["x"],this.uniforms="axis : i32; infinityValue : f32;",this.size=!0;let a=[t];N.assertAxesAreInnerMostDims("arg"+r.charAt(0).toUpperCase()+r.slice(1),a,e.length),this.op=r==="min"?"<":">";let[n]=N.computeOutAndReduceShapes(e,a);this.outputShape=n.length===0?[1]:n,this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,[1,1,1]),this.inputShape=e,this.shaderKey=`argMinMax${this.op}`}getUserCode(){let e=`
|
|
var<workgroup> xBestIndices : array<i32, ${this.workGroupSize[0]}>;
|
|
var<workgroup> xBestValues : array<f32, ${this.workGroupSize[0]}>;
|
|
`,t=(a,n)=>this.outputShape.length===1?a:`${a}[${n}]`,r=a=>this.inputShape.length===1?"uniforms.xShape":`uniforms.xShape[${a}]`;return`
|
|
fn DIV_CEIL(a : u32, b : u32) -> u32 {
|
|
return ((a - 1u) / b + 1u);
|
|
}
|
|
|
|
${e}
|
|
|
|
// In order to get a flattened index into the input tensor, we need to
|
|
// add back the index along the reduced dimension to |outputCoords|.
|
|
// This function outputs the offset to the first value along
|
|
// |axis| and the stride to get the next value of the input along |axis|.
|
|
fn getInputCoordInfo(outputIndex : i32) -> vec2<i32>{
|
|
let outputCoords = getCoordsFromIndex(outputIndex);
|
|
var i = ${this.outputShape.length-1};
|
|
|
|
var stride = 1;
|
|
var inputStride = 1;
|
|
var offset = 0;
|
|
|
|
for (var r = 1; r <= ${this.inputShape.length}; r = r + 1) {
|
|
let length = ${r(`${this.inputShape.length} - r`)};
|
|
if (${this.inputShape.length} - r == uniforms.axis) {
|
|
inputStride = stride;
|
|
} else {
|
|
offset = offset + ${t("outputCoords","i")} * stride;
|
|
i = i - 1;
|
|
}
|
|
stride = stride * length;
|
|
}
|
|
|
|
return vec2<i32>(offset, inputStride);
|
|
}
|
|
|
|
fn getInputIndex(coordInfo : vec2<i32>, index : i32) -> i32{
|
|
return coordInfo[0] + coordInfo[1] * index;
|
|
}
|
|
|
|
${Je()}
|
|
let outputIndex = index / i32(workGroupSizeX);
|
|
let coordInfo = getInputCoordInfo(outputIndex);
|
|
let Length = ${r("uniforms.axis")};
|
|
|
|
var bestIndex = i32(localId.x);
|
|
var bestValue = uniforms.infinityValue;
|
|
|
|
for (var k = i32(localId.x); k < Length && outputIndex < uniforms.size;
|
|
k = k + i32(workGroupSizeX)) {
|
|
let candidate = f32(x.numbers[getInputIndex(coordInfo, k)]);
|
|
if (!isNanCustom(candidate) && candidate ${this.op} bestValue) {
|
|
bestValue = candidate;
|
|
bestIndex = k;
|
|
}
|
|
}
|
|
xBestValues[localId.x] = bestValue;
|
|
xBestIndices[localId.x] = bestIndex;
|
|
workgroupBarrier();
|
|
|
|
var reduceSize = min(u32(Length), workGroupSizeX);
|
|
for (var currentSize = reduceSize / 2u; reduceSize > 1u;
|
|
currentSize = reduceSize / 2u) {
|
|
let interval = DIV_CEIL(reduceSize, 2u);
|
|
if (localId.x < currentSize) {
|
|
let candidate = xBestValues[localId.x + interval];
|
|
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]);
|
|
}
|
|
}
|
|
`}},ipe=class{constructor(e,t){this.variableNames=["A"],this.workGroupSize=[16,16,1];let r=new Array(e.length);for(let a=0;a<r.length;a++)r[a]=e[t[a]];this.outputShape=r,this.dispatchLayout={x:[0],y:[1]},this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize,[1,1,1]),this.shaderKey="transposeShared"}getUserCode(){return`
|
|
let TILE_DIM = ${this.workGroupSize[0]};
|
|
var<workgroup> tile : array<array<f32, ${this.workGroupSize[0]+1}>, ${this.workGroupSize[0]}>;
|
|
${Lx()}
|
|
fn main(@builtin(local_invocation_id) localId : vec3<u32>,
|
|
@builtin(workgroup_id) workgroupId : vec3<u32>) {
|
|
var x = i32(workgroupId.x) * TILE_DIM + i32(localId.x);
|
|
var y = i32(workgroupId.y) * TILE_DIM + i32(localId.y);
|
|
let width = uniforms.outShape[0];
|
|
let height = uniforms.outShape[1];
|
|
if (x < width && y < height) {
|
|
tile[localId.y][localId.x] =
|
|
A.numbers[y * width + x];
|
|
}
|
|
workgroupBarrier();
|
|
|
|
x = i32(workgroupId.y) * TILE_DIM + i32(localId.x);
|
|
y = i32(workgroupId.x) * TILE_DIM + i32(localId.y);
|
|
if (x < height && y < width) {
|
|
setOutputAtIndex((y * height + x), tile[localId.x]
|
|
[localId.y]);
|
|
}
|
|
}
|
|
`}},ope=class{constructor(e,t){this.variableNames=["A"],this.workPerThread=4,this.workGroupSize=[64,1,1],this.size=!0;let r=new Array(e.length);for(let a=0;a<r.length;a++)r[a]=e[t[a]];this.outputShape=r,this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.newDim=t,this.shaderKey=`transpose_${t}`}getUserCode(){let e=cr(this.outputShape.length),t=lpe(this.newDim);return`
|
|
${Je()}
|
|
|
|
for(var i = 0; i < ${this.workPerThread}; i = i + 1) {
|
|
let flatIndex = index * ${this.workPerThread} + i;
|
|
if(flatIndex < uniforms.size) {
|
|
let resRC = getCoordsFromIndex(flatIndex);
|
|
setOutputAtIndex(flatIndex, A.numbers[getIndexFromCoords${this.outputShape.length}D(
|
|
${e}(${t}), uniforms.aShape)]);
|
|
}
|
|
}
|
|
}
|
|
`}};function lpe(e){let t=e.length;if(t>4)throw Error(`Transpose for rank ${t} is not yet supported`);let r=new Array(t);for(let a=0;a<e.length;a++)r[e[a]]=`resRC[${a}]`;return r.join()}function Nl(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{perm:s}=a,i=r,o=n.shape.length,l=new Array(o);for(let u=0;u<l.length;u++)l[u]=n.shape[s[u]];if(r.shouldExecuteOnCPU([n])){let u=i.tensorMap.get(n.dataId).values,p=Jde(u,n.shape,n.dtype,s,l);return r.makeTensorInfo(l,n.dtype,p)}if(n.shape.length===2&&w.arraysEqual(s,[1,0])){let u=new ipe(n.shape,s);return i.runWebGPUProgram(u,[n],n.dtype)}let d=new ope(n.shape,s);return i.runWebGPUProgram(d,[n],n.dtype)}var upe={kernelName:Oi,backendName:"webgpu",kernelFunc:Nl};function dpe(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{axis:s}=a,i=w.parseAxisParam(s,n.shape),o=N.getAxesPermutation(i,n.shape.length),l=n,d=[];o!=null&&(l=Nl({inputs:{x:n},backend:r,attrs:{perm:o}}),d.push(l),i=N.getInnerMostAxes(i.length,l.shape.length)),N.assertAxesAreInnerMostDims("argMax",[i[0]],l.shape.length);let u=new L8(l.shape,i[0],"max"),p=[{type:"int32",data:[i[0]]},{type:"float32",data:[Number.NEGATIVE_INFINITY]}],h=r.runWebGPUProgram(u,[l],"int32",p);return d.forEach(c=>r.disposeData(c.dataId)),h}var ppe={kernelName:Hs,backendName:"webgpu",kernelFunc:dpe};function hpe(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{axis:s}=a,i=w.parseAxisParam(s,n.shape),o=N.getAxesPermutation(i,n.shape.length),l=n,d=[];o!=null&&(l=Nl({inputs:{x:n},backend:r,attrs:{perm:o}}),d.push(l),i=N.getInnerMostAxes(i.length,l.shape.length)),N.assertAxesAreInnerMostDims("argMin",[i[0]],l.shape.length);let u=new L8(l.shape,i[0],"min"),p=[{type:"int32",data:[i[0]]},{type:"float32",data:[Number.POSITIVE_INFINITY]}],h=r.runWebGPUProgram(u,[l],"int32",p);return d.forEach(c=>r.disposeData(c.dataId)),h}var cpe={kernelName:Ru,backendName:"webgpu",kernelFunc:hpe},B8=class{constructor(e,t){this.variableNames=["x"],this.uniforms="stride : vec2<i32>; pad : vec2<i32>; dilation : vec2<i32>; convDims : vec2<i32>; filterDims : vec2<i32>;",this.workGroupSize=[128,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`pool2D_${t}`,this.poolType=t}getUserCode(){let e="resultValue = max(value, resultValue);";this.poolType==="avg"&&(e="resultValue = resultValue + value; count = count + 1.0;");let t="resultValue";return this.poolType==="avg"&&(t="resultValue / count"),`
|
|
${Je()}
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let batch = coords[0];
|
|
let xRCCorner = vec2<i32>(coords.yz) * uniforms.stride - uniforms.pad;
|
|
let xRCorner = xRCCorner.x;
|
|
let xCCorner = xRCCorner.y;
|
|
|
|
var resultValue = ${this.poolType==="avg"?"0.0":"-1.0 / pow(10.0, -20.0)"};
|
|
var count = 0.0;
|
|
|
|
for (var wR = 0; wR < uniforms.filterDims.x; wR = wR + uniforms.dilation.x) {
|
|
let xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= uniforms.convDims.x) {
|
|
continue;
|
|
}
|
|
|
|
for (var wC = 0; wC < uniforms.filterDims.y; wC = wC + uniforms.dilation.y) {
|
|
let xC = xCCorner + wC;
|
|
if (xC < 0 || xC >= uniforms.convDims.y) {
|
|
continue;
|
|
}
|
|
|
|
let value = getX(batch, xR, xC, coords[3]);
|
|
${e}
|
|
}
|
|
}
|
|
|
|
setOutputAtIndex(index, ${t});
|
|
}
|
|
}
|
|
`}},W8=class{constructor(e){this.variableNames=["x"],this.uniforms="stride : vec2<i32>;",this.workGroupSize=[256,1,1],this.size=!0,this.outputShape=e.outShape,this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="poolWithFilterSizeEqualsOne"}getUserCode(){return`
|
|
${Je()}
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let batch = coords[0];
|
|
let d = coords[3];
|
|
|
|
let xRCCorner = coords.yz * uniforms.stride;
|
|
let xRCorner = xRCCorner.x;
|
|
let xCCorner = xRCCorner.y;
|
|
|
|
let value = getX(batch, xRCorner, xCCorner, d);
|
|
setOutputAtIndex(index, value);
|
|
}
|
|
}
|
|
`}};function fpe(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,d=1,u=N.computePool2DInfo(n.shape,s,i,d,o,l);if(u.filterWidth===1&&u.filterHeight===1&&w.arraysEqual(u.inShape,u.outShape))return Va({inputs:{x:n},backend:r});let p,h=[{type:"int32",data:[u.strideHeight,u.strideWidth]}];return u.filterHeight===1&&u.filterWidth===1?p=new W8(u):(p=new B8(u,"avg"),h.push({type:"int32",data:[u.padInfo.top,u.padInfo.left]},{type:"int32",data:[u.dilationHeight,u.dilationWidth]},{type:"int32",data:[u.inHeight,u.inWidth]},{type:"int32",data:[u.effectiveFilterHeight,u.effectiveFilterWidth]})),r.runWebGPUProgram(p,[n],n.dtype,h)}var mpe={kernelName:qs,backendName:"webgpu",kernelFunc:fpe};function gpe(e){let{inputs:t,backend:r,attrs:a}=e,{a:n,b:s}=t,{transposeA:i,transposeB:o}=a;return Gx({a:n,b:s,transposeA:i,transposeB:o,backend:r})}var ype={kernelName:Ks,backendName:"webgpu",kernelFunc:gpe},Ape=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=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.start=e,this.uniforms=`start : ${cr(e.length)}; `,this.shaderKey="slice"}getUserCode(){let e=cr(this.rank),t=xpe(this.rank),r;return this.start.length===1?r=this.outputShape.map((a,n)=>"sourceLoc = uniforms.start + coords;"):r=this.outputShape.map((a,n)=>`sourceLoc.${Sy[n]} = uniforms.start[${n}] + coords.${Sy[n]};`),`
|
|
${Je()}
|
|
if (index < uniforms.size) {
|
|
var sourceLoc : ${e};
|
|
let coords = getCoordsFromIndex(index);
|
|
${r.join(`
|
|
`)}
|
|
setOutputAtIndex(index, getSource(${t}));
|
|
}
|
|
}
|
|
`}},Sy=["x","y","z","w","u","v"];function xpe(e){if(e===1)return"sourceLoc";if(e<=6)return Sy.slice(0,e).map(t=>`sourceLoc.${t}`).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}function bd(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{begin:s,size:i}=a,[o,l]=Ot.parseSliceParams(n,s,i);if(Ot.assertParamsValid(n,o,l),r.shouldExecuteOnCPU([n])||n.dtype==="string"){let p=r.tensorMap.get(n.dataId),h=Hde(p.values,o,l,n.shape,n.dtype);return r.makeTensorInfo(l,n.dtype,h)}if(w.sizeFromShape(l)===0)return r.makeTensorInfo(l,n.dtype,[]);let d=new Ape(o,l),u=[{type:"int32",data:o}];return r.runWebGPUProgram(d,[n],n.dtype,u)}var bpe={kernelName:il,backendName:"webgpu",kernelFunc:bd},vpe=e=>{let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{blockShape:s,crops:i}=a;w.assert(n.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGPU backend not implemented yet");let o=s.reduce((A,x)=>A*x),l=N.getReshaped(n.shape,s,o),d=N.getPermuted(l.length,s.length),u=N.getReshapedPermuted(n.shape,s,o),p=N.getSliceBeginCoords(i,s.length),h=N.getSliceSize(u,i,s.length),c=[],f=Ge({inputs:{x:n},backend:r,attrs:{shape:l}}),m=Nl({inputs:{x:f},backend:r,attrs:{perm:d}}),g=Ge({inputs:{x:m},backend:r,attrs:{shape:u}}),y=bd({inputs:{x:g},backend:r,attrs:{begin:p,size:h}});return c.push(f),c.push(m),c.push(g),c.forEach(A=>r.disposeData(A.dataId)),y},wpe={kernelName:Mo,backendName:"webgpu",kernelFunc:vpe},V8=Wr({opSnippet:10,dtype:"bool",cpuKernelImpl:Wde}),kpe={kernelName:Ko,backendName:"webgpu",kernelFunc:V8};function Ph(e){let{inputs:t,backend:r}=e,{input:a}=t,n=r.tensorMap.get(a.dataId);return Va({inputs:{x:n.complexTensorInfos.real},backend:r})}var Ipe={kernelName:Kp,backendName:"webgpu",kernelFunc:Ph};function Spe(e,t){let r=new $h(e.shape,23),a=t.runWebGPUProgram(r,[e],"int32");return{dataId:a.dataId,shape:a.shape,dtype:a.dtype}}function Ty(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{dtype:s}=a;if(s==="complex64"){if(n.dtype==="complex64")return Va({inputs:{x:n},backend:r});let i=Vt(n.shape),o=Ty({inputs:{x:n},backend:r,attrs:{dtype:"float32"}}),l=xd({inputs:{real:o,imag:i},backend:r});return i.dispose(),r.disposeData(o.dataId),l}if(n.dtype==="complex64"){let i=Ph({inputs:{input:n},backend:r}),o=Ty({inputs:{x:i},backend:r,attrs:{dtype:s}});return r.disposeData(i.dataId),o}if(!w.hasEncodingLoss(n.dtype,s)){let i=Va({inputs:{x:n},backend:r});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(s==="int32")return Spe(n,r);if(s==="bool"){let i=r.makeTensorInfo([],"bool",w.getTypedArrayFromDType("bool",1)),o=V8({inputs:{a:n,b:i},backend:r});return r.disposeData(i.dataId),o}throw new Error(`Error in Cast: failed to cast ${n.dtype} to ${s}`)}var Tpe={kernelName:Xs,backendName:"webgpu",kernelFunc:Ty},Cpe=xr({opType:1,cpuKernelImpl:kde}),Npe={kernelName:Zs,backendName:"webgpu",kernelFunc:Cpe},Epe=class{constructor(e){this.variableNames=["A"],this.uniforms="minVal : f32; maxVal : f32;",this.workPerThread=4,this.workGroupSize=[64,1,1],this.isVec4=!0,this.size=!0,this.outputShape=e,this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.shaderKey="clipVec4"}getUserCode(){return`
|
|
${Je()}
|
|
if(index < uniforms.size) {
|
|
let value = getAByOutputIndex(index);
|
|
var clampedValue : vec4<f32>;
|
|
for (var i = 0; i < 4; i = i + 1) {
|
|
if (isNanCustom(value[i])) {
|
|
clampedValue[i] = value[i];
|
|
} else {
|
|
clampedValue[i] = clamp(value[i], uniforms.minVal, uniforms.maxVal);
|
|
}
|
|
}
|
|
|
|
setOutputAtIndex(index, clampedValue);
|
|
}
|
|
}
|
|
`}},Rpe=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=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="clip"}getUserCode(){return`
|
|
${Je()}
|
|
if(index < uniforms.size) {
|
|
let value = getAByOutputIndex(index);
|
|
if (isNanCustom(value)) {
|
|
setOutputAtIndex(index, value);
|
|
return;
|
|
}
|
|
setOutputAtIndex(index, clamp(value, uniforms.minVal, uniforms.maxVal));
|
|
}
|
|
}
|
|
`}};function Fpe(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{clipValueMin:s,clipValueMax:i}=a,o,l=[{type:"float32",data:[s]},{type:"float32",data:[i]}];return w.sizeFromShape(n.shape)%4===0?o=new Epe(n.shape):o=new Rpe(n.shape),r.runWebGPUProgram(o,[n],n.dtype,l)}var Mpe={kernelName:Kn,backendName:"webgpu",kernelFunc:Fpe},$pe=class{constructor(e){this.uniforms="",this.workPerThread=4,this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=N.computeOutShape(e,1),this.variableNames=e.map((t,r)=>`T${r}`),this.dispatchLayout=He(this.outputShape),this.dispatch=ze(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 a=1;a<this.offsetLength;a++)e.push(`else if (yC < uniforms.offset${[a]}){ setOutputAtCoords(coords.x, coords.y, getT${a}(yR, yC - uniforms.offset${a-1})); }`);let t=this.offsetLength,r=this.offsetLength-1;e.push(`else { setOutputAtCoords(coords.x, coords.y, getT${t}(yR, yC - uniforms.offset${r})); }`)}else e.push("setOutputAtCoords(coords.x, coords.y, getT0(yR, yC));");return`
|
|
${Je()}
|
|
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:r}=e,{input:a}=t,n=r.tensorMap.get(a.dataId);return Va({inputs:{x:n.complexTensorInfos.imag},backend:r})}var Ppe={kernelName:Gp,backendName:"webgpu",kernelFunc:a0};function Cy(e,t,r){let a=e[0].dtype;if(a==="complex64"){let c=e.map(A=>Ph({inputs:{input:A},backend:r})),f=e.map(A=>a0({inputs:{input:A},backend:r})),m=Cy(c,t,r),g=Cy(f,t,r),y=xd({inputs:{real:m,imag:g},backend:r});return c.forEach(A=>r.disposeData(A.dataId)),f.forEach(A=>r.disposeData(A.dataId)),r.disposeData(m.dataId),r.disposeData(g.dataId),y}let n=r.shouldExecuteOnCPU(e);if(a==="string"&&(n=!0),n){let c=e.map(b=>{let v=w.sizeFromShape(b.shape.slice(t));return Ge({inputs:{x:b},backend:r,attrs:{shape:[-1,v]}})}),f=c.map(b=>({vals:r.readSync(b.dataId),shape:b.shape})),m=N.computeOutShape(c.map(b=>b.shape),1),g=c[0].shape[0]===1,y=Ide(f,m,a,g),A=N.computeOutShape(e.map(b=>b.shape),t),x=r.makeTensorInfo(A,a,y);return c.forEach(b=>r.disposeData(b.dataId)),x}let{tensors2D:s,outShape:i}=Ope(e,t,r),o=s.map(c=>c.shape),l=new $pe(o),d=[],u=new Array(o.length-1);if(u.length>0){u[0]=o[0][1],d.push({type:"int32",data:[u[0]]});for(let c=1;c<u.length;c++)u[c]=u[c-1]+o[c][1],d.push({type:"int32",data:[u[c]]})}let p=r.runWebGPUProgram(l,s,s[0].dtype,d);s.forEach(c=>r.disposeData(c.dataId));let h=Ge({inputs:{x:p},backend:r,attrs:{shape:i}});return r.disposeData(p.dataId),h}function Ope(e,t,r){let a=N.computeOutShape(e.map(n=>n.shape),t);return{tensors2D:e.map(n=>Ge({inputs:{x:n},backend:r,attrs:{shape:[w.sizeFromShape(n.shape.slice(0,t)),w.sizeFromShape(n.shape.slice(t))]}})),outShape:a}}function U8(e){let{inputs:t,backend:r,attrs:a}=e,{axis:n}=a,s=w.parseAxisParam(n,t[0].shape)[0],i=N.computeOutShape(t.map(d=>d.shape),s);if(w.sizeFromShape(i)===0)return r.makeTensorInfo(i,t[0].dtype,[]);let o=t.filter(d=>w.sizeFromShape(d.shape)>0);if(o.length===1)return Va({inputs:{x:o[0]},backend:r});let l=o.map(d=>d.shape);return N.assertParamsConsistent(l,s),Cy(o,s,r)}var zpe={kernelName:$o,backendName:"webgpu",kernelFunc:U8},Dpe=class{constructor(e,t){this.variableNames=["A"],this.uniforms=`pad : vec2<i32>; stride : vec2<i32>; dilation : vec2<i32>; outWidth : i32; itemsPerBlockRow : i32;
|
|
inChannels : i32;`,this.workPerThread=4,this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.isChannelsLast=t,this.shaderKey=`im2col_${this.isChannelsLast}`}getUserCode(){let e=this.isChannelsLast?0:1,t=this.isChannelsLast?1:2;return`
|
|
${Je()}
|
|
|
|
for(var i = 0; i<${this.workPerThread}; i = i + 1) {
|
|
let flatIndex = index * ${this.workPerThread} + i;
|
|
|
|
let rc = getCoordsFromIndex(flatIndex);
|
|
|
|
if(flatIndex < uniforms.size) {
|
|
let blockIndex = rc[0];
|
|
let pos = rc[1];
|
|
|
|
let offsetY = blockIndex / uniforms.outWidth * uniforms.stride[1] - uniforms.pad[1];
|
|
let d0 = offsetY + uniforms.dilation[1] * pos / uniforms.itemsPerBlockRow;
|
|
var value = 0.0;
|
|
if(d0 < uniforms.aShape[${e}] && d0 >= 0) {
|
|
let offsetX = (blockIndex % uniforms.outWidth) * uniforms.stride[0] -
|
|
uniforms.pad[0];
|
|
let d1 = offsetX + uniforms.dilation[0] * ((pos %
|
|
uniforms.itemsPerBlockRow) / uniforms.inChannels);
|
|
let ch = pos % uniforms.inChannels;
|
|
if(d1 < uniforms.aShape[${t}] && d1 >= 0) {
|
|
value = getA(d0, d1, ch);
|
|
}
|
|
}
|
|
setOutputAtIndex(flatIndex, value);
|
|
}
|
|
}
|
|
}
|
|
`}},_pe=class{constructor(e,t=!1,r=null,a=!1,n=!1){this.variableNames=["x","W"],this.uniforms=`filterDims : vec2<i32>; pad : vec2<i32>; stride : vec2<i32>; dilation : vec2<i32>;
|
|
dimAOuter : i32; dimBOuter : i32; dimInner : i32;`,this.workGroupSize=[8,8,1],this.isVec4=!0,this.outputShape=e.outShape,w.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),this.dispatchLayout={x:[3],y:[1,2],z:[0]},this.outputShape[1]===1?this.elementsPerThread=[4,1,1]:this.elementsPerThread=[4,4,1],this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize,this.elementsPerThread),this.convInfo=e,this.addBias=t,this.activation=r,this.hasPreluActivationWeights=a,this.hasLeakyreluAlpha=n,this.addBias&&this.variableNames.push("bias"),this.hasPreluActivationWeights&&this.variableNames.push("preluActivationWeights"),this.hasLeakyreluAlpha&&this.variableNames.push("leakyreluAlpha"),this.tileAOuter=this.outputShape[1]===1?1:this.workGroupSize[1]*this.elementsPerThread[1],this.tileBOuter=this.workGroupSize[0]*this.elementsPerThread[0],this.tileInner=this.tileBOuter,[this.fitA,this.fitB]=this.getShapeFit(),this.shaderKey=`conv2DMMVec4_${this.activation}_${this.fitA}_${this.fitB}_${this.elementsPerThread}`}getShapeFit(){let e=[this.tileAOuter,this.tileInner],t=[this.tileInner,this.tileBOuter],r=this.outputShape[1]*this.outputShape[2],a=this.outputShape[3],n=this.convInfo.filterHeight*this.convInfo.filterWidth*this.convInfo.inChannels;return[Hn(e,[r,n]),Hn(t,[n,a])]}getSampleAWithRemainder(e){return`let flatIndex${e} = getIndexFromCoords4D(coord, uniforms.xShape);
|
|
let divBy4Remainder${e} = flatIndex${e} % 4;
|
|
let divBy4Index${e} = flatIndex${e} / 4;
|
|
let curData${e} = x.numbers[divBy4Index${e}];
|
|
if (divBy4Remainder${e} == 0) {
|
|
temp = curData${e};
|
|
} else {
|
|
// TODO: This could end up being a redundant load with another one in
|
|
// the same shader invocation. Perhaps there's an opportunity for
|
|
// optimization
|
|
let nextData${e} = x.numbers[divBy4Index${e} + 1];
|
|
if (divBy4Remainder${e} == 1) {
|
|
temp = vec4<f32>(curData${e}.yzw, nextData${e}.x);
|
|
} else if (divBy4Remainder${e} == 2) {
|
|
temp = vec4<f32>(curData${e}.zw, nextData${e}.xy);
|
|
} else if (divBy4Remainder${e} == 3) {
|
|
temp = vec4<f32>(curData${e}.w, nextData${e}.xyz);
|
|
}
|
|
}
|
|
`}getUserCode(){let e=z8(this.elementsPerThread,this.tileAOuter,this.tileBOuter,this.tileInner),t=`let outRow = r / uniforms.outShape[2];
|
|
let outCol = r % uniforms.outShape[2];
|
|
let WRow = c / (uniforms.filterDims[1] * uniforms.xShape[3]);
|
|
let WCol = c / uniforms.xShape[3] % uniforms.filterDims[1];
|
|
let inChCoord = c % uniforms.xShape[3];
|
|
var coord = vec4<i32>(
|
|
batch,
|
|
outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0],
|
|
outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1],
|
|
inChCoord);
|
|
var resData = vec4<f32>(0.0);
|
|
${this.convInfo.inChannels%4===0?`// The bounds checking is always needed since we use it to pad zero for
|
|
// the 'same' padding type.
|
|
if (coordsInBounds4D(coord, uniforms.xShape)) {
|
|
resData = x.numbers[getIndexFromCoords4D(coord, uniforms.xShape) / 4];
|
|
} else {
|
|
resData = vec4<f32>(0.0); }`:`var temp = vec4<f32>(0.0);
|
|
${this.getSampleAWithRemainder(1)}
|
|
resData = temp;
|
|
if (WCol == (uniforms.filterDims[1] - 1)) {
|
|
coord = vec4<i32>(
|
|
coord.x, coord.y + 1, coord.z + 1 - uniforms.filterDims[1], 0);
|
|
${this.getSampleAWithRemainder(2)}
|
|
if (inChCoord == 0) {
|
|
resData = vec4<f32>(resData.xyz, temp.x);
|
|
} else if (inChCoord == 1) {
|
|
resData = vec4<f32>(resData.xy, temp.xy);
|
|
} else {
|
|
resData = vec4<f32>(resData.x, temp.xyz);
|
|
}
|
|
}
|
|
`}
|
|
return resData;`,r=this.fitA?`${t}`:`if (r < uniforms.dimAOuter && c < uniforms.dimInner) {
|
|
${t}
|
|
}
|
|
return vec4<f32>(0.0);
|
|
`,a=this.fitB?"return W.numbers[row * uniforms.dimBOuter / 4 + col];":`if(coordsInBounds2D(vec2<i32>(row, col * 4), vec2<i32>(uniforms.dimInner, uniforms.dimBOuter))) {
|
|
return W.numbers[row * uniforms.dimBOuter / 4 + col];
|
|
}
|
|
return vec4<f32>(0.0);
|
|
`,n="",s="";if(this.activation){let o=ts(this.activation,this.isVec4);if(this.hasPreluActivationWeights)n=`fn activation(a : vec4<f32>, outCoord : vec4<i32>) -> vec4<f32> {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${o}
|
|
}`;else{if(this.hasLeakyreluAlpha)throw n=`fn activation(outCoord: vec4<f32>) -> vec4<f32> {
|
|
let b = getLeakyreluAlphaByOutputCoords(outCoord);
|
|
${o}
|
|
}`,new Error("Leakyrelu is not supported.");n=`
|
|
fn activation(a : vec4<f32>, outCoord : vec4<i32>) -> vec4<f32> {
|
|
${o}
|
|
}`}s="value = activation(value, outCoord);"}let i=this.addBias?"value = value + getBiasByOutputCoords(outCoord);":"";return`
|
|
${n}
|
|
fn mm_readA(row : i32, col : i32, globalId : vec3<u32>) -> vec4<f32> {
|
|
let r = row;
|
|
let c = col * 4;
|
|
var batch = i32(globalId.z);
|
|
${r}
|
|
}
|
|
|
|
fn mm_readB(row : i32, col : i32, globalId : vec3<u32>) -> vec4<f32> {
|
|
${a}
|
|
}
|
|
|
|
fn mm_write(row : i32, col : i32, valueInput : vec4<f32>, globalId : vec3<u32>) {
|
|
var batch = i32(globalId.z);
|
|
var value = valueInput;
|
|
if (row < uniforms.dimAOuter && col * 4 < uniforms.dimBOuter)
|
|
{
|
|
let outCoord = vec4<i32>(
|
|
batch,
|
|
row / uniforms.outShape[2],
|
|
row % uniforms.outShape[2],
|
|
col * 4);
|
|
${i}
|
|
${s}
|
|
setOutputAtCoords(outCoord[0], outCoord[1], outCoord[2], outCoord[3],
|
|
value);
|
|
}
|
|
}
|
|
${e}
|
|
`}},Lpe=class{constructor(e,t=!1,r=null,a=!1){this.variableNames=["x","W"],this.uniforms="filterDims : vec2<i32>; pad : vec2<i32>; stride : vec2<i32>; dilation : vec2<i32>; dimAOuter : i32; dimBOuter : i32; dimInner : i32;",this.outputShape=e.outShape,w.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),this.dispatchLayout={x:[3],y:[1,2],z:[0]},this.workGroupSize=Bx(this.dispatchLayout,this.outputShape),this.elementsPerThread=Wx(this.dispatchLayout,this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize,this.elementsPerThread),t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=r,this.hasPreluActivationWeights=a,[this.fitA,this.fitB]=this.getShapeFit(),this.shaderKey=`conv2DMM_${this.elementsPerThread}_${this.activation}_${this.fitA}_${this.fitB}`}getShapeFit(){let e=this.workGroupSize[1]*this.elementsPerThread[1],t=this.workGroupSize[0]*this.elementsPerThread[0],r=e>t?e:t;w.assert(r%this.workGroupSize[0]===0&&r%this.workGroupSize[1]===0,()=>"tileInner must be multiple of workgroupsize.x and workgroupsize.y");let a=[e,r],n=[r,t],s=this.outputShape[1]*this.outputShape[2],i=this.outputShape[3],o=this.convInfo.filterHeight*this.convInfo.filterWidth*this.convInfo.inChannels;return[Hn(a,[s,o]),Hn(n,[o,i])]}getUserCode(){let e=Ux(this.elementsPerThread,this.workGroupSize),t=`
|
|
let outRow = row / uniforms.outShape[2];
|
|
let outCol = row % uniforms.outShape[2];
|
|
|
|
let WRow = col / (uniforms.filterDims[1] * uniforms.xShape[3]);
|
|
let WCol = col / uniforms.xShape[3] % uniforms.filterDims[1];
|
|
let coord = vec4<i32>(
|
|
batch,
|
|
outRow * uniforms.stride[0] + uniforms.dilation[0] * WRow - uniforms.pad[0],
|
|
outCol * uniforms.stride[1] + uniforms.dilation[1] * WCol - uniforms.pad[1],
|
|
col % uniforms.xShape[3]);
|
|
// The bounds checking is always needed since we use it to pad zero for the
|
|
// 'same' padding type.
|
|
if(coordsInBounds4D(coord, uniforms.xShape)) {
|
|
return x.numbers[getIndexFromCoords4D(coord, uniforms.xShape)];
|
|
}
|
|
return 0.0;`,r=this.fitA?`${t}`:`if (row < uniforms.dimAOuter && col < uniforms.dimInner) {
|
|
${t}
|
|
}
|
|
return 0.0;
|
|
`,a=this.fitB?"return W.numbers[row * uniforms.dimBOuter + col];":`if(coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimInner, uniforms.dimBOuter))) {
|
|
return W.numbers[row * uniforms.dimBOuter + col];
|
|
}
|
|
return 0.0;
|
|
`,n="",s="";if(this.activation){let o=ts(this.activation,!1);this.hasPreluActivationWeights?n=`fn activation(a: f32, outCoord : vec4<i32>) -> f32 {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${o}
|
|
}`:n=`
|
|
fn activation(a : f32, outCoord : vec4<i32>) -> f32 {
|
|
${o}
|
|
}
|
|
`,s="value = activation(value, outCoord);"}let i=this.addBias?"value = value + getBiasByOutputCoords(outCoord);":"";return`
|
|
${n}
|
|
fn mm_readA(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
|
|
var batch = i32(globalId.z);
|
|
${r}
|
|
}
|
|
|
|
fn mm_readB(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
|
|
${a}
|
|
}
|
|
|
|
fn mm_write(row : i32, col : i32, valueInput : f32, globalId : vec3<u32>) {
|
|
var batch = i32(globalId.z);
|
|
var value = valueInput;
|
|
let outCoord = vec4<i32>(
|
|
batch,
|
|
row / uniforms.outShape[2],
|
|
row % uniforms.outShape[2],
|
|
col);
|
|
${i}
|
|
${s}
|
|
result.numbers[getIndexFromCoords4D(outCoord, uniforms.outShape)] = value;
|
|
}
|
|
${e}
|
|
`}},Bpe=class{constructor(e,t=!1,r=null,a=!1){this.variableNames=["x","W"],this.uniforms="filterDims : vec2<i32>; pad : vec2<i32>; stride : vec2<i32>; dilation : vec2<i32>;",this.workGroupSize=[128,1,1],this.outputShape=e.outShape,this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),w.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=r,this.hasPreluActivationWeights=a,this.shaderKey=`conv2DNaive_${this.activation}`}getUserCode(){let e="",t="";if(this.activation){let a=ts(this.activation);this.hasPreluActivationWeights?e=`fn activation(a : f32, outCoord : vec4<i32>) -> f32{
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${a}
|
|
}`:e=`
|
|
fn activation(a : f32, outCoord : vec4<i32>) -> f32{
|
|
${a}
|
|
}
|
|
`,t="value = activation(value, outCoord);"}let r=this.addBias?"value = value + getBiasByOutputCoords(outCoord);":"";return`
|
|
${e}
|
|
fn readInp(batch : i32, row : i32, col : i32, chan : i32) -> f32 {
|
|
let coord = vec4<i32>(batch, row, col, chan);
|
|
if(coordsInBounds4D(coord, uniforms.xShape)) {
|
|
return getX(batch, row, col, chan);
|
|
}
|
|
return 0.0;
|
|
}
|
|
|
|
fn readFilt(row : i32, col : i32, xChannel : i32, outChannel : i32) -> f32{
|
|
let coord = vec4<i32>(row, col, xChannel, outChannel);
|
|
if(coordsInBounds4D(coord, uniforms.wShape)) {
|
|
return getW(row, col, xChannel, outChannel);
|
|
}
|
|
return 0.0;
|
|
}
|
|
|
|
fn writeResult(batch : i32, row : i32, col : i32, chan : i32, value : f32) {
|
|
let coord = vec4<i32>(batch, row, col, chan);
|
|
if (coordsInBounds4D(coord, uniforms.outShape)) {
|
|
${r}
|
|
${t}
|
|
setOutputAtCoords(batch, row, col, chan, value);
|
|
}
|
|
}
|
|
|
|
${Wi()}
|
|
let coords = getOutputCoords();
|
|
let batch = coords[0];
|
|
let outChannel = coords[3];
|
|
|
|
var acc = 0.0;
|
|
|
|
for (var row = 0; row < uniforms.filterDims[0]; row = row + 1) {
|
|
for (var col = 0; col < uniforms.filterDims[1]; col = col + 1) {
|
|
for (var xChannel = 0; xChannel < uniforms.xShape[3]; xChannel = xChannel + 1) {
|
|
let coordRow = coords[1] * uniforms.stride[0] + uniforms.dilation[0] * row - uniforms.pad[0];
|
|
let coordCol = coords[2] * uniforms.stride[1] + uniforms.dilation[1] * col - uniforms.pad[1];
|
|
let v = readInp(batch, coordRow, coordCol, xChannel);
|
|
let f = readFilt(row, col, xChannel, outChannel);
|
|
acc = acc + v * f;
|
|
}
|
|
}
|
|
}
|
|
|
|
writeResult(batch, coords[1], coords[2], outChannel, acc);
|
|
}
|
|
`}};function Wpe({x:e,filter:t,convInfo:r,backend:a,bias:n=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let l=e.shape,d=r.dataFormat==="channelsLast",u=!1,p=!1,h=r.filterHeight===r.inHeight&&r.filterWidth===r.inWidth&&r.padInfo.type==="VALID",c,f;if(h){let y=r.inHeight*r.inWidth*r.inChannels;c=Ge({inputs:{x:e},backend:a,attrs:{shape:[1,r.batchSize,y]}}),f=Ge({inputs:{x:t},backend:a,attrs:{shape:[1,y,r.outChannels]}})}else{let y=d?l[0]*l[1]*l[2]:l[0]*l[2]*l[3];c=Ge({inputs:{x:e},backend:a,attrs:{shape:[1,y,r.inChannels]}}),f=Ge({inputs:{x:t},backend:a,attrs:{shape:[1,r.inChannels,r.outChannels]}})}let m=Gx({a:c,b:f,transposeA:u,transposeB:p,backend:a,bias:n,activation:o,preluActivationWeights:s,leakyreluAlpha:i}),g=Ge({inputs:{x:m},backend:a,attrs:{shape:r.outShape}});return a.disposeData(c.dataId),a.disposeData(f.dataId),a.disposeData(m.dataId),g}function Vpe({x:e,filter:t,convInfo:r,backend:a,bias:n=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let{filterWidth:l,filterHeight:d,inChannels:u,strideWidth:p,strideHeight:h,padInfo:c,outWidth:f,outHeight:m,dilationWidth:g,dilationHeight:y,dataFormat:A}=r,x=A==="channelsLast",b=l*d*u,v=m*f,C=[v,b],T=!1,E=!1,R=[],z=Ge({inputs:{x:e},backend:a,attrs:{shape:e.shape.slice(1)}}),M=Ge({inputs:{x:t},backend:a,attrs:{shape:[1,b,-1]}});R.push(z),R.push(M);let I=new Dpe(C,x),D=[{type:"int32",data:[c.left,c.top]},{type:"int32",data:[p,h]},{type:"int32",data:[g,y]},{type:"int32",data:[f]},{type:"int32",data:[u*l]},{type:"int32",data:[u]}],O=a.runWebGPUProgram(I,[z],z.dtype,D),j=Ge({inputs:{x:O},backend:a,attrs:{shape:[1,C[0],C[1]]}});R.push(O),R.push(j);let X=[1,C[0],C[1]],_=new D8(X,[1,v,r.outChannels],Y().get("WEBGPU_MATMUL_WORK_PER_THREAD"),T,E,n,o,s),K=X[1],W=X[2],ee=r.outChannels,Q=[{type:"int32",data:[K]},{type:"int32",data:[ee]},{type:"int32",data:[W]}],ne=[j,M];n&&ne.push(n),s&&ne.push(s);let Z=a.runWebGPUProgram(_,ne,j.dtype,Q),ae=x?[1,m,f,r.outChannels]:[1,r.outChannels,m,f],ie=Ge({inputs:{x:Z},backend:a,attrs:{shape:ae}});R.push(Z);for(let xe of R)a.disposeData(xe.dataId);return ie}function G8({x:e,filter:t,convInfo:r,backend:a,bias:n=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let l=n!=null,d=s!=null,u;if(r.filterHeight===r.inHeight&&r.filterWidth===r.inWidth&&r.padInfo.type==="VALID"||r.filterHeight===1&&r.filterWidth===1&&r.dilationHeight===1&&r.dilationWidth===1&&r.strideHeight===1&&r.strideWidth===1&&(r.padInfo.type==="SAME"||r.padInfo.type==="VALID"))return Wpe({x:e,filter:t,convInfo:r,backend:a,bias:n,activation:o,preluActivationWeights:s,leakyreluAlpha:i});if(Y().getBool("WEBGPU_CONV_SEPARATE_IM2COL_SHADER")&&e.shape[0]===1)return Vpe({x:e,filter:t,convInfo:r,backend:a,bias:n,preluActivationWeights:s,leakyreluAlpha:i,activation:o});let p=Y().getBool("WEBGPU_USE_NAIVE_CONV2D"),h=(r.inChannels%4===0||r.inChannels===3&&r.padInfo.type==="VALID")&&r.outChannels%4===0&&r.outChannels>=32,c=[r.padInfo.top,r.padInfo.left],f=[{type:"int32",data:[r.filterHeight,r.filterWidth]},{type:"int32",data:[...c]},{type:"int32",data:[r.strideHeight,r.strideWidth]},{type:"int32",data:[r.dilationHeight,r.dilationWidth]}];if(p)u=new Bpe(r,l,o,d);else{h?u=new _pe(r,l,o,d):u=new Lpe(r,l,o,d);let g=r.outShape[1]*r.outShape[2],y=r.outShape[3],A=r.filterHeight*r.filterWidth*r.inShape[3];f.push({type:"int32",data:[g]},{type:"int32",data:[y]},{type:"int32",data:[A]})}let m=[e,t];return l&&m.push(n),d&&m.push(s),a.runWebGPUProgram(u,m,e.dtype,f)}function Upe(e){let{inputs:t,attrs:r,backend:a}=e,{x:n,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:d,dimRoundingMode:u}=r,p=N.convertConv2DDataFormat(l),h=N.computeConv2DInfo(n.shape,s.shape,i,d,o,u,!1,p);return G8({x:n,filter:s,convInfo:h,backend:a})}var Gpe={kernelName:Ys,backendName:"webgpu",kernelFunc:Upe},jpe=class{constructor(e){this.variableNames=["x","W"],this.uniforms="filterDims : vec2<i32>; pads : vec2<i32>; stride : vec2<i32>; outBackprop : vec4<i32>; dimAOuter : i32; dimBOuter : i32; dimInner : i32;",this.outputShape=e.inShape,w.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),this.dispatchLayout={x:[3],y:[1,2],z:[0]},this.workGroupSize=Bx(this.dispatchLayout,this.outputShape),this.elementsPerThread=Wx(this.dispatchLayout,this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize,this.elementsPerThread),this.shaderKey=`conv2DDerInputMM_${this.elementsPerThread}`}getUserCode(){return`
|
|
fn mm_readA(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
|
|
var batch = i32(globalId.z);
|
|
if (row < uniforms.dimAOuter && col < uniforms.dimInner) {
|
|
|
|
let outRow = row / uniforms.outShape[2];
|
|
let outCol = row % uniforms.outShape[2];
|
|
|
|
let WRow = col / (uniforms.filterDims[1] * uniforms.outBackprop[3]);
|
|
let WCol = col / uniforms.outBackprop[3] % uniforms.filterDims[1];
|
|
let xR = f32(outRow - uniforms.pads[0] + WRow) / f32(uniforms.stride[0]);
|
|
let xC = f32(outCol - uniforms.pads[1] + WCol) / f32(uniforms.stride[1]);
|
|
if (xR < 0.0 || xR >= f32(uniforms.outBackprop[1]) || fract(xR) > 0.0) {
|
|
return 0.0;
|
|
}
|
|
if (xC < 0.0 || xC >= f32(uniforms.outBackprop[2]) || fract(xC) > 0.0) {
|
|
return 0.0;
|
|
}
|
|
let coord = vec4<i32>(
|
|
batch,
|
|
i32(xR),
|
|
i32(xC),
|
|
col % uniforms.outBackprop[3]);
|
|
return x.numbers[getIndexFromCoords4D(coord, uniforms.xShape)];
|
|
}
|
|
return 0.0;
|
|
}
|
|
|
|
fn mm_readB(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
|
|
let coordX = uniforms.filterDims.x - 1 -
|
|
row / (uniforms.filterDims[1] * uniforms.outBackprop[3]);
|
|
let coordY = uniforms.filterDims.y - 1 -
|
|
(row / uniforms.outBackprop[3]) % uniforms.filterDims[1];
|
|
if (row < uniforms.dimInner && col < uniforms.dimBOuter &&
|
|
coordX >= 0 && coordY >= 0) {
|
|
let coord = vec4<i32>(coordX, coordY, col,
|
|
row % uniforms.outBackprop[3]);
|
|
return W.numbers[getIndexFromCoords4D(coord, uniforms.wShape)];
|
|
}
|
|
return 0.0;
|
|
}
|
|
|
|
fn mm_write(row : i32, col : i32, valueInput : f32, globalId : vec3<u32>) {
|
|
var batch = i32(globalId.z);
|
|
var value = valueInput;
|
|
let outCoord = vec4<i32>(
|
|
batch,
|
|
row / uniforms.outShape[2],
|
|
row % uniforms.outShape[2],
|
|
col);
|
|
result.numbers[getIndexFromCoords4D(outCoord, uniforms.outShape)] = value;
|
|
}
|
|
|
|
${Ux(this.elementsPerThread,this.workGroupSize)}
|
|
`}},Hpe=class{constructor(e){this.variableNames=["dy","W"],this.uniforms="filterDims : vec2<i32>; pads : vec2<i32>; stride : vec2<i32>; outBackprop : vec4<i32>;",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e.inShape,this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.isChannelsLast=e.dataFormat==="channelsLast",this.shaderKey=`conv2DDerInput_${this.isChannelsLast}`}getUserCode(){let e=this.isChannelsLast?1:2,t=this.isChannelsLast?2:3,r=this.isChannelsLast?3:1;return`
|
|
${Je()} {
|
|
if(index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let batch = coords[0];
|
|
let d1 = coords[${r}];
|
|
|
|
let dyCorner = vec2<i32>(coords[${e}]), coords[${t}]) - uniforms.pads;
|
|
let dyRCorner = dyCorner.x;
|
|
let dyCCorner = dyCorner.y;
|
|
|
|
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
var dotProd = 0.0;
|
|
for (var wR = 0; wR < uniforms.filterDims.x; wR = wR + 1) {
|
|
let dyR = (f32(dyRCorner) + f32(wR)) / f32(uniforms.stride.x);
|
|
let wRPerm = uniforms.filterDims.x - 1 - wR;
|
|
if (dyR < 0.0 || dyR >= f32(uniforms.outBackprop[1]) || fract(dyR) > 0.0 ||
|
|
wRPerm < 0) {
|
|
continue;
|
|
}
|
|
let idyR = dyR;
|
|
|
|
for (var wC = 0; wC < uniforms.filterDims.y; wC = wC + 1) {
|
|
let dyC = (f32(dyCCorner) + f32(wC)) / f32(uniforms.stride.y);
|
|
let wCPerm = uniforms.filterDims.y - 1 - wC;
|
|
if (dyC < 0.0 || dyC >= f32(uniforms.outBackprop[2]) ||
|
|
fract(dyC) > 0.0 || wCPerm < 0) {
|
|
continue;
|
|
}
|
|
let idyC = dyC;
|
|
|
|
for (var d2 = 0; d2 < uniforms.outBackprop[3]; d2 = d2 + 1) {
|
|
if (${this.isChannelsLast}) {
|
|
let xValue = getDy(batch, idyR, idyC, d2);
|
|
let wValue = getW(wRPerm, wCPerm, d1, d2);
|
|
dotProd = dotProd + xValue * wValue;
|
|
} else {
|
|
let xValue = getDy(batch, d2, idyR, idyC);
|
|
let wValue = getW(wRPerm, wCPerm, d1, d2);
|
|
dotProd = dotProd + xValue * wValue;
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
setOutputAtIndex(index, dotProd);
|
|
}
|
|
}
|
|
`}};function qpe(e){let{inputs:t,backend:r,attrs:a}=e,{dy:n,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:d,dimRoundingMode:u}=a,p=N.convertConv2DDataFormat(d),h=N.computeConv2DInfo(i,s.shape,o,1,l,u,!1,p),c=[{type:"int32",data:[h.filterHeight,h.filterWidth]},{type:"int32",data:[h.filterHeight-1-h.padInfo.top,h.filterWidth-1-h.padInfo.left]},{type:"int32",data:[h.strideHeight,h.strideWidth]},{type:"int32",data:[h.batchSize,h.outHeight,h.outWidth,h.outChannels]}],f;if(Y().getBool("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE"))f=new Hpe(h);else{f=new jpe(h);let m=h.inShape[1]*h.inShape[2],g=h.inShape[3],y=h.filterHeight*h.filterWidth*h.outChannels;c.push({type:"uint32",data:[m]},{type:"uint32",data:[g]},{type:"uint32",data:[y]})}return r.runWebGPUProgram(f,[n,s],"float32",c)}var Kpe={kernelName:Js,backendName:"webgpu",kernelFunc:qpe},Xpe=xr({opType:2}),Zpe={kernelName:Qs,backendName:"webgpu",kernelFunc:Xpe},Ype=xr({opType:3}),Jpe={kernelName:ei,backendName:"webgpu",kernelFunc:Ype},Qpe=class{constructor(e,t,r,a){this.variableNames=["Image","Boxes","BoxInd"],this.uniforms="extrapolationValue : f32;",this.workGroupSize=[64,1,1],this.size=!0;let[n]=t;this.outputShape=[n,r[0],r[1],e],this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.methodId=a==="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)"],[r,a,n]=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`
|
|
${Je()}
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let height_ratio = f32(${r});
|
|
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 = ${a};
|
|
let width_scale = ${i};
|
|
let in_y = ${n};
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
`}},ehe=e=>{let{inputs:t,backend:r,attrs:a}=e,{image:n,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:d}=a,u=new Qpe(n.shape[3],s.shape,o,l),p=[{type:"float32",data:[d]}];return r.runWebGPUProgram(u,[n,s,i],"float32",p)},the={kernelName:Oo,backendName:"webgpu",kernelFunc:ehe},rhe=class{constructor(e,t){this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.uniforms="blockSize : i32;",this.outputShape=e,this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`depthToSpace_${t}`,this.dataFormat=t}getUserCode(){return`
|
|
${Je()}
|
|
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 ahe(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{blockSize:s,dataFormat:i}=a,o=n.shape[0],l=i==="NHWC"?n.shape[1]:n.shape[2],d=i==="NHWC"?n.shape[2]:n.shape[3],u=i==="NHWC"?n.shape[3]:n.shape[1],p=l*s,h=d*s,c=u/(s*s),f=i==="NHWC"?[o,p,h,c]:[o,c,p,h],m=[{type:"int32",data:[s]}],g=new rhe(f,i);return r.runWebGPUProgram(g,[n],n.dtype,m)}var nhe={kernelName:zo,backendName:"webgpu",kernelFunc:ahe},j8=class{constructor(e,t=!1,r=null,a=!1){this.variableNames=["x","W"],this.uniforms="pad : vec2<i32>; stride : vec2<i32>; dilation : vec2<i32>; inDims : vec2<i32>;",this.workGroupSize=[4,4,4],this.isVec4=!0,this.outputShape=e.outShape,this.dispatchLayout={x:[0,1],y:[2],z:[3]},this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize,[1,4,4]),w.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=r,this.hasPreluActivation=a,this.shaderKey=`depthwise3x3_${r}`}getUserCode(){let e="",t="";if(this.activation){let a=ts(this.activation,this.isVec4);this.hasPreluActivation?e=`fn activation(a : vec4<f32>, outCoord : vec4<i32>) -> vec4<f32> {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${a}
|
|
}`:e=`
|
|
fn activation(a : vec4<f32>, outCoord : vec4<i32>) -> vec4<f32> {
|
|
${a}
|
|
}
|
|
`,t="dotProd[i] = activation(dotProd[i], coords);"}let r=this.addBias?"dotProd[i] = dotProd[i] + getBiasByOutputCoords(coords);":"";return`
|
|
${e}
|
|
|
|
${Lx()}
|
|
fn main(@builtin(global_invocation_id) globalId: vec3<u32>) {
|
|
let batch = 0;
|
|
let r = i32(globalId.x);
|
|
let c = i32(globalId.y) * 4;
|
|
let d2 = i32(globalId.z) * 4;
|
|
let xRCCorner = vec2<i32>(r, c) * uniforms.stride - uniforms.pad;
|
|
let d1 = d2;
|
|
let q = 0;
|
|
|
|
let xRCorner = xRCCorner.x;
|
|
let xCCorner = xRCCorner.y;
|
|
|
|
var wVals : array<vec4<f32>, 9>;
|
|
wVals[0] = getW(0, 0, d1, q);
|
|
wVals[1] = getW(0, 1, d1, q);
|
|
wVals[2] = getW(0, 2, d1, q);
|
|
wVals[3] = getW(1, 0, d1, q);
|
|
wVals[4] = getW(1, 1, d1, q);
|
|
wVals[5] = getW(1, 2, d1, q);
|
|
wVals[6] = getW(2, 0, d1, q);
|
|
wVals[7] = getW(2, 1, d1, q);
|
|
wVals[8] = getW(2, 2, d1, q);
|
|
|
|
var xVals : array<array<vec4<f32>, 6>, 3>;
|
|
for (var wR = 0; wR < 3; wR = wR + 1) {
|
|
let xR = xRCorner + wR * uniforms.dilation[0];
|
|
for (var wC = 0; wC < 6; wC = wC + 1) {
|
|
let xC = xCCorner + wC * uniforms.dilation[1];
|
|
if (xR < 0 || xR >= uniforms.inDims[0] || xC < 0 || xC >= uniforms.inDims[1]) {
|
|
xVals[wR][wC] = vec4<f32>(0.0);
|
|
} else {
|
|
xVals[wR][wC] = getX(batch, xR, xC, d1);
|
|
}
|
|
}
|
|
}
|
|
|
|
var dotProd : array<vec4<f32>, 4>;
|
|
dotProd[0] = vec4<f32>(0.0);
|
|
dotProd[1] = vec4<f32>(0.0);
|
|
dotProd[2] = vec4<f32>(0.0);
|
|
dotProd[3] = vec4<f32>(0.0);
|
|
|
|
for (var wR = 0; wR < 3; wR = wR + 1) {
|
|
for (var wC = 0; wC < 3; wC = wC + 1) {
|
|
let indexW = wR * 3 + wC;
|
|
dotProd[0] = dotProd[0] + xVals[wR][0 + wC] * wVals[indexW];
|
|
dotProd[1] = dotProd[1] + xVals[wR][1 + wC] * wVals[indexW];
|
|
dotProd[2] = dotProd[2] + xVals[wR][2 + wC] * wVals[indexW];
|
|
dotProd[3] = dotProd[3] + xVals[wR][3 + wC] * wVals[indexW];
|
|
}
|
|
}
|
|
|
|
for (var i = 0; i < 4; i = i + 1) {
|
|
let coords = vec4<i32>(batch, r, c + i, d2);
|
|
if (coordsInBounds4D(coords, uniforms.outShape)) {
|
|
${r}
|
|
${t}
|
|
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], dotProd[i]);
|
|
}
|
|
}
|
|
}
|
|
`}},H8=class{constructor(e,t=!1,r=null,a=!1){this.variableNames=["x","W"],this.uniforms=`pad : vec2<i32>; stride : vec2<i32>; dilation : vec2<i32>;
|
|
inDims : vec2<i32>; filterHeight : i32; filterWidth : i32;
|
|
channelMul : i32;`,this.workGroupSize=[256,1,1],this.outputShape=e.outShape,this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),w.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=r,this.hasPreluActivation=a,this.shaderKey=`depthwise_${this.activation}`}getUserCode(){let e="",t="";if(this.activation){let a=ts(this.activation,!1);this.hasPreluActivation?e=`fn activation(a : f32, outCoord : vec4<i32>) -> f32 {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${a}
|
|
}`:e=`
|
|
fn activation(a : f32, outCoord : vec4<i32>) -> f32 {
|
|
${a}
|
|
}
|
|
`,t="dotProd = activation(dotProd, coords);"}let r=this.addBias?"dotProd = dotProd + getBiasByOutputCoords(coords);":"";return`
|
|
${e}
|
|
|
|
fn writeResult(batch : i32, row : i32, col : i32, chan : i32,
|
|
value : f32) {
|
|
let coord = vec4<i32>(batch, row, col, chan);
|
|
if (coordsInBounds4D(coord, uniforms.outShape)) {
|
|
setOutputAtCoords(batch, row, col, chan, value);
|
|
}
|
|
}
|
|
|
|
${Wi()}
|
|
let coords = getOutputCoords();
|
|
let batch = coords[0];
|
|
let xRCCorner = vec2<i32>(coords.yz) * uniforms.stride - uniforms.pad;
|
|
let d2 = coords[3];
|
|
let d1 = d2 / uniforms.channelMul;
|
|
let q = d2 - d1 * uniforms.channelMul;
|
|
|
|
let inputRowStart = xRCCorner.x;
|
|
let inputColStart = xRCCorner.y;
|
|
let inputRowEnd = inputRowStart + uniforms.filterHeight *
|
|
uniforms.dilation[0];
|
|
let inputColEnd = inputColStart + uniforms.filterWidth *
|
|
uniforms.dilation[1];
|
|
|
|
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
var dotProd = 0.0;
|
|
|
|
// Extract if checking out of for loop for performance.
|
|
if (inputRowStart >= 0 && inputColStart >= 0 &&
|
|
inputRowEnd < uniforms.inDims[0] &&
|
|
inputColEnd < uniforms.inDims[1]) {
|
|
// Here using a constant value |this.convInfo.filterHeight| instead
|
|
// of uniform value is in order to loop unrolling.
|
|
for (var wR = 0; wR < uniforms.filterHeight; wR = wR + 1) {
|
|
let xR = inputRowStart + wR * uniforms.dilation[0];
|
|
|
|
for (var wC = 0; wC < uniforms.filterWidth; wC = wC + 1) {
|
|
let xC = inputColStart + wC * uniforms.dilation[1];
|
|
|
|
let xVal = getX(batch, xR, xC, d1);
|
|
let wVal = getW(wR, wC, d1, q);
|
|
dotProd = dotProd + xVal * wVal;
|
|
}
|
|
}
|
|
} else {
|
|
for (var wR = 0; wR < uniforms.filterHeight; wR = wR + 1) {
|
|
let xR = inputRowStart + wR * uniforms.dilation[0];
|
|
|
|
if (xR < 0 || xR >= uniforms.inDims[0]) {
|
|
continue;
|
|
}
|
|
|
|
for (var wC = 0; wC < uniforms.filterWidth; wC = wC + 1) {
|
|
let xC = inputColStart + wC * uniforms.dilation[1];
|
|
|
|
if (xC < 0 || xC >= uniforms.inDims[1]) {
|
|
continue;
|
|
}
|
|
|
|
let xVal = getX(batch, xR, xC, d1);
|
|
let wVal = getW(wR, wC, d1, q);
|
|
dotProd = dotProd + xVal * wVal;
|
|
}
|
|
}
|
|
}
|
|
|
|
${r}
|
|
${t}
|
|
writeResult(batch, coords[1], coords[2], d2, dotProd);
|
|
}
|
|
`}};function she(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,filter:s}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:d}=a,u=l;u==null&&(u=[1,1]);let p=N.computeConv2DInfo(n.shape,s.shape,i,u,o,d,!0),h=[{type:"int32",data:[p.padInfo.top,p.padInfo.left]},{type:"int32",data:[p.strideHeight,p.strideWidth]},{type:"int32",data:[p.dilationHeight,p.dilationWidth]},{type:"int32",data:[p.inHeight,p.inWidth]}],c;return p.batchSize===1&&p.inHeight===p.outHeight&&p.inWidth===p.outWidth&&p.strideHeight===1&&p.strideWidth===1&&p.filterHeight===p.filterWidth&&p.inChannels===p.outChannels&&p.filterHeight===3&&p.inChannels%4===0?c=new j8(p):(c=new H8(p),h.push({type:"int32",data:[p.filterHeight]},{type:"int32",data:[p.filterWidth]},{type:"int32",data:[p.outChannels/p.inChannels]})),r.runWebGPUProgram(c,[n,s],n.dtype,h)}var ihe={kernelName:ti,backendName:"webgpu",kernelFunc:she},q8=Wr({opSnippet:0,cpuKernelImpl:Lde,supportsComplex:!0}),ohe={kernelName:xi,backendName:"webgpu",kernelFunc:q8},lhe=class{constructor(e,t){this.workGroupSize=[64,1,1],this.variableNames=["x"],this.uniforms="reduceSize : i32;",this.size=!0,this.inputShape=[e.batchSize,e.inSize];let[r]=N.computeOutAndReduceShapes(this.inputShape,[1]);this.outputShape=r.length===0?[1]:r,this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,[1,1,1]),this.reduceType=t,this.shaderKey=`reduce_${t}`}getUserCode(){let e="",t="0.0";this.reduceType==="min"||this.reduceType==="max"?(e=`
|
|
if (isNanCustom(candidate)) {
|
|
bestValue = uniforms.NAN;
|
|
} else if (!isNanCustom(bestValue) && candidate ${this.reduceType==="min"?"<":">"} bestValue)
|
|
{ bestValue = candidate; }`,t="f32(x.numbers[offset])"):this.reduceType==="sum"||this.reduceType==="mean"?e=" bestValue = bestValue + candidate; ":this.reduceType==="prod"&&(e=" bestValue = bestValue * candidate; ",t="1.0");let r=this.reduceType==="mean"?"setOutputAtIndex(outputIndex, bestValue / f32(uniforms.reduceSize));":"setOutputAtIndex(outputIndex, bestValue);";return`
|
|
fn DIV_CEIL(a : u32, b : u32) -> u32 {
|
|
return ((a - 1u) / b + 1u);
|
|
}
|
|
|
|
${`
|
|
var<workgroup> xBestValues : array<f32, ${this.workGroupSize[0]}>;
|
|
`}
|
|
fn getOffset(outputIndex : i32) -> i32 {
|
|
let outputCoords = getCoordsFromIndex(outputIndex);
|
|
let offset = ${this.outputShape.length===1?"outputCoords":"outputCoords[0]"} * uniforms.reduceSize;
|
|
return offset;
|
|
}
|
|
${Je()}
|
|
let outputIndex = index / i32(workGroupSizeX);
|
|
let offset = getOffset(outputIndex);
|
|
var bestValue = ${t};
|
|
let Length = uniforms.reduceSize;
|
|
let WorkPerThread = DIV_CEIL(u32(Length), workGroupSizeX);
|
|
for (var k = i32(localId.x); k < Length && outputIndex < uniforms.size;
|
|
k = k + i32(workGroupSizeX)) {
|
|
let candidate = f32(x.numbers[offset + k]);
|
|
${e}
|
|
}
|
|
xBestValues[localId.x] = bestValue;
|
|
workgroupBarrier();
|
|
|
|
var reduceSize = min(u32(Length), workGroupSizeX);
|
|
for (var currentSize = reduceSize / 2u; reduceSize > 1u;
|
|
currentSize = reduceSize / 2u) {
|
|
let interval = DIV_CEIL(reduceSize, 2u);
|
|
if (localId.x < currentSize) {
|
|
let candidate = xBestValues[localId.x + interval];
|
|
${e}
|
|
xBestValues[localId.x] = bestValue;
|
|
}
|
|
reduceSize = interval;
|
|
workgroupBarrier();
|
|
}
|
|
|
|
if (localId.x == 0u && outputIndex < uniforms.size) {
|
|
${r}
|
|
}
|
|
}
|
|
`}};function Oh(e,t,r,a,n){let s=e.shape.length,i=[],o=w.parseAxisParam(t,e.shape),l=o,d=N.getAxesPermutation(l,s),u=e;d!=null&&(u=Nl({inputs:{x:e},attrs:{perm:d},backend:n}),l=N.getInnerMostAxes(l.length,s),i.push(u)),N.assertAxesAreInnerMostDims(a,l,s);let[p,h]=N.computeOutAndReduceShapes(u.shape,l),c=p;r&&(c=N.expandShapeToKeepDim(p,o));let f;if((a==="max"||a==="prod")&&n.shouldExecuteOnCPU([u])){let m=n.tensorMap.get(u.dataId).values;switch(a){case"max":let g=zde(m,w.sizeFromShape(h),c,e.dtype);f=n.makeTensorInfo(c,e.dtype,g);break;case"prod":let{outVals:y,outShape:A,outDtype:x}=Vde(u.shape,u.dtype,m,l);f=n.makeTensorInfo(A,x,y);break;default:throw new Error(`${a} CPU implementation is not yet supported.`)}}else{let m=w.sizeFromShape(h),g=w.sizeFromShape(u.shape)/m,y={windowSize:m,inSize:m,batchSize:g,outSize:1},A=a==="mean"?"float32":ah(e.dtype),x=[{type:"int32",data:[m]}],b=new lhe(y,a),v=n.runWebGPUProgram(b,[u],A,x);i.push(v),f=Ge({inputs:{x:v},attrs:{shape:c},backend:n})}return i.forEach(m=>n.disposeData(m.dataId)),f}function jx(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{axis:s,keepDims:i}=a;return Oh(n,s,i,"sum",r)}var uhe={kernelName:Ri,backendName:"webgpu",kernelFunc:jx};function dhe(e){let{inputs:t,backend:r,attrs:a}=e,{equation:n}=a,s=t,{allDims:i,summedDims:o,idDims:l}=N.decodeEinsumEquation(n,s.length);N.checkEinsumDimSizes(i.length,l,s);let{path:d,steps:u}=N.getEinsumComputePath(o,l),p=u.length,h=null,c=i.length,f=[];for(let m=0;m<p;++m){for(let g of u[m]){let{permutationIndices:y,expandDims:A}=N.getEinsumPermutation(c,l[g]),x;N.isIdentityPermutation(y)?x=s[g]:(x=Nl({inputs:{x:s[g]},backend:r,attrs:{perm:y}}),f.push(x));let b=x.shape.slice();for(let v=0;v<A.length;++v)b.splice(A[v],0,1);w.arraysEqual(x.shape,b)||(x=Ge({inputs:{x},backend:r,attrs:{shape:b}}),f.push(x)),h===null?h=x:(h=q8({inputs:{a:x,b:h},backend:r}),f.push(h))}m<p-1&&(d[m]>=0&&(h=jx({inputs:{x:h},backend:r,attrs:{axis:d[m]-(i.length-c),keepDims:!1}}),f.push(h)),c--)}for(let m of f)m!==h&&r.disposeData(m.dataId);return h}var phe={kernelName:Up,backendName:"webgpu",kernelFunc:dhe},hhe=xr({opType:4}),che={kernelName:ai,backendName:"webgpu",kernelFunc:hhe},fhe=Wr({opSnippet:4,dtype:"bool",cpuKernelImpl:Sde}),mhe={kernelName:Do,backendName:"webgpu",kernelFunc:fhe},K8=xr({opType:5,cpuKernelImpl:Tde,dtype:"float32"}),ghe={kernelName:ni,backendName:"webgpu",kernelFunc:K8};function Ny(e){let{inputs:t,attrs:r,backend:a}=e,{dim:n}=r,{input:s}=t,i=s.shape.length,o=s.shape.slice(),l=n;return n<0&&(w.assert(-(i+1)<=n,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+n+1),o.splice(l,0,1),Ge({inputs:{x:s},backend:a,attrs:{shape:o}})}var yhe={kernelName:_o,backendName:"webgpu",kernelFunc:Ny},Ahe=xr({opType:6,cpuKernelImpl:Cde}),xhe={kernelName:Lo,backendName:"webgpu",kernelFunc:Ahe},bhe=class{constructor(e){this.variableNames=[],this.outputShape=[],this.uniforms="value : f32;",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="fill"}getUserCode(){return`
|
|
${Je()}
|
|
if (index < uniforms.size) {
|
|
setOutputAtIndex(index, uniforms.value);
|
|
}
|
|
}
|
|
`}};function vd(e){let{backend:t,attrs:r}=e,{shape:a,value:n}=r,{dtype:s}=r;if(s=s||w.inferDtype(n),s==="string"){let i=w.getArrayFromDType(s,w.sizeFromShape(a));return i.fill(n),t.makeTensorInfo(a,s,i)}else{let i=new bhe(a),o=[{type:"float32",data:[n]}];return t.runWebGPUProgram(i,[],s,o)}}var vhe={kernelName:Du,backendName:"webgpu",kernelFunc:vd},whe=class{constructor(e){this.outputShape=[],this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="flipLeftRight"}getUserCode(){return`
|
|
${Je()}
|
|
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);
|
|
}
|
|
}
|
|
`}},khe={kernelName:Bo,backendName:"webgpu",kernelFunc:({inputs:e,backend:t})=>{let{image:r}=e,a=t,n=new whe(r.shape);return a.runWebGPUProgram(n,[r],r.dtype)}},Ihe=xr({opType:7,cpuKernelImpl:Nde}),She={kernelName:si,backendName:"webgpu",kernelFunc:Ihe},The=Wr({opSnippet:12,dtype:"int32"}),Che={kernelName:ii,backendName:"webgpu",kernelFunc:The},Nhe=(e,t,r,a,n)=>{let s=[a,...r];return n&&s.push(n),e.createBindGroup({layout:t,entries:s.map((i,o)=>({binding:o,resource:i}))})},X8=(e,t,r,a,n,s=!1)=>{let i={dtype:n.dtype,shape:n.shape},o=tue(a,i,t,s),l=e.createShaderModule({code:o,label:t.constructor.name});return e.createComputePipeline({layout:r,compute:{module:l,entryPoint:"main"},label:t.constructor.name})};function Z8(e,t,r,a="",n=""){return e.shaderKey+"_"+(e.workGroupSize?e.workGroupSize.join(","):"")+t.map(s=>s.length).join(",")+r.join(",")+e.variableNames.join(",")+a+n}function gv(e){let{externalImage:t,backend:r,attrs:a,outShape:n,useImport:s}=e,{numChannels:i}=a,o=w.sizeFromShape(n),l=w.computeStrides(n),d=r.makeTensorInfo(n,"int32"),u=r.getFromPixelsProgram(s?"import":"copyExternal");u.updateOutputShape(n);let p=[d.shape],h=[d.dtype,s?"import":"copyExternal"],c=Z8(u,p,h),f=u.getLayout(r.device),m=r.getAndSavePipeline(c,()=>X8(r.device,u,f.pipelineLayout,[],d,!0));u.setPipeline(m),s||r.queue.copyExternalImageToTexture({source:t,origin:{x:0,y:0}},{texture:u.makeInputTexture(r.device,n[1],n[0])},[n[1],n[0]]);let g=r.tensorMap.get(d.dataId);g.bufferInfo.buffer=r.acquireBuffer(g.bufferInfo.byteSize);let y=[o,i,...l,...u.dispatch];u.setUniform(r.device,y);let A;if(s){let x={source:t};A=r.device.importExternalTexture(x)}else A=u.inputTexture.createView();return r.runFromPixelsProgram(u,g.bufferInfo.buffer,f,A,d.dataId),d}var Ehe={kernelName:Ip,backendName:"webgpu",kernelFunc:Rhe},Ql;function Rhe(e){let{inputs:t,backend:r,attrs:a}=e,{pixels:n}=t,{numChannels:s}=a;if(n==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let i=typeof HTMLVideoElement!="undefined"&&n instanceof HTMLVideoElement,o=typeof HTMLImageElement!="undefined"&&n instanceof HTMLImageElement,l=typeof HTMLCanvasElement!="undefined"&&n instanceof HTMLCanvasElement||typeof OffscreenCanvas!="undefined"&&n instanceof OffscreenCanvas,d=typeof ImageBitmap!="undefined"&&n instanceof ImageBitmap,[u,p]=i?[n.videoWidth,n.videoHeight]:[n.width,n.height],h=[p,u,s];if(Y().getBool("WEBGPU_USE_IMPORT")&&i)return gv({externalImage:n,backend:r,attrs:a,outShape:h,useImport:!0});if((i||o)&&(Ql==null&&(Ql=document.createElement("canvas").getContext("2d")),Ql.canvas.width=u,Ql.canvas.height=p,Ql.drawImage(n,0,0,u,p),n=Ql.canvas),d||l||i||o)return gv({externalImage:n,backend:r,attrs:a,outShape:h,useImport:!1});let c=n.data,f=c;if(s!=null&&s!==4){f=new Uint8Array(n.width*n.height*s);let y=c.length,A=0;for(let x=0;x<y;x++)x%4<s&&(f[A++]=c[x])}let m=r.makeTensorInfo(h,"int32"),g=r.tensorMap.get(m.dataId);return g.values=new Int32Array(f),r.maybeReleaseBuffer(m.dataId),r.uploadToGPU(m.dataId),m}var Fhe=class{constructor(e,t,r,a,n){this.uniforms="varianceEpsilon : f32;",this.workGroupSize=[128,1,1],this.size=!0,this.variableNames=["x","mean","variance"],N.assertAndGetBroadcastShape(e,t),N.assertAndGetBroadcastShape(e,r),this.outputShape=e,this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),a!=null&&(N.assertAndGetBroadcastShape(e,a),this.variableNames.push("offset")),n!=null&&(N.assertAndGetBroadcastShape(e,n),this.variableNames.push("scale")),this.offsetShape=a,this.scaleShape=n,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)"),`
|
|
${Je()}
|
|
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)));
|
|
}
|
|
}
|
|
`}},Mhe={kernelName:oi,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{x:a,scale:n,offset:s,mean:i,variance:o}=e,{varianceEpsilon:l}=t,d=r,u=[a,i,o],p=null;s!=null&&(p=s.shape,u.push(s));let h=null;n!=null&&(h=n.shape,u.push(n));let c=new Fhe(a.shape,i.shape,o.shape,p,h),f=[{type:"float32",data:[l]}];return d.runWebGPUProgram(c,u,a.dtype,f)}};function $he(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:d,dataFormat:u,dilations:p,dimRoundingMode:h,activation:c,leakyreluAlpha:f}=a,m=N.convertConv2DDataFormat(u),g=N.computeConv2DInfo(n.shape,s.shape,l,p,d,h,!1,m);return G8({x:n,filter:s,convInfo:g,backend:r,bias:i,preluActivationWeights:o,leakyreluAlpha:f,activation:c})}var Phe={kernelName:Fs,backendName:"webgpu",kernelFunc:$he};function Ohe(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:d,dilations:u,dimRoundingMode:p,activation:h}=a,c=u;c==null&&(c=[1,1]),w.assert(N.eitherStridesOrDilationsAreOne(l,c),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${c}'`);let f=N.computeConv2DInfo(n.shape,s.shape,l,c,d,p,!0),m=[n,s],g=i!=null,y=o!=null;g&&m.push(i),y&&m.push(o);let A=[{type:"int32",data:[f.padInfo.top,f.padInfo.left]},{type:"int32",data:[f.strideHeight,f.strideWidth]},{type:"int32",data:[f.dilationHeight,f.dilationWidth]},{type:"int32",data:[f.inHeight,f.inWidth]}],x;return f.batchSize===1&&f.inHeight===f.outHeight&&f.inWidth===f.outWidth&&f.strideHeight===1&&f.strideWidth===1&&f.filterHeight===f.filterWidth&&f.inChannels===f.outChannels&&f.filterHeight===3&&f.inChannels%4===0?x=new j8(f,g,h,y):(x=new H8(f,g,h,y),A.push({type:"int32",data:[f.filterHeight]},{type:"int32",data:[f.filterWidth]},{type:"int32",data:[f.outChannels/f.inChannels]})),r.runWebGPUProgram(x,m,"float32",A)}var zhe={kernelName:Ms,backendName:"webgpu",kernelFunc:Ohe},Dhe=class{constructor(e,t){this.variableNames=["A","indices"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`gathernd_${e}`,this.sliceDim=e,this.uniforms=`sliceDim : i32; strides : ${cr(e)};`}getUserCode(){let e;return this.sliceDim>1?e="uniforms.strides[j]":e="uniforms.strides",`
|
|
${Je()}
|
|
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 _he(e){let{inputs:t,backend:r}=e,{params:a,indices:n}=t,s=n.shape,i=s[s.length-1],o=w.sizeFromShape(a.shape),[l,d,u,p]=N.prepareAndValidate(a,n),h=Ge({inputs:{x:n},backend:r,attrs:{shape:[d,i]}}),c=Ge({inputs:{x:a},backend:r,attrs:{shape:[w.sizeFromShape(a.shape)/u,u]}});if(r.shouldExecuteOnCPU([a,n])||a.dtype==="string"){let A=r.readSync(n.dataId),x=r.bufferSync(a),b=Ede(A,x,a.dtype,d,i,u,p,a.shape,o);return r.makeTensorInfo(l,a.dtype,b.values)}let f=new Dhe(i,[d,u]),m=[{type:"int32",data:[i]},{type:"int32",data:p}],g=r.runWebGPUProgram(f,[c,h],c.dtype,m),y=Ge({inputs:{x:g},backend:r,attrs:{shape:l}});return r.disposeData(h.dataId),r.disposeData(c.dataId),r.disposeData(g.dataId),y}var Lhe={kernelName:Vo,backendName:"webgpu",kernelFunc:_he},Bhe=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=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="gather"}getUserCode(){let e=Whe(this.aShape,"i32");return`
|
|
${Je()}
|
|
if (index < uniforms.size) {
|
|
let resRC = getCoordsFromIndex(index);
|
|
setOutputAtIndex(index, getA(${e}));
|
|
}
|
|
}
|
|
`}};function Whe(e,t="int"){let r=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[];for(let n=0;n<e.length;n++)n===2?a.push(`${t}(getIndices(resRC.x, resRC.z))`):a.push(`${r[n]}`);return a.join()}function Y8(e){let{inputs:t,backend:r,attrs:a}=e,{x:n,indices:s}=t,{axis:i,batchDims:o}=a,l=w.parseAxisParam(i,n.shape)[0],d=N.segment_util.collectGatherOpShapeInfo(n,s,l,o),u=w.sizeFromShape(s.shape),p=[],h=Ge({inputs:{x:n},backend:r,attrs:{shape:[d.batchSize,d.outerSize,d.dimSize,d.sliceSize]}}),c=Ge({inputs:{x:s},backend:r,attrs:{shape:[d.batchSize,u/d.batchSize]}});p.push(h),p.push(c);let f=[d.batchSize,d.outerSize,u/d.batchSize,d.sliceSize];if(r.shouldExecuteOnCPU([n,s])){let A=r.tensorMap.get(c.dataId).values,x=Le(c.shape,c.dtype,A),b=r.tensorMap.get(h.dataId).values,v=Le(h.shape,h.dtype,b),C=Rde(v,x,f);return p.forEach(T=>r.disposeData(T.dataId)),r.makeTensorInfo(d.outputShape,C.dtype,C.values)}let m=new Bhe(h.shape,f),g=r.runWebGPUProgram(m,[h,c],h.dtype);p.push(g);let y=Ge({inputs:{x:g},backend:r,attrs:{shape:d.outputShape}});return p.forEach(A=>r.disposeData(A.dataId)),y}var Vhe={kernelName:Wo,backendName:"webgpu",kernelFunc:Y8},Uhe=Wr({opSnippet:5,cpuKernelImpl:Mde,dtype:"bool"}),Ghe={kernelName:Uo,backendName:"webgpu",kernelFunc:Uhe},jhe=Wr({opSnippet:6,dtype:"bool",cpuKernelImpl:Fde}),Hhe={kernelName:li,backendName:"webgpu",kernelFunc:jhe};function qhe(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{alpha:s}=a,i=[{type:"float32",data:[s]}],o=new $h(n.shape,15);return o.uniforms="alpha : f32;",r.runWebGPUProgram(o,[n],"float32",i)}var Khe={kernelName:di,backendName:"webgpu",kernelFunc:qhe},Xhe=Wr({opSnippet:7,dtype:"bool",cpuKernelImpl:Pde}),Zhe={kernelName:Go,backendName:"webgpu",kernelFunc:Xhe},Yhe=Wr({opSnippet:8,dtype:"bool",cpuKernelImpl:$de}),Jhe={kernelName:jo,backendName:"webgpu",kernelFunc:Yhe},Qhe=xr({opType:9,cpuKernelImpl:Ode}),ece={kernelName:pi,backendName:"webgpu",kernelFunc:Qhe},tce=Wr({opSnippet:9,dtype:"bool"}),rce={kernelName:Ho,backendName:"webgpu",kernelFunc:tce},ace=xr({opType:10}),nce={kernelName:Vu,backendName:"webgpu",kernelFunc:ace};function J8(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{reductionIndices:s,keepDims:i}=a;return Oh(n,s,i,"max",r)}var sce={kernelName:hi,backendName:"webgpu",kernelFunc:J8},ice=Wr({opSnippet:15,cpuKernelImpl:Dde}),oce={kernelName:ci,backendName:"webgpu",kernelFunc:ice};function lce(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,d=1,u=N.computePool2DInfo(n.shape,s,i,d,o,l),p,h=[];if(u.filterHeight===1&&u.filterWidth===1){if(w.arraysEqual(u.inShape,u.outShape))return Va({inputs:{x:n},backend:r});p=new W8(u),h.push({type:"int32",data:[u.strideHeight,u.strideWidth]})}else p=new B8(u,"max"),h.push({type:"int32",data:[u.strideHeight,u.strideWidth]},{type:"int32",data:[u.padInfo.top,u.padInfo.left]},{type:"int32",data:[u.dilationHeight,u.dilationWidth]},{type:"int32",data:[u.inHeight,u.inWidth]},{type:"int32",data:[u.effectiveFilterHeight,u.effectiveFilterWidth]});return r.runWebGPUProgram(p,[n],n.dtype,h)}var uce={kernelName:fi,backendName:"webgpu",kernelFunc:lce};function dce(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{keepDims:s,axis:i}=a;return Oh(n,i,s,"mean",r)}var pce={kernelName:mi,backendName:"webgpu",kernelFunc:dce};function hce(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{axis:s,keepDims:i}=a;return Oh(n,s,i,"min",r)}var cce={kernelName:gi,backendName:"webgpu",kernelFunc:hce},fce=Wr({opSnippet:16,cpuKernelImpl:_de}),mce={kernelName:yi,backendName:"webgpu",kernelFunc:fce},gce=class{constructor(e,t,r){this.uniforms="",this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t.map((a,n)=>a[0]+e[n]+a[1]),this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.xShape=e,t.map((a,n)=>{this.uniforms+=` pad${n} : vec2<i32>;`}),this.offset=r==="reflect"?0:1,this.shaderKey=`mirrorPad_${r}`}getUserCode(){let e=this.xShape.length,t=this.xShape.map((l,d)=>`uniforms.pad${d}[0]`).join(","),r=this.xShape.map((l,d)=>`uniforms.pad${d}[0] + uniforms.xShape${e>1?`[${d}]`:""}`).join(","),a=e===1?"start":"start[i]",n=e===1?"end":"end[i]",s=e===1?"outC":"outC[i]",i=cr(e),o=e>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,e):"coords";return`
|
|
${Je()}
|
|
if (index < uniforms.size) {
|
|
let start = ${i}(${t});
|
|
let end = ${i}(${r});
|
|
var outC = getCoordsFromIndex(index);
|
|
for (var i = 0; i < ${e}; i = i + 1) {
|
|
if (${s} < ${a}) {
|
|
${s} = ${a} * 2 - ${s} - ${this.offset};
|
|
} else if(${s} >= ${n}) {
|
|
${s} = (${n} - 1) * 2 - ${s} + ${this.offset};
|
|
}
|
|
}
|
|
let coords = outC - start;
|
|
setOutputAtIndex(index, getX(${o}));
|
|
}
|
|
}
|
|
`}},yce={kernelName:Ai,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{x:a}=e,{paddings:n,mode:s}=t,i=r,o=n.map(d=>({type:"int32",data:[d[0],d[1]]})),l=new gce(a.shape,n,s);return i.runWebGPUProgram(l,[a],a.dtype,o)}};function Ace(e){let{inputs:t,backend:r}=e,{x:a}=t;if(r.shouldExecuteOnCPU([a])){let s=r.tensorMap.get(a.dataId),[i,o]=Bde(s.values,a.shape,a.dtype);return r.makeTensorInfo(o,a.dtype,i)}let n=new $h(a.shape,11);return r.runWebGPUProgram(n,[a],a.dtype)}var xce={kernelName:qo,backendName:"webgpu",kernelFunc:Ace};function bce(e){console.warn("tf.nonMaxSuppression() in webgpu locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:r,attrs:a}=e,{boxes:n,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=a,d=r.readSync(n.dataId),u=r.readSync(s.dataId),{selectedIndices:p}=Ha.nonMaxSuppressionV3Impl(d,u,i,o,l);return r.makeTensorInfo([p.length],"int32",new Int32Array(p))}var vce={kernelName:Xo,backendName:"webgpu",kernelFunc:bce};function wce(e){console.warn("tf.nonMaxSuppression() in webgpu locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:r,attrs:a}=e,{boxes:n,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:d}=a,u=r.readSync(n.dataId),p=r.readSync(s.dataId),h=i,c=o,f=l,m=d,{selectedIndices:g,selectedScores:y}=Ha.nonMaxSuppressionV5Impl(u,p,h,c,f,m);return[r.makeTensorInfo([g.length],"int32",new Int32Array(g)),r.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var kce={kernelName:Zo,backendName:"webgpu",kernelFunc:wce};function bf(e){let{inputs:t,backend:r}=e,{x:a}=t;if(a.dtype==="complex64"){let n=Ph({inputs:{input:a},backend:r}),s=bf({inputs:{x:n},backend:r}),i=a0({inputs:{input:a},backend:r}),o=bf({inputs:{x:i},backend:r}),l=xd({inputs:{real:s,imag:o},backend:r});return r.disposeData(n.dataId),r.disposeData(s.dataId),r.disposeData(i.dataId),r.disposeData(o.dataId),l}else return vd({attrs:{shape:a.shape,dtype:a.dtype,value:a.dtype==="string"?"":0},backend:r})}var Ice={kernelName:ml,backendName:"webgpu",kernelFunc:bf};function Q8(e){let{inputs:t,backend:r}=e,{x:a}=t;if(a.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(a.dtype==="complex64"){let n=Ph({inputs:{input:a},backend:r}),s=Q8({inputs:{x:n},backend:r}),i=a0({inputs:{input:a},backend:r}),o=bf({inputs:{x:i},backend:r}),l=xd({inputs:{real:s,imag:o},backend:r});return r.disposeData(n.dataId),r.disposeData(s.dataId),r.disposeData(i.dataId),r.disposeData(o.dataId),l}else return vd({attrs:{shape:a.shape,dtype:a.dtype,value:1},backend:r})}var Sce={kernelName:Yo,backendName:"webgpu",kernelFunc:Q8};function Tce(e){let{inputs:t,backend:r,attrs:a}=e,{axis:n}=a;if(t.length===1)return Ny({inputs:{input:t[0]},backend:r,attrs:{dim:n}});let s=t[0].shape,i=t[0].dtype;t.forEach(u=>{w.assertShapesMatch(s,u.shape,"All tensors passed to stack must have matching shapes"),w.assert(i===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(u=>{let p=Ny({inputs:{input:u},backend:r,attrs:{dim:n}});return o.push(p),p}),d=U8({inputs:l,backend:r,attrs:{axis:n}});return o.forEach(u=>r.disposeData(u.dataId)),d}var Cce={kernelName:Qo,backendName:"webgpu",kernelFunc:Tce},Nce=class{constructor(e,t){this.variableNames=["x"],this.uniforms="constantValue : f32;",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t.map((r,a)=>r[0]+e[a]+r[1]),this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),t.map((r,a)=>{this.uniforms+=` pad${a} : vec2<i32>;`}),this.xShape=e,this.shaderKey="pad"}getUserCode(){let e=this.xShape.length,t=cr(e),r=this.xShape.map((d,u)=>`uniforms.pad${u}[0]`).join(","),a=this.xShape.map((d,u)=>`uniforms.pad${u}[0] + uniforms.xShape${e>1?`[${u}]`:""}`).join(","),n=e>1?`${t}(${r})`:`${r}`,s=e>1?`${t}(${a})`:`${a}`,i=e>1?"any(outC < start)":"outC < start",o=e>1?"any(outC >= end)":"outC >= end",l=e>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,e):"coords";return`
|
|
${Je()}
|
|
if (index < uniforms.size) {
|
|
let start = ${n};
|
|
let end = ${s};
|
|
let outC = getCoordsFromIndex(index);
|
|
|
|
if (${i} || ${o}) {
|
|
setOutputAtIndex(index, uniforms.constantValue);
|
|
} else {
|
|
let coords = outC - start;
|
|
setOutputAtIndex(index, getX(${l}));
|
|
}
|
|
}
|
|
}
|
|
`}},eS=e=>{let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{paddings:s,constantValue:i}=a;if(s.every(d=>w.arraysEqual(d,[0,0])))return Va({inputs:{x:n},backend:r});if(w.sizeFromShape(n.shape)===0){let d=s.map((u,p)=>u[0]+n.shape[p]+u[1]);return vd({backend:r,attrs:{shape:d,value:i,dtype:n.dtype}})}let o=[{type:"float32",data:[i]}];s.map(d=>o.push({type:"int32",data:[d[0],d[1]]}));let l=new Nce(n.shape,s);return r.runWebGPUProgram(l,[n],n.dtype,o)},Ece={kernelName:bi,backendName:"webgpu",kernelFunc:eS},Rce=Wr({opSnippet:13}),Fce={kernelName:vi,backendName:"webgpu",kernelFunc:Rce};function Mce(e){let{inputs:t,backend:r}=e,{x:a,alpha:n}=t,s=new _8(14,a.shape,n.shape);return r.runWebGPUProgram(s,[a,n],"float32")}var $ce={kernelName:wi,backendName:"webgpu",kernelFunc:Mce};function Pce(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{axis:s,keepDims:i}=a;return Oh(n,s,i,"prod",r)}var Oce={kernelName:el,backendName:"webgpu",kernelFunc:Pce},zce=e=>{let{backend:t,attrs:r}=e,{start:a,stop:n,step:s,dtype:i}=r,o=Ude(a,n,s,i);return t.makeTensorInfo([o.length],i,o)},Dce={kernelName:ju,backendName:"webgpu",kernelFunc:zce},tS=Wr({opSnippet:3}),_ce={kernelName:ri,backendName:"webgpu",kernelFunc:tS},Lce=xr({opType:13}),Bce={kernelName:ki,backendName:"webgpu",kernelFunc:Lce},Wce=xr({opType:14}),Vce={kernelName:Si,backendName:"webgpu",kernelFunc:Wce},Uce=class{constructor(e,t,r){this.variableNames=["x"],this.uniforms="adjustHeightWidth : vec2<f32>; halfPixelCenters : f32;",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=[e[0],t,r,e[3]],this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="resizeBilinear"}getUserCode(){return`
|
|
${Je()}
|
|
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 Gce(e){let{inputs:t,backend:r,attrs:a}=e,{images:n}=t,{alignCorners:s,size:i,halfPixelCenters:o}=a,[l,d]=i,u=s&&l>1?1:0,p=s&&d>1?1:0,h=[{type:"float32",data:[u,p]},{type:"float32",data:[o?.5:0]}],c=new Uce(n.shape,l,d);return r.runWebGPUProgram(c,[n],"float32",h)}var jce={kernelName:Ii,backendName:"webgpu",kernelFunc:Gce},Hce=class{constructor(e,t,r,a){this.variableNames=["x"],this.uniforms="adjustHeightWidth : vec2<f32>; roundBase : f32;",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=[e[0],t,r,e[3]],this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.halfPixelCenters=a,this.shaderKey=`resizeNearest_${a}`}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",`
|
|
${Je()}
|
|
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 qce(e){let{inputs:t,backend:r,attrs:a}=e,{images:n}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a,[l,d]=o,u=s&&l>1?1:0,p=s&&d>1?1:0,h=[{type:"float32",data:[u,p]},{type:"float32",data:[s?.5:0]}],c=new Hce(n.shape,l,d,i);return r.runWebGPUProgram(c,[n],n.dtype,h)}var Kce={kernelName:qu,backendName:"webgpu",kernelFunc:qce},Xce=class{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=He(this.outputShape),this.dispatch=ze(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`
|
|
${Je()}
|
|
|
|
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);
|
|
}
|
|
}
|
|
`}},Zce={kernelName:gl,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{image:a}=e,{radians:n,fillValue:s,center:i}=t,o=r,l=new Xce(a.shape,s),[d,u]=N.getImageCenter(i,a.shape[1],a.shape[2]),p=[{type:"float32",data:[d]},{type:"float32",data:[u]},{type:"float32",data:[Math.sin(n)]},{type:"float32",data:[Math.cos(n)]}];return typeof s=="number"?p.push({type:"float32",data:[Number.parseFloat(s.toFixed(2))]}):p.push({type:"float32",data:s}),o.runWebGPUProgram(l,[a],a.dtype,p)}},Yce=xr({opType:16,cpuKernelImpl:Gde}),Jce={kernelName:Ti,backendName:"webgpu",kernelFunc:Yce},Qce=class{constructor(e,t,r,a,n,s,i){this.variableNames=["updates","indices"],this.workGroupSize=[64,1,1],this.atomic=!0,this.outputShape=s,this.type=i,this.dispatchLayout=He(e),this.dispatch=ze(this.dispatchLayout,e,this.workGroupSize),this.sliceDimGreaterThanOne=t>1,this.shaderKey=`scatter_${r}_${a}_${this.sliceDimGreaterThanOne}_${i}`;let o=cr(n.length);this.uniforms=`sliceDim : i32; strides: ${o}; size: i32;`,this.updatesRank=a,this.indicesRank=r}getUserCode(){let e="";this.indicesRank===1?e="coords[0]":this.indicesRank===2&&(e="coords[0], j");let t=`getIndices(${e})`,r=this.sliceDimGreaterThanOne?"uniforms.strides[j]":"uniforms.strides",a="",n="",s="";this.updatesRank===1?(a="coords[0]",n="flattenedIndex",s=`
|
|
fn getUpdatesCoordsFromFlatIndex(index : i32) -> i32 {
|
|
return index;
|
|
}
|
|
`):this.updatesRank===2&&(a="coords[0], coords[1]",n="vec2<i32>(flattenedIndex, coords[1])",s=`
|
|
fn getUpdatesCoordsFromFlatIndex(index : i32) -> vec2<i32> {
|
|
let d0 = index / uniforms.updatesShape[1];
|
|
let d1 = index - d0 * uniforms.updatesShape[1];
|
|
return vec2<i32>(d0, d1);
|
|
}
|
|
`);let i=`getUpdates(${a})`,o=this.type==="int32"?"atomicAdd(&(result.numbers[flatIndex]), i32(updateValue));":`
|
|
var assumed = atomicLoad(&(result.numbers[flatIndex]));
|
|
var success = 0;
|
|
for (; success == 0;) {
|
|
let new = bitcast<f32>(assumed) + updateValue;
|
|
let newI32 = bitcast<i32>(new);
|
|
let resValue = atomicCompareExchangeWeak(&(result.numbers[flatIndex]), assumed, newI32);
|
|
assumed = resValue[0];
|
|
success = resValue[1];
|
|
}
|
|
`;return`
|
|
${s}
|
|
|
|
${Je()}
|
|
|
|
if (index < uniforms.size) {
|
|
let coords = getUpdatesCoordsFromFlatIndex(index);
|
|
var flattenedIndex = 0;
|
|
for (var j = 0; j < uniforms.sliceDim; j = j + 1) {
|
|
let indexInside = i32(round(${t}));
|
|
flattenedIndex = flattenedIndex + indexInside * ${r};
|
|
}
|
|
let updateValue = ${i};
|
|
let flatIndex = getOutputIndexFromCoords(${n});
|
|
|
|
${o}
|
|
}
|
|
}`}};function efe(e){let{inputs:t,backend:r,attrs:a}=e,{indices:n,updates:s}=t,{shape:i}=a,{sliceRank:o,numUpdates:l,sliceSize:d,strides:u,outputSize:p}=N.calculateShapes(s,n,i),h=[p/d,d];if(p===0)return r.makeTensorInfo(i,n.dtype);let c=Ge({inputs:{x:n},backend:r,attrs:{shape:[l,o]}}),f=Ge({inputs:{x:s},backend:r,attrs:{shape:[l,d]}}),m=f.dtype,g=vd({backend:r,attrs:{shape:h,value:0,dtype:m}}),y=w.sizeFromShape(f.shape),A=[{type:"int32",data:[o]},{type:"int32",data:u},{type:"int32",data:[y]}],x=new Qce(f.shape,o,c.shape.length,f.shape.length,u,h,m),b=r.runWebGPUProgram(x,[f,c],m,A,g),v=Ge({inputs:{x:b},backend:r,attrs:{shape:i}});return r.disposeData(c.dataId),r.disposeData(f.dataId),r.disposeData(b.dataId),v}var tfe={kernelName:nl,backendName:"webgpu",kernelFunc:efe},rfe=class{constructor(e,t,r){this.variableNames=["c","a","b"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.cRank=e,this.rank=r,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 r=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[],n=[];for(let s=0;s<this.outputShape.length;s++)n.push(`${r[s]}`),s<this.cRank&&a.push(`${r[s]}`);e=a.join(),t=n.join()}return`
|
|
${Je()}
|
|
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 afe(e){let{inputs:t,backend:r}=e,{condition:a,t:n,e:s}=t,i=new rfe(a.shape.length,n.shape,n.shape.length);return r.runWebGPUProgram(i,[a,n,s],Or(n.dtype,s.dtype))}var nfe={kernelName:sl,backendName:"webgpu",kernelFunc:afe},sfe=xr({opType:19}),ife={kernelName:Ni,backendName:"webgpu",kernelFunc:sfe},ofe=xr({opType:17}),lfe={kernelName:Ci,backendName:"webgpu",kernelFunc:ofe},ufe=xr({opType:18}),dfe={kernelName:ol,backendName:"webgpu",kernelFunc:ufe},rS=Wr({opSnippet:2,cpuKernelImpl:Xde,supportsComplex:!0}),pfe={kernelName:$i,backendName:"webgpu",kernelFunc:rS};function hfe(e){let{inputs:t,backend:r,attrs:a}=e,{logits:n}=t,{dim:s}=a,i=w.parseAxisParam([s],n.shape),o=J8({inputs:{x:n},backend:r,attrs:{reductionIndices:i,keepDims:!1}}),l=N.expandShapeToKeepDim(o.shape,i),d=Ge({inputs:{x:o},backend:r,attrs:{shape:l}}),u=rS({inputs:{a:n,b:d},backend:r}),p=K8({inputs:{x:u},backend:r}),h=jx({inputs:{x:p},backend:r,attrs:{axis:i,keepDims:!1}}),c=Ge({inputs:{x:h},backend:r,attrs:{shape:l}}),f=tS({inputs:{a:p,b:c},backend:r});return r.disposeData(o.dataId),r.disposeData(d.dataId),r.disposeData(u.dataId),r.disposeData(p.dataId),r.disposeData(h.dataId),r.disposeData(c.dataId),f}var cfe={kernelName:Fi,backendName:"webgpu",kernelFunc:hfe},ffe=e=>{let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{blockShape:s,paddings:i}=a;w.assert(n.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGPU backend not implemented yet");let o=s.reduce((y,A)=>y*A),l=[[0,0]];l.push(...i);for(let y=1+s.length;y<n.shape.length;++y)l.push([0,0]);let d=[],u=eS({inputs:{x:n},backend:r,attrs:{paddings:l,constantValue:0}}),p=N.getReshaped(u.shape,s,o,!1),h=N.getPermuted(p.length,s.length,!1),c=N.getReshapedPermuted(u.shape,s,o,!1),f=Ge({inputs:{x:u},backend:r,attrs:{shape:p}}),m=Nl({inputs:{x:f},backend:r,attrs:{perm:h}}),g=Ge({inputs:{x:m},backend:r,attrs:{shape:c}});return d.push(u),d.push(f),d.push(m),d.forEach(y=>r.disposeData(y.dataId)),g},mfe={kernelName:ll,backendName:"webgpu",kernelFunc:ffe},gfe=class{constructor(e,t,r,a,n,s,i=!0){this.variableNames=["updates","indices","defaultValue"],this.workGroupSize=[64,1,1],this.workPerThread=4,this.size=!0,this.outputShape=s,this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]);let o=t>1;this.shaderKey=`scatter_${r}_${a}_${o}`;let l=cr(n.length);this.uniforms=`updateSize : i32; sliceDim : i32; strides: ${l};`;let d="";r===1?d="i":r===2&&(d="i, j"),this.indicesSnippet=`getIndices(${d})`;let u="";a===1?u="i":a===2&&(u="i, coords[1]"),this.updatesSnippet=`getUpdates(${u})`,this.strideString=o?"uniforms.strides[j]":"uniforms.strides"}getUserCode(){return`
|
|
${Je()}
|
|
|
|
let globalIndex = index * ${this.workPerThread};
|
|
if (globalIndex < uniforms.size) {
|
|
var sum = vec4<f32>(0.0);
|
|
var found = vec4<bool>(false);
|
|
for (var i = 0; i < uniforms.updateSize; i = i + 1) {
|
|
var flattenedIndex = 0;
|
|
for (var j = 0; j < uniforms.sliceDim; j = j + 1) {
|
|
let indexInside = i32(round(${this.indicesSnippet}));
|
|
flattenedIndex = flattenedIndex + indexInside * ${this.strideString};
|
|
}
|
|
for (var innerIndex = 0; innerIndex < ${this.workPerThread}; innerIndex = innerIndex + 1) {
|
|
let curIndex = globalIndex + innerIndex;
|
|
let coords = getCoordsFromIndex(curIndex);
|
|
if (flattenedIndex == coords[0]) {
|
|
sum[innerIndex] = sum[innerIndex] + ${this.updatesSnippet};
|
|
found[innerIndex] = true;
|
|
}
|
|
}
|
|
}
|
|
for (var innerIndex = 0; innerIndex < ${this.workPerThread}; innerIndex = innerIndex + 1) {
|
|
let curIndex = globalIndex + innerIndex;
|
|
if (curIndex < uniforms.size)
|
|
{
|
|
setOutputAtIndex(curIndex, mix(getDefaultValue(), sum[innerIndex], f32(found[innerIndex])));
|
|
}
|
|
}
|
|
}
|
|
}`}};function yfe(e){let{inputs:t,backend:r,attrs:a}=e,{sparseIndices:n,sparseValues:s,defaultValue:i}=t,{outputShape:o}=a,{sliceRank:l,numUpdates:d,strides:u,outputSize:p}=N.calculateShapes(s,n,o),h=!1,c=[{type:"int32",data:[d]},{type:"int32",data:[l]},{type:"int32",data:u}],f=new gfe(d,l,n.shape.length,s.shape.length,u,[p,1],h),m=r.runWebGPUProgram(f,[s,n,i],s.dtype,c),g=Ge({inputs:{x:m},backend:r,attrs:{shape:o}});return r.disposeData(m.dataId),g}var Afe={kernelName:Jp,backendName:"webgpu",kernelFunc:yfe};function xfe(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{numOrSizeSplits:s,axis:i}=a,o=w.parseAxisParam(i,n.shape)[0],l=N.prepareSplitSize(n,s,o),d=n.shape.length,u=new Array(d).fill(0),p=n.shape.slice();return l.map(h=>{let c=[...p];c[o]=h;let f=bd({inputs:{x:n},backend:r,attrs:{begin:u,size:c}});return u[o]+=h,f})}var bfe={kernelName:ul,backendName:"webgpu",kernelFunc:xfe},vfe=xr({opType:20}),wfe={kernelName:Ei,backendName:"webgpu",kernelFunc:vfe},kfe={kernelName:Ju,backendName:"webgpu",kernelFunc:({inputs:e,backend:t})=>{let{x:r}=e,a=t,n=new $h(r.shape,21);return a.runWebGPUProgram(n,[r],r.dtype)}},Ife=Wr({opSnippet:11}),Sfe={kernelName:Mi,backendName:"webgpu",kernelFunc:Ife},Tfe=class{constructor(e){this.variableNames=["x"],this.workPerThread=1,this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]);let t=cr(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 r=0;t=this.outputShape.map((a,n)=>(r++,this.outputShape.length===1?`coords * uniforms.strides[${n}] + uniforms.begin[${n}]`:`coords[${r-1}] * uniforms.strides[${n}] + uniforms.begin[${n}]`)).join(",")}return`
|
|
${Je()}
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
setOutputAtIndex(index, getX(${t}));
|
|
}
|
|
}
|
|
`}};function Cfe(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:d,ellipsisMask:u,newAxisMask:p,shrinkAxisMask:h}=a,{finalShapeSparse:c,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:A,end:x,strides:b}=Ot.sliceInfo(n.shape,s,i,o,l,d,u,p,h),v;if(m)v=Ge({inputs:{x:n},backend:r,attrs:{shape:f}});else if(g||y){w.assert(n.shape.length>=1,()=>`Input must have rank at least 1, got: ${n.shape.length}`);let C=Ot.computeOutShape(A,x,b),T=bd({inputs:{x:n},backend:r,attrs:{begin:A,size:C}});v=Ge({inputs:{x:T},backend:r,attrs:{shape:f}}),r.disposeData(T.dataId)}else if(r.shouldExecuteOnCPU([n])){let C=r.readSync(n.dataId),T=Le(n.shape,n.dtype,C),E=qde(c,T,b,A);v=r.makeTensorInfo(f,n.dtype,E.values)}else{let C=new Tfe(c),T=[{type:"int32",data:A},{type:"int32",data:b}],E=r.runWebGPUProgram(C,[n],n.dtype,T);v=Ge({inputs:{x:E},backend:r,attrs:{shape:f}}),r.disposeData(E.dataId)}return v}var Nfe={kernelName:dl,backendName:"webgpu",kernelFunc:Cfe};function Efe(e){let{inputs:t,backend:r,attrs:a}=e,{separator:n,nGramWidths:s,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:d}=a,{data:u,dataSplits:p}=t,h=r.readSync(u.dataId),c=r.readSync(p.dataId),[f,m]=Kde(h,c,n,s,i,o,l,d);return[r.makeTensorInfo([f.length],"string",f),r.makeTensorInfo(p.shape,"int32",m)]}var Rfe={kernelName:Qp,backendName:"webgpu",kernelFunc:Efe},Ffe=xr({opType:22}),Mfe={kernelName:Pi,backendName:"webgpu",kernelFunc:Ffe},$fe=class{constructor(e,t){this.variableNames=["A"],this.workGroupSize=[64,1,1],this.size=!0;let r=new Array(e.length);for(let a=0;a<r.length;a++)r[a]=e[a]*t[a];this.outputShape=r,this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.rank=this.outputShape.length,this.shaderKey="tile"}getUserCode(){let e=Pfe(this.rank,"uniforms.");return`
|
|
${Je()}
|
|
if (index < uniforms.size) {
|
|
let resRC = getCoordsFromIndex(index);
|
|
setOutputAtIndex(index, getA(${e}));
|
|
}
|
|
}
|
|
`}};function Pfe(e,t=""){if(e>=5)throw Error(`Tile for rank ${e} is not yet supported`);if(e===1)return`(resRC % ${t}aShape)`;let r=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[];for(let n=0;n<e;n++)a.push(`(${r[n]} % ${t}aShape[${n}])`);return a.join()}function Ofe(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{reps:s}=a;if(r.shouldExecuteOnCPU([n])||n.dtype==="string"||n.shape.length>=5){let o=r.readSync(n.dataId),l=n.dtype==="string"?o.map(p=>w.decodeString(p)):o,d=Le(n.shape,n.dtype,l),u=Zde(d,s);return r.makeTensorInfo(u.shape,u.dtype,u.values)}let i=new $fe(n.shape,s);return r.runWebGPUProgram(i,[n],n.dtype)}var zfe={kernelName:Xn,backendName:"webgpu",kernelFunc:Ofe},Dfe=class{constructor(e){this.variableNames=["x","indices"],this.workGroupSize=[256,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.uniforms=`inputSize : i32; firstPass : i32; negativeInf : f32;
|
|
dir : i32; inc : i32;`,this.shaderKey="swap"}getUserCode(){return`
|
|
${Je()}
|
|
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));
|
|
}
|
|
}
|
|
}
|
|
`}},_fe=class{constructor(e){this.variableNames=["x","indices"],this.workGroupSize=[256,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.uniforms="inputSize : i32; firstPass : i32; k : i32;",this.shaderKey="merge"}getUserCode(){return`
|
|
${Je()}
|
|
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 eu(e,t){t!==null&&e.disposeData(t.dataId)}function yv(e){let t=1;for(;t<e;)t*=2;return t}function Lfe(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{k:s,sorted:i}=a,o=n.shape,l=o[o.length-1];if(r.shouldExecuteOnCPU([n])){let b=r.readSync(n.dataId),[v,C]=Yde(b,o,n.dtype,s,i);return[r.makeTensorInfo(v.shape,v.dtype,v.values),r.makeTensorInfo(C.shape,C.dtype,C.values)]}if(s===0)return o[o.length-1]=0,[r.makeTensorInfo(o,n.dtype,[]),r.makeTensorInfo(o,"int32",[])];if(l===1)return[n,vd({attrs:{shape:o,dtype:"int32",value:0},backend:r})];let d=w.sizeFromShape(o)/l,u=Ge({inputs:{x:n},attrs:{shape:[d,l]},backend:r}),p=yv(s),h=yv(l),c=null,f=()=>c===null?[u,u]:[u,c],m=(b,v,C)=>{let T=f(),E=new Dfe(C),R=[{type:"int32",data:[l]},{type:"int32",data:[c===null?1:0]},{type:"float32",data:[Number.NEGATIVE_INFINITY]},{type:"int32",data:[b]},{type:"int32",data:[v]}],z=c;c=r.runWebGPUProgram(E,T,"int32",R),eu(r,z)};for(let b=1;b<p;b*=2){let v=b*2;for(let C=b;C>=1;C/=2)m(v,C,[d,h])}for(let b=h;b>p;b/=2){let v=f(),C=new _fe([d,b/2]),T=[{type:"int32",data:[l]},{type:"int32",data:[c===null?1:0]},{type:"int32",data:[p]}],E=c;c=r.runWebGPUProgram(C,v,"int32",T),eu(r,E);let R=p/2,z=R*2;for(let M=R;M>=1;M/=2)m(z,M,c.shape)}let g=c;c=bd({inputs:{x:c},backend:r,attrs:{begin:0,size:[d,s]}}),eu(r,g);let y=Y8({inputs:{x:u,indices:c},backend:r,attrs:{axis:1,batchDims:1}});eu(r,u);let A=o.slice(0,-1);A.push(s),g=c,c=Ge({inputs:{x:c},attrs:{shape:A},backend:r}),eu(r,g);let x=y;return y=Ge({inputs:{x:y},attrs:{shape:A},backend:r}),eu(r,x),[y,c]}var Bfe={kernelName:hl,backendName:"webgpu",kernelFunc:Lfe},Wfe=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=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="transform"}getUserCode(){return`
|
|
fn mapCoord(outCoord : f32, len : f32) -> f32{
|
|
var inCoord = outCoord;
|
|
if(uniforms.fillModeId == 2) {
|
|
if (inCoord < 0.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
let sz2 = 2.0 * len;
|
|
if (inCoord < sz2) {
|
|
inCoord = sz2 * f32(i32(f32(-inCoord / sz2))) +
|
|
inCoord;
|
|
}
|
|
if (inCoord < -len) {
|
|
inCoord = inCoord + sz2;
|
|
} else {
|
|
inCoord = -inCoord - 1.0;
|
|
}
|
|
}
|
|
} else if (inCoord > len - 1.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
let sz2 = 2.0 * len;
|
|
inCoord = inCoord - sz2 * f32(i32(f32(inCoord / sz2)));
|
|
if (inCoord >= len) {
|
|
inCoord = sz2 - inCoord - 1.0;
|
|
}
|
|
}
|
|
}
|
|
return clamp(inCoord, 0.0, len - 1.0);
|
|
} else if (uniforms.fillModeId == 3) {
|
|
if (inCoord < 0.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
let sz = len - 1.0;
|
|
inCoord = inCoord + len * (f32(i32(f32(-inCoord / sz))) + 1.0);
|
|
}
|
|
} else if (inCoord > len - 1.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
let sz = len - 1.0;
|
|
inCoord = inCoord - len * f32(i32(f32(inCoord / sz)));
|
|
}
|
|
}
|
|
return clamp(inCoord, 0.0, len - 1.0);
|
|
} else if (uniforms.fillModeId == 4) {
|
|
return clamp(outCoord, 0.0, len - 1.0);
|
|
}
|
|
return outCoord;
|
|
}
|
|
fn readWithFillValue(batch : i32, coordY : i32, coordX : i32,
|
|
channel : i32) -> f32 {
|
|
var outputValue : f32;
|
|
if (0 <= coordY && coordY < uniforms.imageShape[1] && 0 <= coordX && coordX < uniforms.imageShape[2]) {
|
|
outputValue = getImage(batch, coordY, coordX, channel);
|
|
} else {
|
|
outputValue = uniforms.fillValue;
|
|
}
|
|
return outputValue;
|
|
}
|
|
|
|
${Je()}
|
|
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 Vfe(e){let{inputs:t,backend:r,attrs:a}=e,{image:n,transforms:s}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:d}=a,[u,p,h,c]=n.shape,[f,m]=d!=null?d:[p,h],g=[u,f,m,c],y=new Wfe(g),A=i==="nearest"?1:2,x;switch(o){case"constant":x=1;break;case"reflect":x=2;break;case"wrap":x=3;break;case"nearest":x=4;break;default:x=1;break}let b=[{type:"int32",data:[A]},{type:"int32",data:[x]},{type:"float32",data:[l]}];return r.runWebGPUProgram(y,[n,s],"float32",b)}var Ufe={kernelName:cl,backendName:"webgpu",kernelFunc:Vfe};function Gfe(e){let{inputs:t,backend:r,attrs:a}=e,{value:n}=t,{axis:s}=a;s<0&&(s+=n.shape.length);let i=n,o=i.shape.length,l=n.shape[s],d=new Array(o-1),u=0;for(let m=0;m<o;m++)m!==s&&(d[u++]=i.shape[m]);let p=[],h=new Array(o).fill(0),c=i.shape.slice();c[s]=1;let f=new Array(l);for(let m=0;m<f.length;m++){h[s]=m;let g=bd({inputs:{x:i},backend:r,attrs:{begin:h,size:c}}),y=Ge({inputs:{x:g},backend:r,attrs:{shape:d}});f[m]=y,p.push(g)}return p.forEach(m=>r.disposeData(m.dataId)),f}var jfe={kernelName:fl,backendName:"webgpu",kernelFunc:Gfe},Hfe=[yde,epe,rpe,spe,ppe,cpe,mpe,ype,wpe,Tpe,Npe,Mpe,vde,zpe,Gpe,Kpe,Zpe,Jpe,the,nhe,ihe,phe,che,mhe,ghe,yhe,xhe,vhe,khe,Ehe,She,Che,Mhe,Phe,zhe,Lhe,Vhe,Ghe,Hhe,bde,Ppe,Khe,Zhe,Jhe,ece,rce,nce,sce,oce,uce,pce,cce,mce,yce,ohe,xce,vce,kce,kpe,Sce,Cce,Ece,Fce,$ce,Oce,Dce,Ipe,_ce,Bce,Vce,mde,jce,Kce,Zce,Jce,tfe,nfe,ife,lfe,dfe,bpe,Nfe,Rfe,cfe,mfe,Afe,bfe,wfe,kfe,Sfe,pfe,uhe,Mfe,zfe,Bfe,Ufe,upe,jfe,Ice];for(let e of Hfe)Ga(e);var qfe=class{constructor(e){this.device=e,this.numUsedBuffers=0,this.numFreeBuffers=0,this.freeBuffers=new Map,this.usedBuffers=new Map,this.numBytesUsed=0,this.numBytesAllocated=0}acquireUploadBuffer(e,t){return this.acquireBuffer(e,t,!0)}acquireBuffer(e,t,r=!1){let a=Av(e,t);if(this.freeBuffers.has(a)||this.freeBuffers.set(a,[]),this.usedBuffers.has(a)||this.usedBuffers.set(a,[]),this.numBytesUsed+=e,this.numUsedBuffers++,this.freeBuffers.get(a).length>0){this.numFreeBuffers--;let s=this.freeBuffers.get(a).shift();return this.usedBuffers.get(a).push(s),s}this.numBytesAllocated+=e;let n=this.device.createBuffer({mappedAtCreation:r,size:e,usage:t});return this.usedBuffers.get(a).push(n),n}releaseBuffer(e,t,r){if(this.freeBuffers.size===0)return;let a=Av(t,r);this.freeBuffers.has(a)||this.freeBuffers.set(a,[]),this.freeBuffers.get(a).push(e),this.numFreeBuffers++,this.numUsedBuffers--;let n=this.usedBuffers.get(a),s=n.indexOf(e);if(s<0)throw new Error("Cannot release a buffer that was never provided by this buffer manager");n.splice(s,1),this.numBytesUsed-=t}releaseUploadBuffer(e,t,r){e.mapAsync(GPUMapMode.WRITE).then(()=>{this.releaseBuffer(e,t,r)},a=>{})}getNumUsedBuffers(){return this.numUsedBuffers}getNumFreeBuffers(){return this.numFreeBuffers}dispose(){this.freeBuffers.forEach((e,t)=>{e.forEach(r=>{r.destroy()})}),this.usedBuffers.forEach((e,t)=>{e.forEach(r=>{r.destroy()})}),this.freeBuffers=new Map,this.usedBuffers=new Map,this.numUsedBuffers=0,this.numFreeBuffers=0,this.numBytesUsed=0,this.numBytesAllocated=0}};function Av(e,t){return`${e}_${t}`}var aS=class{constructor(){this.outputShape=[0],this.variableNames=[],this.workGroupSize=[256,1,1],this.lastUniformData=[],this.inputTexture=null,this.layout=null,this.lastPixelSize={width:0,height:0},this.disposed=!1,this.shaderKey="fromPixels",this.useImport=!1}updateOutputShape(e){w.arraysEqual(this.outputShape,e)||(this.outputShape=e,this.workPerThread=e[2],this.dispatchLayout=He(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]))}makeFromPixelsSource(){let e=this.useImport?"textureLoad(src, vec2<i32>(coords.yx));":"textureLoad(src, vec2<i32>(coords.yx), 0)";return`
|
|
@binding(1) @group(0) var src: ${this.useImport?"texture_external":"texture_2d<f32>"};
|
|
|
|
${Je()}
|
|
let flatIndexBase = index * uniforms.numChannels;
|
|
for (var i = 0; i < uniforms.numChannels; i = i + 1) {
|
|
let flatIndex = flatIndexBase + i;
|
|
if (flatIndex < uniforms.size) {
|
|
let coords = getCoordsFromIndex(flatIndexBase);
|
|
let values = ${e};
|
|
result.numbers[flatIndex] = i32(floor(255.0 * values[i]));
|
|
}
|
|
}
|
|
}
|
|
`}getUserCode(){return this.makeFromPixelsSource()}setPipeline(e){this.pipeline=e}setUniform(e,t){if(!this.uniform){let r=e.createBuffer({size:t.length*4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this.uniform=r}!t||t.length===this.lastUniformData.length&&t.every((r,a)=>r===this.lastUniformData[a])||(e.queue.writeBuffer(this.uniform,0,new Uint32Array(t)),this.lastUniformData=t)}makeInputTexture(e,t,r){return(!this.inputTexture||this.lastPixelSize.width!==t||this.lastPixelSize.height!==r)&&(this.inputTexture&&this.inputTexture.destroy(),this.inputTexture=e.createTexture({size:[t,r],format:"rgba8unorm",usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),this.lastPixelSize.width=t,this.lastPixelSize.height=r),this.inputTexture}dispose(){this.disposed||(this.uniform&&this.uniform.destroy(),this.inputTexture&&this.inputTexture.destroy(),this.disposed=!0)}getLayout(e){return this.layout===null&&(this.layout=this.createTextureLayout(e)),this.layout}createTextureLayout(e){let t=[];t.push({binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}),t.push({binding:1,visibility:GPUShaderStage.COMPUTE,texture:{}}),t.push({binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{}});let r=e.createBindGroupLayout({entries:t}),a=e.createPipelineLayout({bindGroupLayouts:[r]});return{bindGroupLayout:r,pipelineLayout:a}}},Kfe=class extends aS{constructor(){super(...arguments);this.layout=null,this.useImport=!0}getUserCode(){return this.makeFromPixelsSource()}getLayout(e){return this.layout===null&&(this.layout=this.createTextureImportLayout(e)),this.layout}createTextureImportLayout(e){let t=[];t.push({binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}}),t.push({binding:1,visibility:GPUShaderStage.COMPUTE,externalTexture:{}}),t.push({binding:2,visibility:GPUShaderStage.COMPUTE,buffer:{}});let r=e.createBindGroupLayout({entries:t}),a=e.createPipelineLayout({bindGroupLayouts:[r]});return{bindGroupLayout:r,pipelineLayout:a}}},Xfe=Y().getNumber("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD"),nS=class extends Iu{constructor(e,t=!1){super();if(this.commandQueueOwnedIds=new WeakSet,this.tensorDisposalQueue=[],this.uniformDisposalQueue=[],this.stagingDisposalQueue=[],this.disposed=!1,this.uploadWaitMs=0,this.downloadWaitMs=0,this.dispatchNumberInEncoder=0,!Vx())throw new Error("WebGPU is not supported on this device");this.layoutCache={},this.pipelineCache={},this.device=e,this.queue=e.queue,this.currentCommandEncoder=null,this.currentComputePass=null,this.supportTimeQuery=t,this.bufferManager=new qfe(this.device),this.tensorMap=new Dp(this,kr()),this.supportTimeQuery&&(this.querySet=this.device.createQuerySet({type:"timestamp",count:2})),Y().getBool("WEBGPU_USE_PROFILE_TOOL")&&(this.dummyCanvas=document.createElement("canvas"),this.dummyCanvas.width=1,this.dummyCanvas.height=1,this.dummyContext=this.dummyCanvas.getContext("webgpu"),this.dummyContext.configure({device:e,format:"bgra8unorm"}),document.body.appendChild(this.dummyCanvas))}nextDataId(){return nS.nextDataId++}floatPrecision(){return 32}defaultGpuBufferUsage(){return GPUBufferUsage.STORAGE|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST}flushDisposalQueue(){this.tensorDisposalQueue.forEach(e=>{this.maybeReleaseBuffer(e),this.tensorMap.delete(e)}),this.uniformDisposalQueue.forEach(e=>this.bufferManager.releaseBuffer(e.buffer,e.byteSize,e.usage)),this.stagingDisposalQueue.forEach(e=>this.bufferManager.releaseUploadBuffer(e.buffer,e.byteSize,e.usage)),this.tensorDisposalQueue=[],this.uniformDisposalQueue=[],this.stagingDisposalQueue=[]}disposeData(e,t=!1){if(this.tensorMap.has(e)){let r=this.tensorMap.get(e);if(r.refCount--,!t&&r.refCount>0)return!1;if(this.commandQueueOwnedIds.has(e))return this.tensorDisposalQueue.push(e),!1;this.maybeReleaseBuffer(e);let{complexTensorInfos:a}=this.tensorMap.get(e);a!=null&&(this.disposeData(a.real.dataId,!0),this.disposeData(a.imag.dataId,!0)),this.tensorMap.delete(e)}return!0}memory(){return{numBytesInGPU:this.bufferManager.numBytesUsed,numBytesAllocatedInGPU:this.bufferManager.numBytesAllocated,unreliable:!1}}getBufferManager(){return this.bufferManager}acquireBuffer(e,t=this.defaultGpuBufferUsage()){return this.bufferManager.acquireBuffer(e,t)}maybeReleaseBuffer(e){let t=this.tensorMap.get(e);t!=null&&t.bufferInfo.buffer!=null&&(this.bufferManager.releaseBuffer(t.bufferInfo.buffer,t.bufferInfo.byteSize,t.bufferInfo.usage),t.bufferInfo.buffer=null)}refCount(e){return this.tensorMap.has(e)?this.tensorMap.get(e).refCount:0}incRef(e){let t=this.tensorMap.get(e);t.refCount++}decRef(e){if(this.tensorMap.has(e)){let t=this.tensorMap.get(e);t.refCount--}}write(e,t,r){if(r==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let a={id:this.nextDataId()},n=w.sizeFromShape(t)*Iy(r);return this.tensorMap.set(a,{dtype:r,values:e,bufferInfo:{byteSize:n,usage:this.defaultGpuBufferUsage()},refCount:1}),a}move(e,t,r,a,n){if(a==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let s=w.sizeFromShape(r)*Iy(a);this.tensorMap.set(e,{dtype:a,values:t,bufferInfo:{byteSize:s,usage:this.defaultGpuBufferUsage()},refCount:n})}submitQueue(){this.ensureComputePassEnded(),this.queue.submit([this.currentCommandEncoder.finish()]),this.currentCommandEncoder=null,this.dispatchNumberInEncoder=0,this.commandQueueOwnedIds=new WeakSet,this.flushDisposalQueue()}getBuffer(e){return this.uploadToGPU(e),this.tensorMap.get(e).bufferInfo.buffer}getFromPixelsProgram(e){switch(e){case"copyExternal":return this.fromPixelProgram||(this.fromPixelProgram=new aS),this.fromPixelProgram;case"import":return this.fromPixelImportProgram||(this.fromPixelImportProgram=new Kfe),this.fromPixelImportProgram;default:w.assert(!1,()=>"Unsupported fromPixels shape");return}}ensureCommandEncoderReady(){this.currentCommandEncoder||(this.currentCommandEncoder=this.device.createCommandEncoder())}ensureComputePassEnded(){this.currentComputePass&&(this.currentComputePass.endPass(),this.currentComputePass=null)}getComputePass(){return this.currentComputePass||(this.currentComputePass=this.currentCommandEncoder.beginComputePass()),this.currentComputePass}async getBufferData(e){if(e.values!=null)return e.values;let t=this.acquireBuffer(e.bufferInfo.byteSize,GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ);this.ensureCommandEncoderReady(),this.ensureComputePassEnded(),this.currentCommandEncoder.copyBufferToBuffer(e.bufferInfo.buffer,0,t,0,e.bufferInfo.byteSize),this.submitQueue(),await t.mapAsync(GPUMapMode.READ);let r=t.getMappedRange().slice(0);return t.unmap(),t!=null&&this.bufferManager.releaseBuffer(t,e.bufferInfo.byteSize,GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ),Y().getBool("WEBGPU_USE_PROFILE_TOOL")&&(w.assert(this.dummyContext!==void 0,()=>"Fail to get context for profiling tool"),this.dummyContext.getCurrentTexture()),r}convertAndCacheOnCPU(e,t){let r=this.tensorMap.get(e);return this.maybeReleaseBuffer(e),r.values=t,r.values}readSync(e){let t=this.tensorMap.get(e),{values:r}=t;if(r==null)throw new Error("WebGPU readSync is only available for CPU-resident tensors.");return r}async read(e){if(!this.tensorMap.has(e))throw new Error(`Tensor ${e} was not registered!`);let t=this.tensorMap.get(e),{values:r}=t;if(r!=null)return this.convertAndCacheOnCPU(e,r);let a;if(t.dtype==="complex64"){let n=await Promise.all([this.read(t.complexTensorInfos.real.dataId),this.read(t.complexTensorInfos.imag.dataId)]),s=n[0],i=n[1];a=N.mergeRealAndImagArrays(s,i)}else{let n=await this.getBufferData(t);a=P8(n,t.dtype)}return this.convertAndCacheOnCPU(e,a),a}bufferSync(e){let t=this.readSync(e.dataId),r=t;if(e.dtype==="string")try{r=t.map(a=>w.decodeString(a))}catch(a){throw new Error("Failed to decode encoded string bytes into utf-8")}return Le(e.shape,e.dtype,r)}async time(e){let t=this.activeTimers,r=[],a=!1;this.programTimersStack==null?(this.programTimersStack=r,a=!0):this.activeTimers.push(r),this.activeTimers=r,e();let n=w.flatten(this.activeTimers.map(l=>l.query)).filter(l=>l!=null),s=w.flatten(this.activeTimers.map(l=>l.name)).filter(l=>l!=null);this.activeTimers=t,a&&(this.programTimersStack=null);let i={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null},o=await Promise.all(n);return i.kernelMs=w.sum(o),i.getExtraProfileInfo=()=>o.map((l,d)=>({name:s[d],ms:l})).map(l=>`${l.name}: ${l.ms}`).join(", "),this.uploadWaitMs=0,this.downloadWaitMs=0,i}getAndSavePipeline(e,t){return e in this.pipelineCache||(this.pipelineCache[e]=t()),this.pipelineCache[e]}makeTensorInfo(e,t,r){let a;if(t==="string"&&r!=null&&r.length>0&&w.isString(r[0])){let n=r.map(s=>w.encodeString(s));a=this.write(n,e,t)}else a=this.write(r,e,t);return{dataId:a,shape:e,dtype:t}}tensorToBinding(e){if(!e)return null;let t=this.tensorMap.get(e.dataId);return{offset:0,size:t.bufferInfo.byteSize,buffer:t.bufferInfo.buffer}}async getQueryTime(e){return this.supportTimeQuery?this.getTimeFromQuerySet(e):0}uploadToGPU(e){let t=this.tensorMap.get(e);if(t.bufferInfo.buffer==null&&(t.bufferInfo.buffer=this.acquireBuffer(t.bufferInfo.byteSize),t.values)){let r=this.bufferManager.acquireUploadBuffer(t.bufferInfo.byteSize,GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC),a=r.getMappedRange();t.dtype==="int32"||t.dtype==="bool"?new Int32Array(a).set(t.values):new Float32Array(a).set(t.values),r.unmap(),this.ensureCommandEncoderReady(),this.ensureComputePassEnded(),this.currentCommandEncoder.copyBufferToBuffer(r,0,t.bufferInfo.buffer,0,t.bufferInfo.byteSize);let n={byteSize:t.bufferInfo.byteSize,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC,buffer:r};this.stagingDisposalQueue.push(n)}}makeUniforms(e){let t=0,r=[];e.forEach(s=>{s.data.length===0&&(s.data=[1]);let i;switch(s.data.length){case 1:i=4;break;case 2:i=8;break;case 3:i=16;break;case 4:i=16;break;default:w.assert(!1,()=>`Unsupported ${s.data.length}D shape`)}t=Math.ceil(t/i)*i,r.push(t),t+=s.data.length*4});let a=new ArrayBuffer(t);e.forEach((s,i)=>{let o=r[i];s.type==="int32"?new Int32Array(a,o,s.data.length).set(s.data):s.type==="uint32"?new Uint32Array(a,o,s.data.length).set(s.data):new Float32Array(a,o,s.data.length).set(s.data)});let n=this.acquireBuffer(t,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);return this.queue.writeBuffer(n,0,a,0,t),{offset:0,size:t,buffer:n}}createLayout(e){let t=[];t.push({binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}});for(let n=0;n<e;n++)t.push({binding:n+1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}});t.push({binding:e+1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}});let r=this.device.createBindGroupLayout({entries:t}),a=this.device.createPipelineLayout({bindGroupLayouts:[r]});return{bindGroupLayout:r,pipelineLayout:a}}getCachedOrCreateLayout(e){return e in this.layoutCache||(this.layoutCache[e]=this.createLayout(e)),this.layoutCache[e]}runWebGPUProgram(e,t,r,a,n){if(!n){if(n=this.makeTensorInfo(e.outputShape,r),w.sizeFromShape(n.shape)===0){let T=this.tensorMap.get(n.dataId);return T.values=w.getTypedArrayFromDType(n.dtype,0),n}this.uploadToGPU(n.dataId)}let s=[{type:"float32",data:[NaN]}],i=t.concat(n).map(T=>T.shape),o="int32";i.map(T=>{s.push({type:o,data:T})});let l=w.computeStrides(n.shape);if(s.push({type:o,data:l}),e.size){let T=w.sizeFromShape(e.outputShape);s.push({type:o,data:[e.isVec4?T/4:T]})}a&&(s=[...s,...a]);let d=this.makeUniforms(s),u=t.map((T,E)=>{if(T.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(T.dataId),{dtype:this.tensorMap.get(T.dataId).dtype,shape:T.shape,name:e.variableNames[E]}}),p=u.map(T=>T.dtype).concat(n.dtype),h=u.map(T=>N.getBroadcastDims(T.shape,n.shape)),c=u.map(T=>w.arraysEqual(T.shape,n.shape)).join("_"),f=h.map(T=>T.join("_")).join(";"),m=Z8(e,i,p,f,c),{bindGroupLayout:g,pipelineLayout:y}=this.getCachedOrCreateLayout(e.variableNames.length),A=this.getAndSavePipeline(m,()=>X8(this.device,e,y,u,n)),x=this.activeTimers!=null,b=Nhe(this.device,g,t.map(T=>this.tensorToBinding(T)),this.tensorToBinding(n),d);this.ensureCommandEncoderReady();let v=this.getComputePass();x&&this.supportTimeQuery&&v.writeTimestamp(this.querySet,0),v.setPipeline(A),v.setBindGroup(0,b),v.dispatch(e.dispatch[0],e.dispatch[1],e.dispatch[2]),x&&this.supportTimeQuery&&v.writeTimestamp(this.querySet,1),this.dispatchNumberInEncoder++,t.forEach(T=>{this.commandQueueOwnedIds.add(T.dataId)}),this.commandQueueOwnedIds.add(n.dataId);let C={byteSize:d.size,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM,buffer:d.buffer};return this.uniformDisposalQueue.push(C),Y().get("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE")<=this.dispatchNumberInEncoder&&this.submitQueue(),x&&this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(this.querySet)}),n}runFromPixelsProgram(e,t,r,a,n){let s=this.device.createBindGroup({layout:r.bindGroupLayout,entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:a},{binding:2,resource:{buffer:e.uniform}}]});this.ensureCommandEncoderReady();let i=this.getComputePass(),o=this.activeTimers!=null;o&&this.supportTimeQuery&&i.writeTimestamp(this.querySet,0),i.setPipeline(e.pipeline),i.setBindGroup(0,s),i.dispatch(e.dispatch[0],e.dispatch[1],e.dispatch[2]),o&&this.supportTimeQuery&&i.writeTimestamp(this.querySet,1),this.commandQueueOwnedIds.add(n),this.submitQueue(),o&&this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(this.querySet)})}async getTimeFromQuerySet(e){let t=this.acquireBuffer(16,GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE),r=this.acquireBuffer(16,GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST);this.ensureCommandEncoderReady(),this.ensureComputePassEnded(),this.currentCommandEncoder.resolveQuerySet(e,0,2,t,0),this.currentCommandEncoder.copyBufferToBuffer(t,0,r,0,16),this.submitQueue(),await r.mapAsync(GPUMapMode.READ);let a=new BigUint64Array(r.getMappedRange()),n=Number(a[1]-a[0]);return r.unmap(),this.bufferManager.releaseBuffer(r,16,GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST),this.bufferManager.releaseBuffer(t,16,GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE),n/1e6}shouldExecuteOnCPU(e,t=Xfe){return Y().getBool("WEBGPU_CPU_FORWARD")&&e.every(r=>this.tensorMap.get(r.dataId).bufferInfo.buffer==null&&w.sizeFromShape(r.shape)<t)}numDataIds(){return this.tensorMap.numDataIds()-this.tensorDisposalQueue.length}dispose(){this.disposed||(this.bufferManager.dispose(),this.fromPixelProgram&&this.fromPixelProgram.dispose(),this.fromPixelImportProgram&&this.fromPixelImportProgram.dispose(),this.disposed=!0)}},Hx=nS;Hx.nextDataId=0;var sS={};De(sS,{WebGPUBackend:()=>Hx,webgpu_util:()=>M8});Vx()&&Al("webgpu",async()=>{Y().set("CHECK_COMPUTATION_FOR_ERRORS",!1);let e={powerPreference:Y().get("WEBGPU_USE_LOW_POWER_GPU")?"low-power":"high-performance"},t=await navigator.gpu.requestAdapter(e),r={},a=t.features.has("timestamp-query");a?r={requiredFeatures:["timestamp-query"]}:console.warn("This device doesn't support timestamp-query extension. Start Chrome browser with flag --disable-dawn-features=disallow_unsafe_apis then try again. Or zero will shown for the kernel time when profiling mode isenabled. Using performance.now is not workable for webgpu sinceit doesn't support synchronously to read data from GPU.");let n=await t.requestDevice(r);return new Hx(n,a)},3);var Gt=(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",e))(Gt||{}),n0=(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",e))(n0||{}),iS;function Zfe(e){iS=e.wasm.cwrap(Rs,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function Yfe(e){let{inputs:t,backend:r,attrs:a}=e,{a:n,b:s,bias:i,preluActivationWeights:o}=t;if(n.dtype!=="float32"||s.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:l,transposeB:d,activation:u,leakyreluAlpha:p}=a,h=r.dataIdMap.get(n.dataId).id,c=r.dataIdMap.get(s.dataId).id,f=0;if(i!=null){let E=r.dataIdMap.get(i.dataId);if(E.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${E.shape.length}.`);f=E.id}let m=o==null?0:r.dataIdMap.get(o.dataId).id,g=n0[u];if(g==null)throw new Error(`${u} activation not yet supported for FusedConv2D in the wasm backend.`);let y=l?n.shape[2]:n.shape[1],A=d?s.shape[1]:s.shape[2],x=yl.assertAndGetBroadcastShape(n.shape.slice(0,-2),s.shape.slice(0,-2)),b=r.makeOutput([...x,y,A],n.dtype),v=r.dataIdMap.get(b.dataId).id,C=new Uint8Array(new Int32Array(n.shape).buffer),T=new Uint8Array(new Int32Array(s.shape).buffer);return iS(h,C,n.shape.length,c,T,s.shape.length,l,d,g,f,m,p||0,v),b}var Jfe={kernelName:Rs,backendName:"wasm",setupFunc:Zfe,kernelFunc:Yfe};function br(e,t){let r;function a(s){r=s.wasm.cwrap(e,null,["number","number","number"])}function n(s){let{backend:i,inputs:{x:o}}=s,l=i.dataIdMap.get(o.dataId).id,d=i.makeOutput(o.shape,t||o.dtype),u=i.dataIdMap.get(d.dataId).id;return w.sizeFromShape(d.shape)===0||r(l,Gt[o.dtype],u),d}return{kernelName:e,backendName:"wasm",setupFunc:a,kernelFunc:n}}var Qfe=br(Fo);function Vr(e,t,r){let a;function n(i){a=i.wasm.cwrap(e,null,["number","array","number","number","array","number","number","number"])}function s(i){let{backend:o,inputs:l}=i,{a:d,b:u}=l,p=o.dataIdMap.get(d.dataId).id,h=o.dataIdMap.get(u.dataId).id,c=r!=null?r:d.dtype,f=N.assertAndGetBroadcastShape(d.shape,u.shape),m=o.makeOutput(f,c);if(w.sizeFromShape(f)===0)return m;let g=new Uint8Array(new Int32Array(d.shape).buffer),y=new Uint8Array(new Int32Array(u.shape).buffer),A=o.dataIdMap.get(m.dataId).id;return a(p,g,d.shape.length,h,y,u.shape.length,Gt[d.dtype],A),m}return{kernelName:e,backendName:"wasm",setupFunc:n,kernelFunc:s}}var eme=!0,tme=Vr(qn,eme),oS;function rme(e){oS=e.wasm.cwrap(js,null,["array","number","number","number"])}function ame(e){let{inputs:t,backend:r}=e,a=r.makeOutput(t[0].shape,t[0].dtype);if(w.sizeFromShape(a.shape)===0)return a;let n=t.map(o=>r.dataIdMap.get(o.dataId).id),s=new Uint8Array(new Int32Array(n).buffer),i=r.dataIdMap.get(a.dataId).id;return oS(s,n.length,Gt[a.dtype],i),a}var nme={kernelName:js,backendName:"wasm",setupFunc:rme,kernelFunc:ame};function s0(e){let{inputs:{x:t},backend:r}=e,a=r.makeOutput(t.shape,t.dtype),n=r.typedArrayFromHeap(t);return r.typedArrayFromHeap(a).set(n),a}var sme={kernelName:ui,backendName:"wasm",kernelFunc:s0},lS;function ime(e){lS=e.wasm.cwrap(Oi,null,["number","array","number","number","number","array","number"])}function ku(e){let{inputs:t,backend:r,attrs:a}=e,[n,s]=lme(t.x.shape,a.perm),i=!0;for(let f=0;f<s.length;f++)s[f]!==f&&(i=!1);let o=ome(t.x.shape,a.perm),l={dataId:t.x.dataId,shape:n,dtype:t.x.dtype};if(i){let f=s0({inputs:t,backend:r});return f.shape=o,f}let d=r.makeOutput(o,l.dtype),u=r.dataIdMap.get(l.dataId).id,p=r.dataIdMap.get(d.dataId).id,h=new Uint8Array(new Int32Array(s).buffer),c=new Uint8Array(new Int32Array(l.shape).buffer);return lS(u,c,l.shape.length,Gt[l.dtype],p,h,s.length),d}function ome(e,t){let r=new Array(e.length);for(let a=0;a<r.length;a++)r[a]=e[t[a]];return r}function lme(e,t){let r=[],a=[];for(let n=0;n<e.length;++n)e[n]!==1&&r.push(e[n]),e[t[n]]!==1&&a.push(t[n]);for(let n=0;n<a.length;++n){let s=-1;for(let i=0;i<a.length;++i)a[i]>=n&&(s===-1||a[s]>a[i])&&(s=i);a[s]=n}return[r,a]}var ume={kernelName:Oi,backendName:"wasm",kernelFunc:ku,setupFunc:ime};function Vi(e,t,r){let a=e.shape,n=e.shape.length,s=w.parseAxisParam(t,a),i=s,o=N.getAxesPermutation(i,n),l=null,d=!1;if(o!=null){let u=new Array(n);for(let h=0;h<u.length;h++)u[h]=a[o[h]];i=N.getInnerMostAxes(i.length,n),l=ku({inputs:{x:e},attrs:{perm:o},backend:r});let p=r.dataIdMap.get(e.dataId).id;r.dataIdMap.get(l.dataId).id!==p&&(d=!0)}return{transposed:l,originalAxes:s,axes:i,inputWasTransposed:d}}var uS;function dme(e){uS=e.wasm.cwrap(Nu,null,["number, number, number"])}function pme(e){let{backend:t,inputs:r,attrs:a}=e,{axis:n,keepDims:s}=a,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=i,{transposed:d,axes:u,originalAxes:p,inputWasTransposed:h}=Vi(i,n,t);if(h){let A=t.dataIdMap.get(d.dataId).id;l=d,o=A}let c=l.shape.length;N.assertAxesAreInnerMostDims("all",u,c);let[f,m]=N.computeOutAndReduceShapes(l.shape,u),g=w.sizeFromShape(m),y=t.makeOutput(f,i.dtype);if(w.sizeFromShape(l.shape)!==0){let A=t.dataIdMap.get(y.dataId).id;uS(o,g,A)}if(h&&t.disposeData(d.dataId),s){let A=N.expandShapeToKeepDim(y.shape,p);y.shape=A}return y}var hme={kernelName:Nu,backendName:"wasm",setupFunc:dme,kernelFunc:pme},dS;function cme(e){dS=e.wasm.cwrap(Eu,null,["number, number, number"])}function fme(e){let{backend:t,inputs:r,attrs:a}=e,{axis:n,keepDims:s}=a,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=i,{transposed:d,axes:u,originalAxes:p,inputWasTransposed:h}=Vi(i,n,t);if(h){let A=t.dataIdMap.get(d.dataId).id;l=d,o=A}let c=l.shape.length;N.assertAxesAreInnerMostDims("any",u,c);let[f,m]=N.computeOutAndReduceShapes(l.shape,u),g=w.sizeFromShape(m),y=t.makeOutput(f,i.dtype);if(w.sizeFromShape(l.shape)!==0){let A=t.dataIdMap.get(y.dataId).id;dS(o,g,A)}if(h&&t.disposeData(d.dataId),s){let A=N.expandShapeToKeepDim(y.shape,p);y.shape=A}return y}var mme={kernelName:Eu,backendName:"wasm",setupFunc:cme,kernelFunc:fme},pS;function gme(e){pS=e.wasm.cwrap(Hs,null,["number","number","number","number","number"])}function yme(e){let{backend:t,inputs:r,attrs:a}=e,{axis:n}=a,{x:s}=r,i=t.dataIdMap.get(s.dataId).id,o=i,l=s,{transposed:d,axes:u,inputWasTransposed:p}=Vi(s,n,t);if(p){let y=t.dataIdMap.get(d.dataId).id;y!==i&&(l=d,o=y)}let h=l.shape.slice(0,-1),c=t.makeOutput(h,"int32"),f=t.dataIdMap.get(c.dataId).id,m=w.sizeFromShape(c.shape),g=l.shape[u[0]];return pS(o,Gt[l.dtype],m,g,f),p&&t.disposeData(d.dataId),c}var Ame={kernelName:Hs,backendName:"wasm",kernelFunc:yme,setupFunc:gme},hS;function xme(e){hS=e.wasm.cwrap(qs,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function bme(e){let{inputs:t,attrs:r,backend:a}=e,n=t.x,s=a.dataIdMap.get(n.dataId).id,{filterSize:i,strides:o,pad:l,dimRoundingMode:d}=r,u=N.computePool2DInfo(n.shape,i,o,1,l,d),p=u.filterHeight,h=u.filterWidth,c=u.padInfo.top,f=u.padInfo.right,m=u.padInfo.bottom,g=u.padInfo.left,y=u.strideHeight,A=u.strideWidth,x=u.inChannels;if(u.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${u.dataFormat}'. Please use 'channelsLast'.`);if(u.dilationWidth!==1||u.dilationHeight!==1)throw new Error(`was backend only supports average pooling with dilation = [1, 1], got [${u.dilationHeight}, ${u.dilationWidth}].`);let b=a.makeOutput(u.outShape,"float32"),v=a.dataIdMap.get(b.dataId).id;return hS(s,n.shape[0],n.shape[1],n.shape[2],p,h,c,f,m,g,y,A,x,v),b}var vme={kernelName:qs,backendName:"wasm",setupFunc:xme,kernelFunc:bme};function ta(e){let{inputs:t,attrs:r}=e,{x:a}=t,{shape:n}=r,s=w.sizeFromShape(a.shape),i=w.inferFromImplicitShape(n,s);return w.assert(s===w.sizeFromShape(i),()=>`new shape: ${i}, old shape: ${a.shape}. New shape and old shape must have the same number of elements.`),e.backend.incRef(a.dataId),{dataId:a.dataId,shape:i,dtype:a.dtype}}var wme={kernelName:tl,backendName:"wasm",kernelFunc:ta},cS;function kme(e){cS=e.wasm.cwrap(Ks,null,["number","array","number","number","array","number","number","number","number"])}function Ime(e){let{inputs:t,backend:r,attrs:a}=e,{a:n,b:s}=t,{transposeA:i,transposeB:o}=a;if(n.dtype!=="float32"||s.dtype!=="float32")throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");let l=n.shape.length,d=s.shape.length,u=i?n.shape[l-2]:n.shape[l-1],p=o?s.shape[d-1]:s.shape[d-2],h=i?n.shape[l-1]:n.shape[l-2],c=o?s.shape[d-2]:s.shape[d-1],f=n.shape.slice(0,-2),m=s.shape.slice(0,-2),g=w.sizeFromShape(f),y=w.sizeFromShape(m),A=yl.assertAndGetBroadcastShape(n.shape.slice(0,-2),s.shape.slice(0,-2)).concat([h,c]);w.assert(u===p,()=>`Error in matMul: inner shapes (${u}) and (${p}) of Tensors with shapes ${n.shape} and ${s.shape} and transposeA=${i} and transposeB=${o} must match.`);let x=i?[g,u,h]:[g,h,u],b=o?[y,c,p]:[y,p,c],v=ta({inputs:{x:n},backend:r,attrs:{shape:x}}),C=ta({inputs:{x:s},backend:r,attrs:{shape:b}}),T=r.dataIdMap.get(v.dataId).id,E=r.dataIdMap.get(C.dataId).id,R=i?v.shape[2]:v.shape[1],z=o?C.shape[1]:C.shape[2],M=Math.max(g,y),I=r.makeOutput([M,R,z],v.dtype),D=r.dataIdMap.get(I.dataId).id,O=new Uint8Array(new Int32Array(v.shape).buffer),j=new Uint8Array(new Int32Array(C.shape).buffer);return cS(T,O,v.shape.length,E,j,C.shape.length,i,o,D),r.disposeData(v.dataId),r.disposeData(C.dataId),I.shape=A,I}var Sme={kernelName:Ks,backendName:"wasm",setupFunc:kme,kernelFunc:Ime};function No(e){let{inputs:{x:t},attrs:{begin:r,size:a},backend:n}=e,[s,i]=Ot.parseSliceParams(t,r,a),o=Ot.isSliceContinous(t.shape,s,i),l=n.readSync(t.dataId),d=n.makeOutput(i,t.dtype),u=w.computeStrides(t.shape),p=n.dataIdMap.get(d.dataId);if(o){let f=Ot.computeFlatOffset(s,u);return t.dtype==="string"?p.stringBytes=l.slice(f,f+w.sizeFromShape(i)):n.typedArrayFromHeap(d).set(l.subarray(f,f+w.sizeFromShape(i))),d}if(t.dtype==="string"){let f=mf(l,s,i,t.shape,t.dtype);return p.stringBytes=f,d}let h=n.typedArrayFromHeap(d),c=t.shape.length;if(c===2)Tme(l,u[0],h,s,i);else if(c===3)Cme(l,u[0],u[1],h,s,i);else if(c===4)Nme(l,u[0],u[1],u[2],h,s,i);else{let f=mf(l,s,i,t.shape,t.dtype);h.set(f)}return d}function Tme(e,t,r,a,n){let s=0,i=a[0],o=a[1],l=i+n[0];for(let d=i;d<l;d++){let u=d*t+o;r.set(e.subarray(u,u+n[1]),s),s+=n[1]}}function Cme(e,t,r,a,n,s){let i=0,o=n[0],l=n[1],d=n[2],u=o+s[0],p=l+s[1];for(let h=o;h<u;h++)for(let c=l;c<p;c++){let f=h*t+c*r+d;a.set(e.subarray(f,f+s[2]),i),i+=s[2]}}function Nme(e,t,r,a,n,s,i){let o=0,l=s[0],d=s[1],u=s[2],p=l+i[0],h=d+i[1],c=u+i[2],f=s[3];for(let m=l;m<p;m++)for(let g=d;g<h;g++)for(let y=u;y<c;y++){let A=m*t+g*r+y*a+f;n.set(e.subarray(A,A+i[3]),o),o+=i[3]}}var Eme={kernelName:il,backendName:"wasm",kernelFunc:No};function Rme(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{blockShape:s,crops:i}=a,o=s.reduce((y,A)=>y*A),l=N.getReshaped(n.shape,s,o),d=N.getPermuted(l.length,s.length),u=N.getReshapedPermuted(n.shape,s,o),p=N.getSliceBeginCoords(i,s.length),h=N.getSliceSize(u,i,s.length),c=ta({inputs:{x:n},backend:r,attrs:{shape:l}}),f=ku({inputs:{x:c},backend:r,attrs:{perm:d}}),m=ta({inputs:{x:f},backend:r,attrs:{shape:u}}),g=No({inputs:{x:m},backend:r,attrs:{begin:p,size:h}});return r.disposeData(c.dataId),r.disposeData(f.dataId),r.disposeData(c.dataId),g}var Fme={kernelName:Mo,backendName:"wasm",kernelFunc:Rme};function zh(e){let{inputs:{x:t},attrs:{dtype:r},backend:a}=e,n=a.makeOutput(t.shape,r),s=a.typedArrayFromHeap(t);return a.typedArrayFromHeap(n).set(s),n}var Mme={kernelName:Xs,backendName:"wasm",kernelFunc:zh},$me=br(Zs),fS;function Pme(e){fS=e.wasm.cwrap(Kn,null,["number","number","number","number"])}function Ome(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{clipValueMin:s,clipValueMax:i}=a,o=r.dataIdMap.get(n.dataId).id,l=r.makeOutput(n.shape,n.dtype),d=r.dataIdMap.get(l.dataId).id;return fS(o,s,i,d),l}var zme={kernelName:Kn,backendName:"wasm",setupFunc:Pme,kernelFunc:Ome};function mS(e){let{inputs:t,backend:r}=e,a=w.parseAxisParam(e.attrs.axis,t[0].shape)[0],n=N.computeOutShape(t.map(c=>c.shape),a),s=t.filter(c=>w.sizeFromShape(c.shape)>0);if(s.length===1)return s0({inputs:{x:s[0]},backend:r});let i=r.makeOutput(n,t[0].dtype);if(w.sizeFromShape(n)===0)return i;let o=s.map(c=>c.shape);if(N.assertParamsConsistent(o,a),s[0].dtype==="string"){let c=s.map(x=>{let b=w.sizeFromShape(x.shape.slice(a));return ta({inputs:{x},backend:r,attrs:{shape:[-1,b]}})}),f=c.map(x=>({vals:r.readSync(x.dataId),shape:x.shape}));n=N.computeOutShape(c.map(x=>x.shape),1);let m=c[0].shape[0]===1,g=yx(f,n,t[0].dtype,m),y=N.computeOutShape(s.map(x=>x.shape),a);i.shape=y;let A=r.dataIdMap.get(i.dataId);return A.stringBytes=N.fromStringArrayToUint8(g),c.forEach(x=>r.disposeData(x.dataId)),i}let l=w.sizeFromShape(s[0].shape.slice(0,a)),d=0,u=s.map(c=>{let f=w.sizeFromShape(c.shape.slice(a));return d+=f,f}),p=s.map(c=>r.typedArrayFromHeap(c)),h=r.typedArrayFromHeap(i);for(let c=0;c<l;c++){let f=c*d;for(let m=0;m<p.length;m++){let g=u[m],y=c*g,A=p[m].subarray(y,y+g);h.set(A,f),f+=g}}return i}var Dme={kernelName:$o,backendName:"wasm",kernelFunc:mS},gS;function _me(e){gS=e.wasm.cwrap(Ys,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Lme(e){let{inputs:t,attrs:r,backend:a}=e,{x:n,filter:s}=t,i=a.dataIdMap.get(n.dataId).id,o=a.dataIdMap.get(s.dataId).id,{strides:l,dilations:d,pad:u,dimRoundingMode:p,dataFormat:h}=r,c=N.convertConv2DDataFormat(h),f=N.computeConv2DInfo(n.shape,s.shape,l,d,u,p,!1,c),m=f.filterHeight,g=f.filterWidth,y=f.padInfo.top,A=f.padInfo.right,x=f.padInfo.bottom,b=f.padInfo.left,v=f.dilationHeight,C=f.dilationWidth,T=f.strideHeight,E=f.strideWidth,R=f.inChannels,z=f.outChannels,M=f.padInfo.type==="SAME"?1:0;if(f.dataFormat!=="channelsLast")throw new Error(`wasm backend Conv2D does not support dataFormat:'${f.dataFormat}'. Please use 'channelsLast'.`);let I=a.makeOutput(f.outShape,"float32"),D=a.dataIdMap.get(I.dataId).id;return gS(i,n.shape[0],n.shape[1],n.shape[2],o,m,g,y,A,x,b,M,v,C,T,E,R,z,D),I}var Bme={kernelName:Ys,backendName:"wasm",setupFunc:_me,kernelFunc:Lme},yS;function Wme(e){yS=e.wasm.cwrap(Js,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 Vme(e){let{backend:t,inputs:r,attrs:a}=e,{dy:n,filter:s}=r,{strides:i,pad:o,dataFormat:l,dimRoundingMode:d,inputShape:u}=a,p=1,h=N.convertConv2DDataFormat(l),c=N.computeConv2DInfo(u,s.shape,i,p,o,d,!1,h),{batchSize:f,filterHeight:m,filterWidth:g,inChannels:y,inHeight:A,inWidth:x,outChannels:b,outHeight:v,outWidth:C,strideHeight:T,strideWidth:E}=c,R=m-1-c.padInfo.top,z=g-1-c.padInfo.left,M=c.dataFormat==="channelsLast",I=w.computeStrides(c.inShape),D=w.computeStrides(n.shape),[O,j,X]=w.computeStrides(s.shape),_=I[0],K=M?I[1]:I[2],W=M?I[2]:1,ee=M?1:I[1],Q=D[0],ne=M?D[1]:D[2],Z=M?D[2]:1,ae=M?1:D[1],ie=t.makeOutput(c.inShape,"float32"),xe=t.dataIdMap.get(ie.dataId).id,be=t.dataIdMap.get(n.dataId).id,Te=t.dataIdMap.get(s.dataId).id;return yS(be,Te,f,m,g,A,x,y,v,C,b,T,E,R,z,O,j,X,_,K,W,ee,Q,ne,Z,ae,xe),ie}var Ume={kernelName:Js,backendName:"wasm",setupFunc:Wme,kernelFunc:Vme},Gme=br(Qs),jme=br(ei),AS=(e=>(e[e.bilinear=0]="bilinear",e[e.nearest=1]="nearest",e))(AS||{}),xS;function Hme(e){xS=e.wasm.cwrap(Oo,null,["number","number","number","number","array","number","number","number","number","number"])}function qme(e){let{backend:t,inputs:r,attrs:a}=e,{method:n,extrapolationValue:s,cropSize:i}=a,{image:o,boxes:l,boxInd:d}=r,u=l.shape[0],[p,h]=i,c=[u,p,h,o.shape[3]],f=t.dataIdMap.get(o.dataId),m;o.dtype!=="float32"&&(m=zh({backend:t,inputs:{x:o},attrs:{dtype:"float32"}}),f=t.dataIdMap.get(m.dataId));let g=f.id,y=t.dataIdMap.get(l.dataId).id,A=t.dataIdMap.get(d.dataId).id,x=t.makeOutput(c,"float32"),b=t.dataIdMap.get(x.dataId).id,v=new Uint8Array(new Int32Array(o.shape).buffer);return xS(g,y,A,u,v,p,h,AS[n],s,b),m!=null&&t.disposeData(m.dataId),x}var Kme={kernelName:Oo,backendName:"wasm",setupFunc:Hme,kernelFunc:qme},bS;function Xme(e){bS=e.wasm.cwrap(Po,null,["number","number","number","number","number","number"])}function Zme(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{axis:s,exclusive:i,reverse:o}=a,l=n.shape.length;w.assert(n.dtype==="float32"||n.dtype==="int32",()=>`cumsum does not support ${n.dtype} tensors in the WASM backend`);let d=N.getAxesPermutation([s],l),u=n;d!==null&&(u=ku({inputs:{x:n},attrs:{perm:d},backend:r}));let p=N.getInnerMostAxes(1,l)[0];N.assertAxesAreInnerMostDims("cumsum",[p],l);let h=r.makeOutput(u.shape,u.dtype),c=u.shape[p],f=r.dataIdMap.get(u.dataId).id,m=r.dataIdMap.get(h.dataId).id;bS(f,i?1:0,o?1:0,c,m,Gt[n.dtype]);let g=h;if(d!==null){let y=N.getUndoAxesPermutation(d);g=ku({inputs:{x:h},attrs:{perm:y},backend:r}),r.disposeData(u.dataId),r.disposeData(h.dataId)}return g}var Yme={kernelName:Po,backendName:"wasm",setupFunc:Xme,kernelFunc:Zme},vS;function Jme(e){vS=e.wasm.cwrap(zo,null,["number","number","number","array","number","array","array","number","number"])}function Qme(e){let{backend:t,inputs:r,attrs:a}=e,{x:n}=r,{blockSize:s,dataFormat:i}=a,o=n.shape[0],l=i==="NHWC"?n.shape[1]:n.shape[2],d=i==="NHWC"?n.shape[2]:n.shape[3],u=i==="NHWC"?n.shape[3]:n.shape[1],p=l*s,h=d*s,c=u/(s*s),f=i==="NHWC"?[o,p,h,c]:[o,c,p,h],m=t.makeOutput(f,"float32"),g=t.dataIdMap.get(n.dataId).id,y=new Uint8Array(new Int32Array(w.computeStrides(n.shape)).buffer),A=new Uint8Array(new Int32Array(f).buffer),x=new Uint8Array(new Int32Array(w.computeStrides(f)).buffer),b=t.dataIdMap.get(m.dataId).id;return vS(g,s,i==="NHWC"?1:0,y,n.shape.length-1,A,x,f.length,b),m}var e0e={kernelName:zo,backendName:"wasm",setupFunc:Jme,kernelFunc:Qme},wS;function t0e(e){wS=e.wasm.cwrap(ti,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function r0e(e){let{inputs:t,attrs:r,backend:a}=e,{x:n,filter:s}=t,i=a.dataIdMap.get(n.dataId).id,o=a.dataIdMap.get(s.dataId).id,{strides:l,dilations:d,pad:u,dimRoundingMode:p}=r,h=d==null?[1,1]:d,c=N.computeConv2DInfo(n.shape,s.shape,l,h,u,p,!0),f=c.filterHeight,m=c.filterWidth,g=c.padInfo.top,y=c.padInfo.right,A=c.padInfo.bottom,x=c.padInfo.left,b=c.dilationHeight,v=c.dilationWidth,C=c.strideHeight,T=c.strideWidth,E=c.inChannels,R=c.outChannels,z=c.padInfo.type==="SAME"?1:0;if(c.dataFormat!=="channelsLast")throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${c.dataFormat}'. Please use 'channelsLast'.`);let M=a.makeOutput(c.outShape,"float32"),I=a.dataIdMap.get(M.dataId).id;return wS(i,n.shape[0],n.shape[1],n.shape[2],o,f,m,g,y,A,x,z,b,v,C,T,E,R,I),M}var a0e={kernelName:ti,backendName:"wasm",setupFunc:t0e,kernelFunc:r0e},n0e=br(ai),s0e=!1,i0e=Vr(Do,s0e,"bool"),o0e=br(ni,"float32");function Ey(e){let{inputs:t,attrs:r,backend:a}=e,{input:n}=t,{dim:s}=r,i=n.shape.length,o=n.shape.slice(),l=s;return s<0&&(w.assert(-(i+1)<=s,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+s+1),o.splice(l,0,1),ta({inputs:{x:n},backend:a,attrs:{shape:o}})}var l0e={kernelName:_o,backendName:"wasm",kernelFunc:Ey};function kS(e){let{attrs:{shape:t,value:r,dtype:a},backend:n}=e,s=n.makeOutput(t,a);return n.typedArrayFromHeap(s).fill(r),s}var u0e={kernelName:Du,backendName:"wasm",kernelFunc:kS},IS;function d0e(e){IS=e.wasm.cwrap(Bo,null,["number","number","number","number","number","number"])}function p0e(e){let{inputs:t,backend:r}=e,{image:a}=t,n=r.makeOutput(a.shape,a.dtype),s=r.dataIdMap.get(a.dataId).id,i=r.dataIdMap.get(n.dataId).id,[o,l,d,u]=a.shape;return IS(s,o,l,d,u,i),n}var h0e={kernelName:Bo,backendName:"wasm",kernelFunc:p0e,setupFunc:d0e},c0e=br(si),f0e=!1,m0e=Vr(ii,f0e),SS;function g0e(e){SS=e.wasm.cwrap(oi,null,["number","number","number","number","number","number","number"])}function y0e(e){let{backend:t,inputs:r,attrs:a}=e,{varianceEpsilon:n}=a,{x:s,mean:i,variance:o,offset:l,scale:d}=r,u=t.dataIdMap.get(s.dataId).id,p=t.dataIdMap.get(i.dataId).id,h=t.dataIdMap.get(o.dataId).id,c=l!=null?t.dataIdMap.get(l.dataId).id:0,f=d!=null?t.dataIdMap.get(d.dataId).id:0,m=t.makeOutput(s.shape,s.dtype);if(w.sizeFromShape(s.shape)===0)return m;let g=t.dataIdMap.get(m.dataId).id;return SS(u,p,h,c,f,n,g),m}var A0e={kernelName:oi,backendName:"wasm",setupFunc:g0e,kernelFunc:y0e},TS;function x0e(e){TS=e.wasm.cwrap(Fs,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 b0e(e){let{inputs:t,attrs:r,backend:a}=e,{x:n,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:d,dilations:u,dataFormat:p,dimRoundingMode:h,activation:c,leakyreluAlpha:f}=r,m=N.computeConv2DInfo(n.shape,s.shape,l,u,d,h),g=n0[c];if(g==null)throw new Error(`${c} activation not yet supported for FusedConv2D in the wasm backend.`);let y=a.dataIdMap.get(n.dataId).id,A=a.dataIdMap.get(s.dataId).id,x=m.outChannels,b=0;if(i!=null){let Z=a.dataIdMap.get(i.dataId);if(Z.shape.length!==1)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${Z.shape.length}.`);if(Z.shape[0]!==x)throw new Error(`FusedConv2D bias shape (${Z.shape}) does not match the number of output channels (${x})`);b=Z.id}let v=m.filterHeight,C=m.filterWidth,T=m.padInfo.top,E=m.padInfo.right,R=m.padInfo.bottom,z=m.padInfo.left,M=m.dilationHeight,I=m.dilationWidth,D=m.strideHeight,O=m.strideWidth,j=m.inChannels,X=m.padInfo.type==="SAME"?1:0,_=m.batchSize,K=m.inHeight,W=m.inWidth;if(p!=="NHWC")throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);let ee=a.makeOutput(m.outShape,"float32"),Q=a.dataIdMap.get(ee.dataId).id,ne=o==null?0:a.dataIdMap.get(o.dataId).id;return TS(y,_,K,W,A,v,C,b,T,E,R,z,X,M,I,D,O,j,x,g,ne,f||0,Q),ee}var v0e={kernelName:Fs,backendName:"wasm",setupFunc:x0e,kernelFunc:b0e},CS;function w0e(e){CS=e.wasm.cwrap(Ms,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 k0e(e){let{inputs:t,attrs:r,backend:a}=e,{x:n,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:d,dilations:u,dataFormat:p,dimRoundingMode:h,activation:c,leakyreluAlpha:f}=r,m=N.computeConv2DInfo(n.shape,s.shape,l,u,d,h,!0),g=n0[c];if(g==null)throw new Error(`${c} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);let y=a.dataIdMap.get(n.dataId).id,A=a.dataIdMap.get(s.dataId).id,x=m.outChannels,b=0;if(i!=null){let Z=a.dataIdMap.get(i.dataId);if(Z.shape.length!==1)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${Z.shape.length}.`);if(Z.shape[0]!==x)throw new Error(`FusedDepthwiseConv2D bias shape (${Z.shape}) does not match the number of output channels (${x})`);b=Z.id}let v=m.filterHeight,C=m.filterWidth,T=m.padInfo.top,E=m.padInfo.right,R=m.padInfo.bottom,z=m.padInfo.left,M=m.dilationHeight,I=m.dilationWidth,D=m.strideHeight,O=m.strideWidth,j=m.inChannels,X=m.padInfo.type==="SAME"?1:0,_=m.batchSize,K=m.inHeight,W=m.inWidth;if(p!=="NHWC")throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);let ee=a.makeOutput(m.outShape,"float32"),Q=a.dataIdMap.get(ee.dataId).id,ne=o==null?0:a.dataIdMap.get(o.dataId).id;return CS(y,_,K,W,A,v,C,b,T,E,R,z,X,M,I,D,O,j,x,g,ne,f||0,Q),ee}var I0e={kernelName:Ms,backendName:"wasm",setupFunc:w0e,kernelFunc:k0e},NS;function S0e(e){NS=e.wasm.cwrap(Vo,null,["number","number","number","number","number","number","array","number"])}function T0e(e){let{backend:t,inputs:r}=e,{params:a,indices:n}=r,[s,i,o,l]=Gy.prepareAndValidate(a,n),d=t.makeOutput(s,a.dtype);if(i===0)return d;let u=n.shape,p=u[u.length-1],h=t.dataIdMap.get(a.dataId).id,c=t.dataIdMap.get(n.dataId).id,f=new Uint8Array(new Int32Array(l).buffer),m=t.dataIdMap.get(d.dataId).id;return NS(h,Gt[a.dtype],c,i,p,o,f,m),d}var C0e={kernelName:Vo,backendName:"wasm",setupFunc:S0e,kernelFunc:T0e},ES;function N0e(e){ES=e.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function E0e(e){let{backend:t,inputs:r,attrs:a}=e,{x:n,indices:s}=r,{axis:i,batchDims:o}=a,l=w.parseAxisParam(i,n.shape)[0],d=t.readSync(s.dataId),u=n.shape[l];for(let T=0;T<d.length;++T){let E=d[T];w.assert(E<=u-1&&E>=0,()=>`GatherV2: the index value ${E} is not in [0, ${u-1}]`)}let p=N.segment_util.collectGatherOpShapeInfo(n,s,l,o),h=ta({inputs:{x:n},attrs:{shape:[p.batchSize,p.outerSize,p.dimSize,p.sliceSize]},backend:t}),c=w.sizeFromShape(s.shape),f=ta({inputs:{x:s},attrs:{shape:[p.batchSize,c/p.batchSize]},backend:t}),m=[p.batchSize,p.outerSize,c/p.batchSize,p.sliceSize],g=t.makeOutput(m,n.dtype);if(w.sizeFromShape(n.shape)===0)return g;let y=h.shape.length-1,A=t.dataIdMap.get(h.dataId).id,x=t.dataIdMap.get(f.dataId).id,b=t.dataIdMap.get(g.dataId).id,v=new Uint8Array(new Int32Array(w.computeStrides(h.shape)).buffer),C=new Uint8Array(new Int32Array(w.computeStrides(m)).buffer);return ES(A,Gt[n.dtype],v,y,x,p.batchSize,C,b),t.disposeData(h.dataId),t.disposeData(f.dataId),g.shape=p.outputShape,g}var R0e={kernelName:Wo,backendName:"wasm",setupFunc:N0e,kernelFunc:E0e},F0e=!1,M0e=Vr(Uo,F0e,"bool"),$0e=!1,P0e=Vr(li,$0e,"bool"),RS;function O0e(e){RS=e.wasm.cwrap(di,null,["number","number","number","number"])}function z0e(e){let{inputs:{x:t},attrs:{alpha:r},backend:a}=e,n=a.dataIdMap.get(t.dataId).id,s=a.makeOutput(t.shape,"float32");if(w.sizeFromShape(t.shape)!==0){let i=a.dataIdMap.get(s.dataId).id;RS(n,Gt[t.dtype],r,i)}return s}var D0e={kernelName:di,backendName:"wasm",setupFunc:O0e,kernelFunc:z0e},_0e=!1,L0e=Vr(Go,_0e,"bool"),B0e=!1,W0e=Vr(jo,B0e,"bool"),V0e=br(pi),U0e=!1,G0e=Vr(Ho,U0e,"bool"),FS;function j0e(e){FS=e.wasm.cwrap(hi,null,["number","number","number","number"])}function H0e(e){let{backend:t,inputs:r,attrs:a}=e,{reductionIndices:n,keepDims:s}=a,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=i,{transposed:d,axes:u,originalAxes:p,inputWasTransposed:h}=Vi(i,n,t);if(h){let A=t.dataIdMap.get(d.dataId).id;l=d,o=A}let c=l.shape.length;N.assertAxesAreInnerMostDims("max",u,c);let[f,m]=N.computeOutAndReduceShapes(l.shape,u),g=w.sizeFromShape(m),y=t.makeOutput(f,i.dtype);if(w.sizeFromShape(l.shape)!==0){let A=t.dataIdMap.get(y.dataId).id;FS(o,Gt[i.dtype],g,A)}if(h&&t.disposeData(d.dataId),s){let A=N.expandShapeToKeepDim(y.shape,p);y.shape=A}return y}var q0e={kernelName:hi,backendName:"wasm",setupFunc:j0e,kernelFunc:H0e},K0e=!1,X0e=Vr(ci,K0e),MS;function Z0e(e){MS=e.wasm.cwrap(fi,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Y0e(e){let{inputs:t,attrs:r,backend:a}=e,n=t.x,s=a.dataIdMap.get(n.dataId).id;w.assert(n.dtype==="float32",()=>`Error in MaxPool: only float32 input is supported. Got ${n.dtype}.`);let{filterSize:i,strides:o,pad:l,dimRoundingMode:d}=r,u=N.computePool2DInfo(n.shape,i,o,1,l,d),p=u.filterHeight,h=u.filterWidth,c=u.padInfo.top,f=u.padInfo.right,m=u.padInfo.bottom,g=u.padInfo.left,y=u.dilationHeight,A=u.dilationWidth,x=u.strideHeight,b=u.strideWidth,v=u.inChannels,C=u.outChannels;if(u.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${u.dataFormat}'. Please use 'channelsLast'.`);let T=a.makeOutput(u.outShape,"float32"),E=a.dataIdMap.get(T.dataId).id;return MS(s,n.shape[0],n.shape[1],n.shape[2],p,h,c,f,m,g,y,A,x,b,v,C,E),T}var J0e={kernelName:fi,backendName:"wasm",setupFunc:Z0e,kernelFunc:Y0e},$S;function Q0e(e){$S=e.wasm.cwrap(mi,null,["number, number, number"])}function ege(e){let{backend:t,inputs:r,attrs:a}=e,{axis:n,keepDims:s}=a,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=o,d=i,{transposed:u,axes:p,originalAxes:h,inputWasTransposed:c}=Vi(i,n,t),f=p;if(c){let b=t.dataIdMap.get(u.dataId).id;b!==o&&(d=u,l=b,f=N.getInnerMostAxes(f.length,d.shape.length))}N.assertAxesAreInnerMostDims("mean",f,d.shape.length);let[m,g]=N.computeOutAndReduceShapes(d.shape,f),y=w.sizeFromShape(g),A=d;d.dtype!=="float32"&&(A=zh({backend:t,inputs:{x:d},attrs:{dtype:"float32"}}),l=t.dataIdMap.get(A.dataId).id);let x=t.makeOutput(m,"float32");if(w.sizeFromShape(d.shape)!==0){let b=t.dataIdMap.get(x.dataId).id;$S(l,y,b)}if(c&&t.disposeData(u.dataId),s){let b=N.expandShapeToKeepDim(x.shape,h);x.shape=b}return d.dtype!=="float32"&&t.disposeData(A.dataId),x}var tge={kernelName:mi,backendName:"wasm",setupFunc:Q0e,kernelFunc:ege},PS;function rge(e){PS=e.wasm.cwrap(gi,null,["number","number","number","number"])}function age(e){let{backend:t,inputs:r,attrs:a}=e,{axis:n,keepDims:s}=a,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=o,d=i,{transposed:u,axes:p,originalAxes:h,inputWasTransposed:c}=Vi(i,n,t);if(c){let x=t.dataIdMap.get(u.dataId).id;x!==o&&(d=u,l=x)}let f=d.shape.length;N.assertAxesAreInnerMostDims("min",p,f);let[m,g]=N.computeOutAndReduceShapes(d.shape,p),y=w.sizeFromShape(g),A=t.makeOutput(m,d.dtype);if(w.sizeFromShape(d.shape)!==0){let x=t.dataIdMap.get(A.dataId).id;PS(l,Gt[i.dtype],y,x)}if(c&&t.disposeData(u.dataId),s){let x=N.expandShapeToKeepDim(A.shape,h);A.shape=x}return A}var nge={kernelName:gi,backendName:"wasm",setupFunc:rge,kernelFunc:age},sge=!1,ige=Vr(yi,sge),OS=(e=>(e[e.reflect=0]="reflect",e[e.symmetric=1]="symmetric",e))(OS||{}),zS;function oge(e){zS=e.wasm.cwrap(Ai,null,["number","array","number","number","array","array","number","number"])}function lge(e){let{inputs:{x:t},backend:r,attrs:{paddings:a,mode:n}}=e,s=a.map((f,m)=>f[0]+t.shape[m]+f[1]),i=r.dataIdMap.get(t.dataId).id,o=r.makeOutput(s,t.dtype),l=r.dataIdMap.get(o.dataId).id,d=new Uint8Array(new Int32Array(t.shape).buffer),u=a.map(f=>f[0]),p=a.map(f=>f[1]),h=new Uint8Array(new Int32Array(u).buffer),c=new Uint8Array(new Int32Array(p).buffer);return zS(i,d,t.shape.length,Gt[t.dtype],h,c,OS[n],l),o}var uge={kernelName:Ai,backendName:"wasm",kernelFunc:lge,setupFunc:oge},dge=!0,pge=Vr(xi,dge),hge=br(qo);function qx(e,t){let r=new Int32Array(e.wasm.HEAPU8.buffer,t,4),a=r[0],n=r[1],s=r[2],i=r[3];return e.wasm._free(t),{pSelectedIndices:a,selectedSize:n,pSelectedScores:s,pValidOutputs:i}}var DS;function cge(e){DS=e.wasm.cwrap(Xo,"number",["number","number","number","number","number"])}function fge(e){let{backend:t,inputs:r,attrs:a}=e,{iouThreshold:n,maxOutputSize:s,scoreThreshold:i}=a,{boxes:o,scores:l}=r,d=t.dataIdMap.get(o.dataId).id,u=t.dataIdMap.get(l.dataId).id,p=DS(d,u,s,n,i),{pSelectedIndices:h,selectedSize:c,pSelectedScores:f,pValidOutputs:m}=qx(t,p);return t.wasm._free(f),t.wasm._free(m),t.makeOutput([c],"int32",h)}var mge={kernelName:Xo,backendName:"wasm",setupFunc:cge,kernelFunc:fge},_S;function gge(e){_S=e.wasm.cwrap(Gu,"number",["number","number","number","number","number","bool"])}function yge(e){let{backend:t,inputs:r,attrs:a}=e,{iouThreshold:n,maxOutputSize:s,scoreThreshold:i,padToMaxOutputSize:o}=a,{boxes:l,scores:d}=r,u=t.dataIdMap.get(l.dataId).id,p=t.dataIdMap.get(d.dataId).id,h=_S(u,p,s,n,i,o),{pSelectedIndices:c,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=qx(t,h);t.wasm._free(m);let y=t.makeOutput([f],"int32",c),A=t.makeOutput([],"int32",g);return[y,A]}var Age={kernelName:Gu,backendName:"wasm",setupFunc:gge,kernelFunc:yge},LS;function xge(e){LS=e.wasm.cwrap(Zo,"number",["number","number","number","number","number","number"])}function bge(e){let{backend:t,inputs:r,attrs:a}=e,{iouThreshold:n,maxOutputSize:s,scoreThreshold:i,softNmsSigma:o}=a,{boxes:l,scores:d}=r,u=t.dataIdMap.get(l.dataId).id,p=t.dataIdMap.get(d.dataId).id,h=LS(u,p,s,n,i,o),{pSelectedIndices:c,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=qx(t,h);t.wasm._free(g);let y=t.makeOutput([f],"int32",c),A=t.makeOutput([f],"float32",m);return[y,A]}var vge={kernelName:Zo,backendName:"wasm",setupFunc:xge,kernelFunc:bge},wge=!1,kge=Vr(Ko,wge,"bool"),BS;function Ige(e){BS=e.wasm.cwrap(Jo,null,["number","number","number","number","number"])}function Sge(e){let{inputs:t,backend:r,attrs:a}=e,{indices:n}=t,{depth:s,onValue:i,offValue:o}=a,l=r.makeOutput([...n.shape,s],"int32"),d=r.dataIdMap.get(l.dataId).id,u=r.dataIdMap.get(n.dataId).id;return BS(u,s,i,o,d),l}var Tge={kernelName:Jo,backendName:"wasm",setupFunc:Ige,kernelFunc:Sge};function Cge(e){let{inputs:{x:t},backend:r}=e,a=r.makeOutput(t.shape,t.dtype);return r.typedArrayFromHeap(a).fill(1),a}var Nge={kernelName:Yo,backendName:"wasm",kernelFunc:Cge};function Ege(e){let{inputs:t,backend:r,attrs:a}=e,{axis:n}=a;if(t.length===1)return Ey({inputs:{input:t[0]},backend:r,attrs:{dim:n}});let s=t[0].shape,i=t[0].dtype;t.forEach(u=>{w.assertShapesMatch(s,u.shape,"All tensors passed to stack must have matching shapes"),w.assert(i===u.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(u=>{let p=Ey({inputs:{input:u},backend:r,attrs:{dim:n}});return o.push(p),p}),d=mS({inputs:l,backend:r,attrs:{axis:n}});return o.forEach(u=>r.disposeData(u.dataId)),d}var Rge={kernelName:Qo,backendName:"wasm",kernelFunc:Ege},WS;function Fge(e){WS=e.wasm.cwrap(bi,null,["number","array","number","number","array","array","number","number"])}function Mge(e){let{inputs:{x:t},backend:r,attrs:{paddings:a,constantValue:n}}=e,s=a.map((f,m)=>f[0]+t.shape[m]+f[1]);if(w.sizeFromShape(t.shape)===0)return kS({backend:r,attrs:{shape:s,value:n,dtype:t.dtype}});let i=r.dataIdMap.get(t.dataId).id,o=r.makeOutput(s,t.dtype),l=r.dataIdMap.get(o.dataId).id,d=new Uint8Array(new Int32Array(t.shape).buffer),u=a.map(f=>f[0]),p=a.map(f=>f[1]),h=new Uint8Array(new Int32Array(u).buffer),c=new Uint8Array(new Int32Array(p).buffer);return WS(i,d,t.shape.length,Gt[t.dtype],h,c,n,l),o}var VS={kernelName:bi,backendName:"wasm",kernelFunc:Mge,setupFunc:Fge},$ge=!1,Pge=Vr(vi,$ge),US;function Oge(e){US=e.wasm.cwrap(wi,null,["number","number","number"])}function zge(e){let{inputs:t,backend:r}=e,{x:a,alpha:n}=t,s=r.dataIdMap.get(a.dataId).id,i=r.dataIdMap.get(n.dataId).id,o=s,l=a,d=l;l.dtype!=="float32"&&(d=zh({backend:r,inputs:{x:a},attrs:{dtype:"float32"}}),o=r.dataIdMap.get(d.dataId).id);let u=r.makeOutput(a.shape,"float32"),p=r.dataIdMap.get(u.dataId).id;return US(o,i,p),l.dtype!=="float32"&&r.disposeData(d.dataId),u}var Dge={kernelName:wi,backendName:"wasm",setupFunc:Oge,kernelFunc:zge},GS;function _ge(e){GS=e.wasm.cwrap(el,null,["number","number","number","number"])}function Lge(e){let{backend:t,inputs:r,attrs:a}=e,{axis:n,keepDims:s}=a,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=o,d=i,{transposed:u,axes:p,originalAxes:h,inputWasTransposed:c}=Vi(i,n,t),f=p;if(c){let x=t.dataIdMap.get(u.dataId).id;x!==o&&(d=u,l=x,f=N.getInnerMostAxes(f.length,d.shape.length))}N.assertAxesAreInnerMostDims("prod",f,d.shape.length);let[m,g]=N.computeOutAndReduceShapes(d.shape,f),y=w.sizeFromShape(g),A=t.makeOutput(m,d.dtype);if(w.sizeFromShape(d.shape)!==0){let x=t.dataIdMap.get(A.dataId).id;GS(l,y,Gt[A.dtype],x)}if(c&&t.disposeData(u.dataId),s){let x=N.expandShapeToKeepDim(A.shape,h);A.shape=x}return A}var Bge={kernelName:el,backendName:"wasm",setupFunc:_ge,kernelFunc:Lge},Wge=e=>{let{backend:t,attrs:r}=e,{start:a,stop:n,step:s,dtype:i}=r,o=bx(a,n,s,i),l=t.makeOutput([o.length],i);return t.typedArrayFromHeap(l).set(o),l},Vge={kernelName:ju,backendName:"wasm",kernelFunc:Wge},Uge=!0,Gge=Vr(ri,Uge),jge=br(ki),Hge=br(Si),jS;function qge(e){jS=e.wasm.cwrap(Ii,null,["number","number","number","number","number","number","number","number","number","number"])}function Kge(e){let{backend:t,inputs:r,attrs:a}=e,{images:n}=r,{alignCorners:s,halfPixelCenters:i,size:o}=a,[l,d]=o,[u,p,h,c]=n.shape,f=[u,l,d,c],m=t.dataIdMap.get(n.dataId),g;m.dtype!=="float32"&&(g=zh({backend:t,inputs:{x:n},attrs:{dtype:"float32"}}),m=t.dataIdMap.get(g.dataId));let y=m.id,A=t.makeOutput(f,"float32");if(w.sizeFromShape(n.shape)===0)return A;let x=t.dataIdMap.get(A.dataId).id;return jS(y,u,p,h,c,l,d,s?1:0,i?1:0,x),g!=null&&t.disposeData(g.dataId),A}var Xge={kernelName:Ii,backendName:"wasm",setupFunc:qge,kernelFunc:Kge},HS;function Zge(e){HS=e.wasm.cwrap(rl,null,["number","array","number","array","number","number"])}function Yge(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{dims:s}=a,i=w.parseAxisParam(s,n.shape);if(n.shape.length===0)return s0({inputs:{x:n},backend:r});let o=r.makeOutput(n.shape,n.dtype),l=r.dataIdMap.get(n.dataId).id,d=r.dataIdMap.get(o.dataId).id,u=new Uint8Array(new Int32Array(i).buffer),p=new Uint8Array(new Int32Array(n.shape).buffer);HS(l,u,i.length,p,n.shape.length,d);let h=ta({inputs:{x:o},attrs:{shape:n.shape},backend:r});return r.disposeData(o.dataId),h}var Jge={kernelName:rl,backendName:"wasm",kernelFunc:Yge,setupFunc:Zge},qS;function Qge(e){qS=e.wasm.cwrap(gl,null,["number","number","number","number","number","number","number","number","array","number","number"])}function e1e(e){let{inputs:t,backend:r,attrs:a}=e,{image:n}=t,{radians:s,fillValue:i,center:o}=a,l=r.makeOutput(n.shape,n.dtype),d=r.dataIdMap.get(n.dataId).id,u=r.dataIdMap.get(l.dataId).id,[p,h,c,f]=n.shape,[m,g]=N.getImageCenter(o,h,c),y=i===0,A=255,x=typeof i=="number"?[i,i,i,y?0:A]:[...i,A],b=new Uint8Array(new Int32Array(x).buffer);return qS(d,p,h,c,f,s,m,g,b,x.length,u),l}var t1e={kernelName:gl,backendName:"wasm",kernelFunc:e1e,setupFunc:Qge},r1e=br(al),a1e=br(Ti),KS;function n1e(e){KS=e.wasm.cwrap(nl,null,["number","number","number","number","number","number","array","number","number"])}function s1e(e){let{backend:t,inputs:r,attrs:a}=e,{indices:n,updates:s}=r,{shape:i}=a,o=t.makeOutput(i,s.dtype);if(w.sizeFromShape(i)===0)return o;let{sliceRank:l,numUpdates:d,sliceSize:u,strides:p,outputSize:h}=jy.calculateShapes(s,n,i),c=t.dataIdMap.get(n.dataId).id,f=t.dataIdMap.get(s.dataId).id,m=new Uint8Array(new Int32Array(p).buffer),g=t.dataIdMap.get(o.dataId).id;return KS(c,f,Gt[s.dtype],l,d,u,m,h,g),o}var i1e={kernelName:nl,backendName:"wasm",setupFunc:n1e,kernelFunc:s1e},XS;function o1e(e){XS=e.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function l1e(e){let{inputs:t,backend:r}=e,{condition:a,t:n,e:s}=t,i=r.dataIdMap.get(a.dataId).id,o=r.dataIdMap.get(n.dataId).id,l=r.dataIdMap.get(s.dataId).id,d=r.makeOutput(n.shape,n.dtype),u=r.dataIdMap.get(d.dataId).id,p=a.shape.length,h=n.shape.length,c=p===0||p>1||h===1?1:w.sizeFromShape(n.shape.slice(1));return XS(i,o,l,c,u),d}var u1e={kernelName:sl,backendName:"wasm",kernelFunc:l1e,setupFunc:o1e},ZS;function d1e(e){ZS=e.wasm.cwrap(Ni,null,["number","number"])}function p1e(e){let{backend:t,inputs:{x:r}}=e,a=t.dataIdMap.get(r.dataId).id,n=t.makeOutput(r.shape,r.dtype),s=t.dataIdMap.get(n.dataId).id;return w.sizeFromShape(n.shape)===0||ZS(a,s),n}var h1e={kernelName:"Sigmoid",backendName:"wasm",setupFunc:d1e,kernelFunc:p1e},c1e=br(Ci),YS;function f1e(e){YS=e.wasm.cwrap(Fi,null,["number","number","number","number"])}function m1e(e){let{backend:t,inputs:{logits:r},attrs:{dim:a}}=e,n=t.dataIdMap.get(r.dataId).id,s=t.makeOutput(r.shape,r.dtype),i=t.dataIdMap.get(s.dataId).id,o=r.shape[a],l=w.sizeFromShape(r.shape)/o;return w.sizeFromShape(s.shape)===0||YS(n,i,o,l),s}var g1e={kernelName:Fi,backendName:"wasm",setupFunc:f1e,kernelFunc:m1e};function y1e(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,{blockShape:s,paddings:i}=a,o=w.sizeFromShape(s),l=[[0,0]];l.push(...i);for(let g=1+s.length;g<n.shape.length;++g)l.push([0,0]);let d=VS.kernelFunc({inputs:{x:n},backend:r,attrs:{paddings:l,constantValue:0}}),u=N.getReshaped(d.shape,s,o,!1),p=N.getPermuted(u.length,s.length,!1),h=N.getReshapedPermuted(d.shape,s,o,!1),c=ta({inputs:{x:d},backend:r,attrs:{shape:u}}),f=ku({inputs:{x:c},backend:r,attrs:{perm:p}}),m=ta({inputs:{x:f},backend:r,attrs:{shape:h}});return r.disposeData(d.dataId),r.disposeData(c.dataId),r.disposeData(f.dataId),m}var A1e={kernelName:ll,backendName:"wasm",kernelFunc:y1e},JS;function x1e(e){JS=e.wasm.cwrap("SparseFillEmptyRows","number",["number","number","number","number","number","number","number","number","number","number","number","number"])}function b1e(e){let{backend:t,inputs:r}=e,{indices:a,values:n,denseShape:s,defaultValue:i}=r,o=a.shape[0],l=a.shape[1],d=t.readSync(s.dataId)[0],u=[o+d,l],p=t.dataIdMap.get(a.dataId).id,h=t.dataIdMap.get(n.dataId).id,c=t.dataIdMap.get(i.dataId).id,f=t.makeOutput(u,a.dtype),m=t.dataIdMap.get(f.dataId).id,g=t.makeOutput(u.slice(0,1),n.dtype),y=t.dataIdMap.get(g.dataId).id,A=t.makeOutput([d],"bool"),x=t.dataIdMap.get(A.dataId).id,b=t.makeOutput([o],a.dtype),v=t.dataIdMap.get(b.dataId).id,C=t.makeOutput([4],"int32"),T=t.dataIdMap.get(C.dataId).id,E=JS(p,h,Gt[n.dtype],o,d,l,c,m,y,x,v,T),R=t.readSync(C.dataId),z;switch(R[0]){case 1:{z=N.getSparseFillEmptyRowsIndicesDenseShapeMismatch(R[1]);break}case 2:{z=N.getSparseFillEmptyRowsNegativeIndexErrorMessage(R[1],R[2]);break}case 3:z=N.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(R[1],R[2],R[3]);break;default:z=""}if(t.disposeData(C.dataId),z)throw t.disposeData(f.dataId),t.disposeData(g.dataId),t.disposeData(A.dataId),t.disposeData(b.dataId),new Error(z);let M=f,I=g;return E!==u[0]&&(M=No({inputs:{x:f},attrs:{begin:0,size:[E,l]},backend:t}),I=No({inputs:{x:g},attrs:{begin:0,size:E},backend:t}),t.disposeData(f.dataId),t.disposeData(g.dataId)),[M,I,A,b]}var v1e={kernelName:Xp,backendName:"wasm",setupFunc:x1e,kernelFunc:b1e},QS;function w1e(e){QS=e.wasm.cwrap(Yu,null,["number","number","number","number","number","number","number"])}function k1e(e){let{backend:t,inputs:r}=e,{inputIndices:a,inputShape:n,newShape:s}=r;if(a.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
|
|
${a.shape}`);if(n.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
|
|
${n.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(a.dataId).id,o=t.dataIdMap.get(n.dataId).id,l=t.dataIdMap.get(s.dataId).id,d=a.shape[0],u=w.sizeFromShape(s.shape),p=t.makeOutput([d,u],a.dtype),h=t.dataIdMap.get(p.dataId).id,c=t.makeOutput([u],s.dtype),f=t.dataIdMap.get(c.dataId).id,m=t.makeOutput([3],"int32"),g=t.dataIdMap.get(m.dataId).id;QS(i,o,l,d,h,f,g);let y=t.readSync(m.dataId),A;switch(y[0]){case 0:{A=N.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(y[1],y[2]);break}case 1:{A=N.getSparseReshapeNegativeOutputDimErrorMessage(y[1],y[2]);break}case 2:A=N.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage();break;case 3:{let x=Array.from(t.readSync(n.dataId)),b=Array.from(t.readSync(c.dataId));A=N.getSparseReshapeInputOutputMultipleErrorMessage(x,b);break}case 4:{let x=Array.from(t.readSync(n.dataId)),b=Array.from(t.readSync(c.dataId));A=N.getSparseReshapeInputOutputMismatchErrorMessage(x,b);break}default:A=""}if(t.disposeData(m.dataId),A)throw t.disposeData(p.dataId),t.disposeData(c.dataId),new Error(A);return[p,c]}var I1e={kernelName:Yu,backendName:"wasm",setupFunc:w1e,kernelFunc:k1e},eT;function tT(e){eT=e.wasm.cwrap("SparseSegmentReduction",null,["number","number","number","number","number","number","number","number","number"])}function rT(e,t){let{backend:r,inputs:a}=e,{data:n,indices:s,segmentIds:i}=a,o=s.shape[0],l=r.readSync(i.dataId,o-1,o)[0],d=o>0?l+1:0;if(d<0)throw new Error(N.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let u=n.shape.slice();u[0]=d;let p=r.dataIdMap.get(n.dataId).id,h=r.dataIdMap.get(s.dataId).id,c=r.dataIdMap.get(i.dataId).id,f=r.makeOutput(u,n.dtype),m=r.dataIdMap.get(f.dataId).id,g=r.makeOutput([4],"int32"),y=r.dataIdMap.get(g.dataId).id;eT(p,Gt[n.dtype],n.shape[0],h,c,m,y,t,0);let A=r.readSync(g.dataId),x;switch(A[0]){case 0:{x=N.getSparseSegmentReductionNegativeSegmentIdsErrorMessage();break}case 1:{x=N.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage();break}case 2:x=N.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(A[1],A[2]);break;case 3:x=N.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(A[1],A[2],A[3]);break;default:x=""}if(r.disposeData(g.dataId),x)throw r.disposeData(f.dataId),new Error(x);return f}function S1e(e){return rT(e,!0)}var T1e={kernelName:Zp,backendName:"wasm",setupFunc:tT,kernelFunc:S1e};function C1e(e){return rT(e,!1)}var N1e={kernelName:Yp,backendName:"wasm",setupFunc:tT,kernelFunc:C1e};function E1e(e){let{inputs:t,attrs:r,backend:a}=e,{x:n}=t,{numOrSizeSplits:s,axis:i}=r,o=w.parseAxisParam(i,n.shape)[0],l=N.prepareSplitSize(n,s,o),d=new Array(n.shape.length).fill(0),u=n.shape.slice();return l.map(p=>{let h=[...u];h[o]=p;let c=No({inputs:{x:n},attrs:{begin:d,size:h},backend:a});return d[o]+=p,c})}var R1e={kernelName:ul,backendName:"wasm",kernelFunc:E1e},F1e=br(Ei),M1e=br(Ju),$1e=!0,P1e=Vr(Mi,$1e),aT;function O1e(e){aT=e.wasm.cwrap(zi,null,["number","number","number","number"])}function z1e(e){let{backend:t,inputs:r,attrs:a}=e,{alpha:n}=a,{x:s}=r,i=t.dataIdMap.get(s.dataId).id,o=t.makeOutput(s.shape,s.dtype),l=t.dataIdMap.get(o.dataId).id;return aT(i,n,Gt[s.dtype],l),o}var D1e={kernelName:zi,backendName:"wasm",setupFunc:O1e,kernelFunc:z1e},nT;function _1e(e){nT=e.wasm.cwrap(dl,null,["number","array","number","array","array","array","array","array","number","number"])}function L1e(e){let{backend:t,inputs:r,attrs:a}=e,{x:n}=r,{begin:s,end:i,strides:o,beginMask:l,endMask:d,ellipsisMask:u,newAxisMask:p,shrinkAxisMask:h}=a,{finalShapeSparse:c,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:A,end:x,strides:b}=Ot.sliceInfo(n.shape,s,i,o,l,d,u,p,h),v;if(m)v=ta({inputs:{x:n},backend:t,attrs:{shape:f}});else if(g||y){w.assert(n.shape.length>=1,()=>`Input must have rank at least 1, got: ${n.shape.length}`);let C=Ot.computeOutShape(A,x,b),T=No({inputs:{x:n},backend:t,attrs:{begin:A,size:C}});v=ta({inputs:{x:T},backend:t,attrs:{shape:f}}),t.disposeData(T.dataId)}else{let C=t.makeOutput(c,"float32"),T=t.dataIdMap.get(n.dataId).id,E=new Uint8Array(new Int32Array(w.computeStrides(n.shape)).buffer),R=new Uint8Array(new Int32Array(A).buffer),z=new Uint8Array(new Int32Array(x).buffer),M=new Uint8Array(new Int32Array(b).buffer),I=new Uint8Array(new Int32Array(c).buffer),D=new Uint8Array(new Int32Array(w.computeStrides(c)).buffer),O=t.dataIdMap.get(C.dataId).id;nT(T,E,n.shape.length,R,z,M,I,D,c.length,O),v=ta({inputs:{x:C},backend:t,attrs:{shape:f}}),t.disposeData(C.dataId)}return v}var B1e={kernelName:dl,backendName:"wasm",setupFunc:_1e,kernelFunc:L1e},W1e=!0,V1e=Vr($i,W1e),sT;function U1e(e){sT=e.wasm.cwrap(Ri,null,["number","number","number","number"])}function G1e(e){let{backend:t,inputs:r,attrs:a}=e,{axis:n,keepDims:s}=a,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=o,d=i,{transposed:u,axes:p,originalAxes:h,inputWasTransposed:c}=Vi(i,n,t),f=p;if(c){let x=t.dataIdMap.get(u.dataId).id;x!==o&&(d=u,l=x,f=N.getInnerMostAxes(f.length,d.shape.length))}N.assertAxesAreInnerMostDims("sum",f,d.shape.length);let[m,g]=N.computeOutAndReduceShapes(d.shape,f),y=w.sizeFromShape(g),A=t.makeOutput(m,d.dtype);if(w.sizeFromShape(d.shape)!==0){let x=t.dataIdMap.get(A.dataId).id;sT(l,y,Gt[A.dtype],x)}if(c&&t.disposeData(u.dataId),s){let x=N.expandShapeToKeepDim(A.shape,h);A.shape=x}return A}var j1e={kernelName:Ri,backendName:"wasm",setupFunc:U1e,kernelFunc:G1e},H1e=br(pl),q1e=br(Pi),iT;function K1e(e){iT=e.wasm.cwrap(Xn,null,["number","array","number","array","number","number"])}function X1e(e){let{inputs:t,backend:r,attrs:a}=e,{x:n}=t,s=r.dataIdMap.get(n.dataId).id,{reps:i}=a,o=new Array(n.shape.length);for(let h=0;h<o.length;h++)o[h]=n.shape[h]*i[h];let l=new Uint8Array(new Int32Array(n.shape).buffer),d=new Uint8Array(new Int32Array(o).buffer),u=r.makeOutput(o,n.dtype),p=r.dataIdMap.get(u.dataId).id;return iT(s,l,n.shape.length,d,o.length,Gt[u.dtype],p),u}var Z1e={kernelName:Xn,backendName:"wasm",setupFunc:K1e,kernelFunc:X1e},oT;function Y1e(e){oT=e.wasm.cwrap(hl,null,["number","array","number","number","number","bool","number","number"])}var J1e=({inputs:e,backend:t,attrs:r})=>{let{x:a}=e,{k:n,sorted:s}=r,i=t.dataIdMap.get(a.dataId).id,o=new Uint8Array(new Int32Array(a.shape).buffer),l=a.shape.slice();l[l.length-1]=n;let d=t.makeOutput(l,a.dtype),u=t.dataIdMap.get(d.dataId).id,p=t.makeOutput(l,"int32"),h=t.dataIdMap.get(p.dataId).id;return oT(i,o,a.shape.length,Gt[a.dtype],n,s,u,h),[d,p]},Q1e={kernelName:hl,backendName:"wasm",setupFunc:Y1e,kernelFunc:J1e},lT;function eye(e){lT=e.wasm.cwrap(cl,null,["number","number","bool","number","number","number","number","number","number","array","number","number","number","number","number"])}function tye(e){let{backend:t,inputs:r,attrs:a}=e,{image:n,transforms:s}=r,{interpolation:i,fillMode:o,fillValue:l,outputShape:d}=a,[u,p,h,c]=n.shape,[f,m]=d!=null?d:[p,h],g=[u,f,m,c],y=new Uint8Array(new Int32Array(w.computeStrides(n.shape)).buffer),A=t.makeOutput(g,n.dtype),x=t.dataIdMap.get(A.dataId).id,b=t.dataIdMap.get(n.dataId).id,v=t.dataIdMap.get(s.dataId).id,C=i==="nearest"?1:2,T;switch(o){case"constant":T=1;break;case"reflect":T=2;break;case"wrap":T=3;break;case"nearest":T=4;break;default:T=1;break}return lT(b,v,s.shape[0]>1,u,f,m,c,h,p,y,n.shape.length-1,C,T,l,x),A}var rye={kernelName:cl,backendName:"wasm",setupFunc:eye,kernelFunc:tye};function aye(e){let{inputs:t,backend:r,attrs:a}=e,{value:n}=t,{axis:s}=a;s<0&&(s+=n.shape.length);let i=n.shape[s],o=n.shape.length,l=new Array(o-1),d=0;for(let c=0;c<o;c++)c!==s&&(l[d++]=n.shape[c]);let u=new Array(i),p=new Array(o).fill(0),h=n.shape.slice();h[s]=1;for(let c=0;c<u.length;c++)p[s]=c,u[c]=No({inputs:{x:n},attrs:{begin:p,size:h},backend:r});return u.map(({dataId:c,dtype:f})=>({dataId:c,dtype:f,shape:l}))}var nye={kernelName:fl,backendName:"wasm",kernelFunc:aye};function sye(e){let{inputs:{x:t},backend:r}=e,a=r.makeOutput(t.shape,t.dtype);return r.typedArrayFromHeap(a).fill(0),a}var iye={kernelName:ml,backendName:"wasm",kernelFunc:sye},oye=[Jfe,Qfe,tme,nme,hme,mme,Ame,vme,Sme,Fme,Mme,$me,zme,Dme,Bme,Ume,Gme,jme,Kme,Yme,e0e,a0e,n0e,i0e,o0e,l0e,u0e,h0e,c0e,m0e,A0e,v0e,I0e,C0e,R0e,M0e,P0e,sme,D0e,L0e,W0e,V0e,G0e,q0e,X0e,J0e,tge,nge,ige,uge,pge,hge,mge,Age,vge,kge,Tge,Nge,Rge,VS,Pge,Dge,Bge,Vge,Gge,jge,Hge,wme,Xge,Jge,t1e,r1e,a1e,i1e,u1e,h1e,c1e,Eme,g1e,A1e,v1e,I1e,T1e,N1e,R1e,F1e,M1e,P1e,D1e,B1e,V1e,j1e,H1e,q1e,Z1e,Q1e,rye,ume,nye,iye];for(let e of oye)Ga(e);var Ry=Y();Ry.registerFlag("WASM_HAS_SIMD_SUPPORT",async()=>WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,10,9,1,7,0,65,0,253,15,26,11])));Ry.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(Ry.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 xv=Eo(SE()),lye='var Module={};function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;this.alert=threadAlert;Module["instantiateWasm"]=function(info,receiveInstance){var instance=new WebAssembly.Instance(Module["wasmModule"],info);Module["wasmModule"]=null;receiveInstance(instance);return instance.exports};function moduleLoaded(){}this.onmessage=function(e){try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;if(typeof e.data.urlOrBlob==="string"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}WasmBackendModuleThreadedSimd(Module).then(function(instance){Module=instance;moduleLoaded()})}else if(e.data.cmd==="objectTransfer"){Module["PThread"].receiveObjectTransfer(e.data)}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;Module["__emscripten_thread_init"](e.data.threadInfoStruct,0,0);var max=e.data.stackBase;var top=e.data.stackBase+e.data.stackSize;Module["establishStackSpace"](top,max);Module["_emscripten_tls_init"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].setThreadStatus(Module["_pthread_self"](),1);try{var result=Module["invokeEntryPoint"](e.data.start_routine,e.data.arg);if(!Module["getNoExitRuntime"]())Module["PThread"].threadExit(result)}catch(ex){if(ex==="Canceled!"){Module["PThread"].threadCancel()}else if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["getNoExitRuntime"]()){}else{Module["PThread"].threadExit(ex.status)}}else{Module["PThread"].threadExit(-2);throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["PThread"].threadCancel()}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(Module["_pthread_self"]()){Module["_emscripten_current_thread_process_queued_calls"]()}}else{err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){err("worker.js onmessage() captured an uncaught exception: "+ex);if(ex&&ex.stack)err(ex.stack);throw ex}};if(typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string"){self={location:{href:__filename}};var onmessage=this.onmessage;var nodeWorkerThreads=require("worker_threads");global.Worker=nodeWorkerThreads.Worker;var parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",function(data){onmessage({data:data})});var nodeFS=require("fs");var nodeRead=function(filename){return nodeFS.readFileSync(filename,"utf8")};function globalEval(x){global.require=require;global.Module=Module;eval.call(null,x)}importScripts=function(f){globalEval(nodeRead(f))};postMessage=function(msg){parentPort.postMessage(msg)};if(typeof performance==="undefined"){performance={now:function(){return Date.now()}}}}',uye=Eo(TE()),uT=class extends Iu{constructor(e){super();this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.initWithThreadsCount(dT),Fy=this.wasm.tfjs.getThreadsCount(),this.dataIdMap=new Dp(this,kr())}write(e,t,r){let a={id:this.dataIdNextNumber++};return this.move(a,e,t,r,1),a}numDataIds(){return this.dataIdMap.numDataIds()}async time(e){let t=w.now();return e(),{kernelMs:w.now()-t}}move(e,t,r,a,n){let s=this.dataIdNextNumber++;if(a==="string"){let d=t;this.dataIdMap.set(e,{id:s,stringBytes:d,shape:r,dtype:a,memoryOffset:null,refCount:n});return}let i=w.sizeFromShape(r),o=i*w.bytesPerElement(a),l=this.wasm._malloc(o);this.dataIdMap.set(e,{id:s,memoryOffset:l,shape:r,dtype:a,refCount:n}),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,r){let{memoryOffset:a,dtype:n,shape:s,stringBytes:i}=this.dataIdMap.get(e);if(n==="string")return(t==null||t===0)&&(r==null||r>=i.length)?i:i.slice(t,r);t=t||0,r=r||w.sizeFromShape(s);let o=w.bytesPerElement(n),l=this.wasm.HEAPU8.slice(a+t*o,a+r*o);return hye(l.buffer,n)}disposeData(e,t=!1){if(this.dataIdMap.has(e)){let r=this.dataIdMap.get(e);if(r.refCount--,!t&&r.refCount>0)return!1;this.wasm._free(r.memoryOffset),this.wasm.tfjs.disposeData(r.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,r){let a;if(r==null)a=this.write(null,e,t);else{let n=this.dataIdNextNumber++;a={id:n},this.dataIdMap.set(a,{id:n,memoryOffset:r,shape:e,dtype:t,refCount:1});let s=w.sizeFromShape(e);this.wasm.tfjs.registerTensor(n,s,r)}return{dataId:a,shape:e,dtype:t}}typedArrayFromHeap({shape:e,dtype:t,dataId:r}){let a=this.wasm.HEAPU8.buffer,{memoryOffset:n}=this.dataIdMap.get(r),s=w.sizeFromShape(e);switch(t){case"float32":return new Float32Array(a,n,s);case"int32":return new Int32Array(a,n,s);case"bool":return new Uint8Array(a,n,s);default:throw new Error(`Unknown dtype ${t}`)}}};function dye(e){return(t,r)=>(w.fetch(e,{credentials:"same-origin"}).then(a=>{a.ok||t.env.a(`failed to load wasm binary file at '${e}'`),a.arrayBuffer().then(n=>{WebAssembly.instantiate(n,t).then(s=>{r(s.instance,s.module)})})}),{})}function bv(e,t,r){if(vf!=null)return vf;let a="tfjs-backend-wasm.wasm";return e&&t?a="tfjs-backend-wasm-threaded-simd.wasm":e&&(a="tfjs-backend-wasm-simd.wasm"),vp!=null&&vp[a]!=null?vp[a]:r+a}async function pye(){let[e,t]=await Promise.all([Y().getAsync("WASM_HAS_SIMD_SUPPORT"),Y().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise((r,a)=>{let n={};n.locateFile=(o,l)=>{if(o.endsWith(".worker.js")){let d=lye,u=new Blob([d],{type:"application/javascript"});return URL.createObjectURL(u)}return o.endsWith(".wasm")?bv(e,t,gp!=null?gp:l):l+o},Kx&&(n.instantiateWasm=dye(bv(e,t,gp!=null?gp:"")));let s=!1;n.onAbort=()=>{s||wp||(wp=!0,a({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&&vf==null?(n.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+xv.default.toString()],{type:"text/javascript"}),i=(0,xv.default)(n)):i=(0,uye.default)(n),i.then(o=>{s=!0,wp=!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,[])},r({wasm:o})})})}function hye(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 cye=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"],vf=null,gp=null,vp={},wp=!1,Kx=!1;function fye(e,t=!1){if(Jy("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."),wp)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");vf=e,Kx=t}function Xx(e,t=!1){if(wp)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")gp=e;else{vp=e;let r=cye.filter(a=>vp[a]==null);if(r.length>0)throw new Error(`There were no entries found for the following binaries: ${r.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.`)}Kx=t}var dT=-1,Fy=-1;function mye(e){dT=e}function gye(){if(Fy===-1)throw new Error("WASM backend not initialized.");return Fy}var yye="0.0.0",Aye=2;Al("wasm",async()=>{let{wasm:e}=await pye();return new uT(e)},Aye);var bs="3.13.0-20220214",Dh={tfjs:bs,"tfjs-core":bs,"tfjs-data":bs,"tfjs-layers":bs,"tfjs-converter":bs,"tfjs-backend-cpu":bs,"tfjs-backend-webgl":bs,"tfjs-backend-wasm":bs};var pT=`
|
|
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 hT=`
|
|
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];
|
|
}
|
|
`,cT=`
|
|
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;
|
|
}
|
|
`,fT=`
|
|
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);
|
|
}
|
|
`,mT=`
|
|
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;
|
|
}
|
|
`,gT=`
|
|
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 Zx=(e,t,r)=>{let a=new RegExp("\\b"+t+" \\w+ (\\w+)","ig");e.replace(a,(n,s)=>(r[s]=0,n))},yT=class{constructor(t,r,a){fe(this,"uniform",{});fe(this,"attribute",{});fe(this,"gl");fe(this,"id");fe(this,"compile",(t,r)=>{let a=this.gl.createShader(r);return a?(this.gl.shaderSource(a,t),this.gl.compileShader(a),this.gl.getShaderParameter(a,this.gl.COMPILE_STATUS)?a:(se(`filter: gl compile failed: ${this.gl.getShaderInfoLog(a)}`),null)):(se("filter: could not create shader"),null)});this.gl=t;let n=this.compile(r,this.gl.VERTEX_SHADER),s=this.compile(a,this.gl.FRAGMENT_SHADER);if(this.id=this.gl.createProgram(),!(!n||!s)){if(!this.id){se("filter: could not create webgl program");return}if(this.gl.attachShader(this.id,n),this.gl.attachShader(this.id,s),this.gl.linkProgram(this.id),!this.gl.getProgramParameter(this.id,this.gl.LINK_STATUS)){se(`filter: gl link failed: ${this.gl.getProgramInfoLog(this.id)}`);return}this.gl.useProgram(this.id),Zx(r,"attribute",this.attribute);for(let i in this.attribute)this.attribute[i]=this.gl.getAttribLocation(this.id,i);Zx(r,"uniform",this.uniform),Zx(a,"uniform",this.uniform);for(let i in this.uniform)this.uniform[i]=this.gl.getUniformLocation(this.id,i)}}};function AT(){let e=0,t=null,r=!1,a=-1,n=[null,null],s=[],i=null,o=null,l=Ur(100,100),d={},u={INTERMEDIATE:1},p=l.getContext("webgl");if(this.gl=p,!p){se("filter: cannot get webgl context");return}function h(A,x){if(!(A===l.width&&x===l.height)){if(l.width=A,l.height=x,!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=p.createBuffer(),p.bindBuffer(p.ARRAY_BUFFER,i),p.bufferData(p.ARRAY_BUFFER,b,p.STATIC_DRAW),p.pixelStorei(p.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0)}p.viewport(0,0,l.width,l.height),n=[null,null]}}function c(A,x){let b=p.createFramebuffer();p.bindFramebuffer(p.FRAMEBUFFER,b);let v=p.createRenderbuffer();p.bindRenderbuffer(p.RENDERBUFFER,v);let C=p.createTexture();return p.bindTexture(p.TEXTURE_2D,C),p.texImage2D(p.TEXTURE_2D,0,p.RGBA,A,x,0,p.RGBA,p.UNSIGNED_BYTE,null),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MAG_FILTER,p.LINEAR),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MIN_FILTER,p.LINEAR),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_S,p.CLAMP_TO_EDGE),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_T,p.CLAMP_TO_EDGE),p.framebufferTexture2D(p.FRAMEBUFFER,p.COLOR_ATTACHMENT0,p.TEXTURE_2D,C,0),p.bindTexture(p.TEXTURE_2D,null),p.bindFramebuffer(p.FRAMEBUFFER,null),{fbo:b,texture:C}}function f(A){return n[A]=n[A]||c(l.width,l.height),n[A]}function m(A=0){if(!o)return;let x=null,b=null,v=!1;e===0?x=t:x=f(a).texture||null,e++,r&&!(A&u.INTERMEDIATE)?(b=null,v=e%2===0):(a=(a+1)%2,b=f(a).fbo||null),p.bindTexture(p.TEXTURE_2D,x),p.bindFramebuffer(p.FRAMEBUFFER,b),p.uniform1f(o.uniform.flipY,v?-1:1),p.drawArrays(p.TRIANGLES,0,6)}function g(A){if(d[A])return o=d[A],p.useProgram((o?o.id:null)||null),o;if(o=new yT(p,pT,A),!o)return se("filter: could not get webgl program"),null;let x=Float32Array.BYTES_PER_ELEMENT,b=4*x;return p.enableVertexAttribArray(o.attribute.pos),p.vertexAttribPointer(o.attribute.pos,2,p.FLOAT,!1,b,0*x),p.enableVertexAttribArray(o.attribute.uv),p.vertexAttribPointer(o.attribute.uv,2,p.FLOAT,!1,b,2*x),d[A]=o,o}let y={colorMatrix:A=>{let x=new Float32Array(A);x[4]/=255,x[9]/=255,x[14]/=255,x[19]/=255;let b=x[18]===1&&x[3]===0&&x[8]===0&&x[13]===0&&x[15]===0&&x[16]===0&&x[17]===0&&x[19]===0?cT:hT,v=g(b);!v||(p.uniform1fv(v.uniform.m,x),m())},brightness:A=>{let x=(A||0)+1;y.colorMatrix([x,0,0,0,0,0,x,0,0,0,0,0,x,0,0,0,0,0,1,0])},saturation:A=>{let x=(A||0)*2/3+1,b=(x-1)*-.5;y.colorMatrix([x,b,b,0,0,b,x,b,0,0,b,b,x,0,0,0,0,0,1,0])},desaturate:()=>{y.saturation(-1)},contrast:A=>{let x=(A||0)+1,b=-128*(x-1);y.colorMatrix([x,0,0,0,b,0,x,0,0,b,0,0,x,0,b,0,0,0,1,0])},negative:()=>{y.contrast(-2)},hue:A=>{A=(A||0)/180*Math.PI;let x=Math.cos(A),b=Math.sin(A),v=.213,C=.715,T=.072;y.colorMatrix([v+x*(1-v)+b*-v,C+x*-C+b*-C,T+x*-T+b*(1-T),0,0,v+x*-v+b*.143,C+x*(1-C)+b*.14,T+x*-T+b*-.283,0,0,v+x*-v+b*-(1-v),C+x*-C+b*C,T+x*(1-T)+b*T,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:A=>{let x=new Float32Array(A),b=1/l.width,v=1/l.height,C=g(gT);!C||(p.uniform1fv(C.uniform.m,x),p.uniform2f(C.uniform.px,b,v),m())},detectEdges:()=>{y.convolution.call(this,[0,1,0,1,-4,1,0,1,0])},sobelX:()=>{y.convolution.call(this,[-1,0,1,-2,0,2,-1,0,1])},sobelY:()=>{y.convolution.call(this,[-1,-2,-1,0,0,0,1,2,1])},sharpen:A=>{let x=A||1;y.convolution.call(this,[0,-1*x,0,-1*x,1+4*x,-1*x,0,-1*x,0])},emboss:A=>{let x=A||1;y.convolution.call(this,[-2*x,-1*x,0,-1*x,1,1*x,0,1*x,2*x])},blur:A=>{let x=A/7/l.width,b=A/7/l.height,v=g(mT);!v||(p.uniform2f(v.uniform.px,0,b),m(u.INTERMEDIATE),p.uniform2f(v.uniform.px,x,0),m())},pixelate:A=>{let x=A/l.width,b=A/l.height,v=g(fT);!v||(p.uniform2f(v.uniform.size,x,b),m())}};this.add=function(A){let x=Array.prototype.slice.call(arguments,1),b=y[A];s.push({func:b,args:x})},this.reset=function(){s=[]},this.get=function(){return s},this.apply=function(A){h(A.width,A.height),e=0,t||(t=p.createTexture()),p.bindTexture(p.TEXTURE_2D,t),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_S,p.CLAMP_TO_EDGE),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_T,p.CLAMP_TO_EDGE),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MIN_FILTER,p.NEAREST),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MAG_FILTER,p.NEAREST),p.texImage2D(p.TEXTURE_2D,0,p.RGBA,p.RGBA,p.UNSIGNED_BYTE,A);for(let x=0;x<s.length;x++){r=x===s.length-1;let b=s[x];b.func.apply(this,b.args||[])}return l},this.draw=function(A){return this.add("brightness",0),this.apply(A)}}async function i0(e){let t=e.shape.length===4?Ye(e):e,r=Kt(t,3,2),a=[zs(r[0]),zs(r[1]),zs(r[2])],n=[hr(r[0]),hr(r[1]),hr(r[2])],s=await Promise.all(n.map(c=>c.data())),i=.99*Math.max(s[0][0],s[1][0],s[2][0]),o=[he(r[0],a[0]),he(r[1],a[1]),he(r[2],a[2])],l=[he(n[0],a[0]),he(n[1],a[1]),he(n[2],a[2])],d=[pe(i,l[0]),pe(i,l[1]),pe(i,l[2])],u=[L(o[0],d[0]),L(o[1],d[1]),L(o[2],d[2])],p=nr([u[0],u[1],u[2]],2),h=U(p,[1,t.shape[0],t.shape[1],3]);return re([...r,...a,...n,...o,...l,...d,...u,p,t]),h}var o0=2048,lt=null,ir=null,wd=null,Ct,rs={inputSum:0,cacheDiff:1,sumMethod:0,inputTensor:void 0};function Ur(e,t){let r;if(ce.browser)if(ce.worker){if(typeof OffscreenCanvas=="undefined")throw new Error("canvas error: attempted to run in web worker but OffscreenCanvas is not supported");r=new OffscreenCanvas(e,t)}else{if(typeof document=="undefined")throw new Error("canvas error: attempted to run in browser but DOM is not defined");r=document.createElement("canvas"),r.width=e,r.height=t}else typeof ce.Canvas!="undefined"?r=new ce.Canvas(e,t):typeof globalThis.Canvas!="undefined"&&(r=new globalThis.Canvas(e,t));return r}function Yx(e,t){let r=t||Ur(e.width,e.height);return r.getContext("2d").drawImage(e,0,0),r}async function kd(e,t,r=!0){if(!e)return t.debug&&se("input error: input is missing"),{tensor:null,canvas:null};if(!(e instanceof et)&&!(typeof Image!="undefined"&&e instanceof Image)&&!(typeof ce.Canvas!="undefined"&&e instanceof ce.Canvas)&&!(typeof globalThis.Canvas!="undefined"&&e instanceof globalThis.Canvas)&&!(typeof ImageData!="undefined"&&e instanceof ImageData)&&!(typeof ImageBitmap!="undefined"&&e instanceof ImageBitmap)&&!(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement)&&!(typeof HTMLMediaElement!="undefined"&&e instanceof HTMLMediaElement)&&!(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)&&!(typeof HTMLCanvasElement!="undefined"&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas!="undefined"&&e instanceof OffscreenCanvas))throw new Error("input error: type is not recognized");if(e instanceof et){let a=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)a=Ht(e,0);else if(e.shape[2]===4){let n=vl(e,[0,0,0],[-1,-1,3]);a=Ht(n,0),re(n)}}else e.shape.length===4&&(e.shape[3]===3?a=Pr(e):e.shape[3]===4&&(a=wo(e,[0,0,0,0],[-1,-1,-1,3])));if(a==null||a.shape.length!==4||a.shape[0]!==1||a.shape[3]!==3)throw new Error(`input error: attempted to use tensor with unrecognized shape: ${e.shape}`);if(a.dtype==="int32"){let n=me(a,"float32");re(a),a=n}return{tensor:a,canvas:t.filter.return?ir:null}}else{if(typeof e.readyState!="undefined"&&e.readyState<=2)return t.debug&&se("input stream is not ready"),{tensor:null,canvas:lt};let a=e.naturalWidth||e.videoWidth||e.width||e.shape&&e.shape[1]>0,n=e.naturalHeight||e.videoHeight||e.height||e.shape&&e.shape[2]>0;if(!a||!n)return t.debug&&se("cannot determine input dimensions"),{tensor:null,canvas:lt};let s=a,i=n;if(s>o0&&(s=o0,i=Math.trunc(s*n/a)),i>o0&&(i=o0,s=Math.trunc(i*a/n)),(t.filter.width||0)>0?s=t.filter.width:(t.filter.height||0)>0&&(s=a*((t.filter.height||0)/n)),(t.filter.height||0)>0?i=t.filter.height:(t.filter.width||0)>0&&(i=n*((t.filter.width||0)/a)),!s||!i)throw new Error("input error: cannot determine dimension");(!lt||(lt==null?void 0:lt.width)!==s||(lt==null?void 0:lt.height)!==i)&&(lt=Ur(s,i));let o=lt.getContext("2d");if(typeof ImageData!="undefined"&&e instanceof ImageData?o.putImageData(e,0,0):t.filter.flip&&typeof o.translate!="undefined"?(o.translate(a,0),o.scale(-1,1),o.drawImage(e,0,0,a,n,0,0,lt==null?void 0:lt.width,lt==null?void 0:lt.height),o.setTransform(1,0,0,1,0,0)):o.drawImage(e,0,0,a,n,0,0,lt==null?void 0:lt.width,lt==null?void 0:lt.height),(!ir||lt.width!==ir.width||(lt==null?void 0:lt.height)!==(ir==null?void 0:ir.height))&&(ir=Ur(lt.width,lt.height)),t.filter.enabled&&ce.webgl.supported){if(Ct||(Ct=ce.browser?new AT:null),ce.filter=!!Ct,!Ct||!Ct.add)return t.debug&&se("input process error: cannot initialize filters"),{tensor:null,canvas:lt};Ct.reset(),t.filter.brightness!==0&&Ct.add("brightness",t.filter.brightness),t.filter.contrast!==0&&Ct.add("contrast",t.filter.contrast),t.filter.sharpness!==0&&Ct.add("sharpen",t.filter.sharpness),t.filter.blur!==0&&Ct.add("blur",t.filter.blur),t.filter.saturation!==0&&Ct.add("saturation",t.filter.saturation),t.filter.hue!==0&&Ct.add("hue",t.filter.hue),t.filter.negative&&Ct.add("negative"),t.filter.sepia&&Ct.add("sepia"),t.filter.vintage&&Ct.add("brownie"),t.filter.sepia&&Ct.add("sepia"),t.filter.kodachrome&&Ct.add("kodachrome"),t.filter.technicolor&&Ct.add("technicolor"),t.filter.polaroid&&Ct.add("polaroid"),t.filter.pixelate!==0&&Ct.add("pixelate",t.filter.pixelate),Ct.get()>0?ir=Ct.apply(lt):ir=Ct.draw(lt)}else Yx(lt,ir),Ct&&(Ct=null),ce.filter=!!Ct;if(!r)return{tensor:null,canvas:ir};if(!ir)throw new Error("canvas error: cannot create output");let l,d=3;if(typeof ImageData!="undefined"&&e instanceof ImageData||e.data&&e.width&&e.height)if(ce.browser&&$a)l=$a?$a.fromPixels(e):null;else{d=e.data.length/e.height/e.width;let h=new Uint8Array(e.data.buffer);l=pt(h,[e.height,e.width,d],"int32")}else if((!wd||ir.width!==wd.width||ir.height!==wd.height)&&(wd=Ur(ir.width,ir.height)),$a&&ce.browser)t.backend==="webgl"||t.backend==="humangl"||t.backend==="webgpu"?l=$a.fromPixels(ir):(wd=Yx(ir),l=$a.fromPixels(wd));else{let f=Yx(ir).getContext("2d").getImageData(0,0,s,i);d=f.data.length/s/i;let m=new Uint8Array(f.data.buffer);l=pt(m,[s,i,d])}if(d===4){let h=vl(l,[0,0,0],[-1,-1,3]);re(l),l=h}if(!l)throw new Error("input error: cannot create tensor");let u=me(l,"float32"),p=t.filter.equalization?await i0(u):Ht(u,0);return re([l,u]),{tensor:p,canvas:t.filter.return?ir:null}}}async function xT(e,t){let r=!1;if(e.cacheSensitivity===0||!t.shape||t.shape.length!==4||t.shape[1]>2048||t.shape[2]>2048)return r;if(!rs.inputTensor)rs.inputTensor=Pr(t);else if(rs.inputTensor.shape[1]!==t.shape[1]||rs.inputTensor.shape[2]!==t.shape[2])re(rs.inputTensor),rs.inputTensor=Pr(t);else{let a={};a.diff=he(t,rs.inputTensor),a.squared=L(a.diff,a.diff),a.sum=ke(a.squared);let s=(await a.sum.data())[0]/(t.shape[1]||1)/(t.shape[2]||1)/255/3;re([rs.inputTensor,a.diff,a.squared,a.sum]),rs.inputTensor=Pr(t),r=s<=(e.cacheSensitivity||0)}return r}async function bT(e,t,r){let a={};if(!t||!r||t.shape.length!==4||t.shape.length!==r.shape.length)return e.debug||se("invalid input tensor or tensor shapes do not match:",t.shape,r.shape),0;if(t.shape[0]!==1||r.shape[0]!==1||t.shape[3]!==3||r.shape[3]!==3)return e.debug||se("input tensors must be of shape [1, height, width, 3]:",t.shape,r.shape),0;a.input1=Pr(t),a.input2=t.shape[1]!==r.shape[1]||t.shape[2]!==r.shape[2]?Ie.resizeBilinear(r,[t.shape[1],t.shape[2]]):Pr(r),a.diff=he(a.input1,a.input2),a.squared=L(a.diff,a.diff),a.sum=ke(a.squared);let s=(await a.sum.data())[0]/(t.shape[1]||1)/(t.shape[2]||1)/255/3;return re([a.input1,a.input2,a.diff,a.squared,a.sum]),s}var vT=class{constructor(){fe(this,"browser");fe(this,"node");fe(this,"worker");fe(this,"platform","");fe(this,"agent","");fe(this,"backends",[]);fe(this,"initial");fe(this,"filter");fe(this,"tfjs");fe(this,"offscreen");fe(this,"perfadd",!1);fe(this,"wasm",{supported:void 0,backend:void 0,simd:void 0,multithread:void 0});fe(this,"webgl",{supported:void 0,backend:void 0,version:void 0,renderer:void 0});fe(this,"webgpu",{supported:void 0,backend:void 0,adapter:void 0});fe(this,"cpu",{model:void 0,flags:[]});fe(this,"kernels",[]);fe(this,"Canvas");fe(this,"Image");fe(this,"ImageData");if(this.browser=typeof navigator!="undefined",this.node=typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined",this.tfjs={version:Dh["tfjs-core"]},this.offscreen=typeof OffscreenCanvas!="undefined",this.initial=!0,this.worker=this.browser&&this.offscreen?typeof WorkerGlobalScope!="undefined":void 0,typeof navigator!="undefined"){let t=navigator.userAgent.match(/\(([^()]+)\)/g);if(t&&t[0]){let r=t[0].match(/\(([^()]+)\)/g);this.platform=r&&r[0]?r[0].replace(/\(|\)/g,""):"",this.agent=navigator.userAgent.replace(t[0],""),this.platform[1]&&(this.agent=this.agent.replace(t[1],"")),this.agent=this.agent.replace(/ /g," ")}}else typeof process!="undefined"&&(this.platform=`${process.platform} ${process.arch}`,this.agent=`NodeJS ${process.version}`)}async updateBackend(){this.backends=Object.keys(kr().registryFactory),this.wasm.supported=typeof WebAssembly!="undefined",this.wasm.backend=this.backends.includes("wasm"),this.wasm.supported&&this.wasm.backend&&ca()==="wasm"&&(this.wasm.simd=await Y().getAsync("WASM_HAS_SIMD_SUPPORT"),this.wasm.multithread=await Y().getAsync("WASM_HAS_MULTITHREAD_SUPPORT"));let t=Ur(100,100),r=t?t.getContext("webgl2"):void 0;if(this.webgl.supported=typeof r!="undefined",this.webgl.backend=this.backends.includes("webgl"),this.webgl.supported&&this.webgl.backend&&(ca()==="webgl"||ca()==="humangl")){let a=cn().gpgpu!=="undefined"?await cn().getGPGPUContext().gl:null;a&&(this.webgl.version=a.getParameter(a.VERSION),this.webgl.renderer=a.getParameter(a.RENDERER))}this.webgpu.supported=this.browser&&typeof navigator.gpu!="undefined",this.webgpu.backend=this.backends.includes("webgpu");try{this.webgpu.supported&&(this.webgpu.adapter=(await navigator.gpu.requestAdapter()).name)}catch(a){this.webgpu.supported=!1}try{this.kernels=Tn(ca()).map(a=>a.kernelName.toLowerCase())}catch(a){}}async updateCPU(){let t={model:"",flags:[]};this.node&&this.platform.startsWith("linux"),this.cpu?this.cpu=t:Object.defineProperty(this,"cpu",{value:t})}},ce=new vT;var as={cacheModels:!1,verbose:!0,debug:!1,modelBasePath:""};async function wye(e,t){return as.debug&&se("load model fetch:",e,t),fetch(e,t)}function wT(e){as.cacheModels=e.cacheModels,as.verbose=e.debug,as.modelBasePath=e.modelBasePath}async function Ue(e){let t=B5(as.modelBasePath,e||""),r=t.split("/"),a="indexeddb://"+r[r.length-1].replace(".json",""),n=await Ir.listModels(),s=as.cacheModels&&Object.keys(n).includes(a),i=typeof fetch=="undefined"?{}:{fetchFunc:(l,d)=>wye(l,d)},o=new qm(s?a:t,i);try{o.findIOHandler(),as.debug&&se("model load handler:",o.handler);let l=await o.handler.load();o.loadSync(l),as.verbose&&se("load model:",o.modelUrl)}catch(l){se("error loading model:",t,l)}if(as.cacheModels&&!s)try{let l=await o.save(a);se("model saved:",a,l)}catch(l){se("error saving model:",t,l)}return o}var Jx="2.6.3";var Xa,Qx=[],Sye=["white","black","asian","indian","other"],Tye=[15,23,28,35.5,45.5,55.5,65],kT=0,IT=0,eb=Number.MAX_SAFE_INTEGER;async function ST(e){return ce.initial&&(Xa=null),Xa?e.debug&&se("cached model:",Xa.modelUrl):Xa=await Ue(e.face.gear),Xa}async function tb(e,t,r,a){var i,o;if(!Xa)return{age:0,gender:"unknown",genderScore:0,race:[]};let n=eb<(((i=t.face.gear)==null?void 0:i.skipFrames)||0),s=(((o=t.face.gear)==null?void 0:o.skipTime)||0)>oe()-IT;return t.skipAllowed&&s&&n&&kT===a&&Qx[r]?(eb++,Qx[r]):(eb=0,new Promise(async l=>{var y,A;if(!(Xa==null?void 0:Xa.inputs[0].shape))return;let d={},u=[[0,.1,.9,.9]];d.resize=Ie.cropAndResize(e,u,[0],[Xa.inputs[0].shape[2],Xa.inputs[0].shape[1]]);let p={age:0,gender:"unknown",genderScore:0,race:[]};((y=t.face.gear)==null?void 0:y.enabled)&&([d.age,d.gender,d.race]=Xa.execute(d.resize,["age_output","gender_output","race_output"]));let h=await d.gender.data();p.gender=h[0]>h[1]?"male":"female",p.genderScore=Math.round(100*(h[0]>h[1]?h[0]:h[1]))/100;let c=await d.race.data();for(let x=0;x<c.length;x++)c[x]>(((A=t.face.gear)==null?void 0:A.minConfidence)||.2)&&p.race.push({score:Math.round(100*c[x])/100,race:Sye[x]});p.race.sort((x,b)=>b.score-x.score);let m=Array.from(await d.age.data()).map((x,b)=>[Tye[b],x]).sort((x,b)=>b[1]-x[1]),g=m[0][0];for(let x=1;x<m.length;x++)g+=m[x][1]*(m[x][0]-g);p.age=Math.round(10*g)/10,Object.keys(d).forEach(x=>re(d[x])),Qx[r]=p,kT=a,IT=oe(),l(p)}))}var Xe={tf255:255,tf1:1,tf2:2,tf05:.5,tf127:127.5,rgb:[.2989,.587,.114]};function CT(){Xe.tf255=Se(255,"float32"),Xe.tf1=Se(1,"float32"),Xe.tf2=Se(2,"float32"),Xe.tf05=Se(.5,"float32"),Xe.tf127=Se(127.5,"float32"),Xe.rgb=St([.2989,.587,.114],"float32")}var ma,l0=[],NT=0,ET=0,rb=Number.MAX_SAFE_INTEGER;async function RT(e){return ce.initial&&(ma=null),ma?e.debug&&se("cached model:",ma.modelUrl):ma=await Ue(e.face.ssrnet.modelPathAge),ma}async function ab(e,t,r,a){var i,o,l,d;if(!ma)return{age:0};let n=rb<(((i=t.face.ssrnet)==null?void 0:i.skipFrames)||0),s=(((o=t.face.ssrnet)==null?void 0:o.skipTime)||0)>oe()-ET;return t.skipAllowed&&n&&s&&NT===a&&((l=l0[r])==null?void 0:l.age)&&((d=l0[r])==null?void 0:d.age)>0?(rb++,l0[r]):(rb=0,new Promise(async u=>{if(!(ma==null?void 0:ma.inputs)||!ma.inputs[0]||!ma.inputs[0].shape)return;let p={};p.resize=Ie.resizeBilinear(e,[ma.inputs[0].shape[2],ma.inputs[0].shape[1]],!1),p.enhance=L(p.resize,Xe.tf255);let h={age:0};if(t.face.ssrnet.enabled&&(p.age=ma.execute(p.enhance)),p.age){let c=await p.age.data();h.age=Math.trunc(10*c[0])/10}Object.keys(p).forEach(c=>re(p[c])),l0[r]=h,NT=a,ET=oe(),u(h)}))}var Za,u0=[],MT=0,$T=0,nb=Number.MAX_SAFE_INTEGER,sb=[.2989,.587,.114];async function PT(e){return ce.initial&&(Za=null),Za?e.debug&&se("cached model:",Za.modelUrl):Za=await Ue(e.face.ssrnet.modelPathGender),Za}async function ib(e,t,r,a){var i,o,l,d;if(!Za)return{gender:"unknown",genderScore:0};let n=nb<(((i=t.face.ssrnet)==null?void 0:i.skipFrames)||0),s=(((o=t.face.ssrnet)==null?void 0:o.skipTime)||0)>oe()-$T;return t.skipAllowed&&n&&s&&MT===a&&((l=u0[r])==null?void 0:l.gender)&&((d=u0[r])==null?void 0:d.genderScore)>0?(nb++,u0[r]):(nb=0,new Promise(async u=>{if(!(Za==null?void 0:Za.inputs[0].shape))return;let p={};p.resize=Ie.resizeBilinear(e,[Za.inputs[0].shape[2],Za.inputs[0].shape[1]],!1),p.enhance=q(()=>{let[f,m,g]=Kt(p.resize,3,3),y=L(f,sb[0]),A=L(m,sb[1]),x=L(g,sb[2]),b=Jf([y,A,x]);return L(he(b,Xe.tf05),2)});let h={gender:"unknown",genderScore:0};t.face.ssrnet.enabled&&(p.gender=Za.execute(p.enhance));let c=await p.gender.data();h.gender=c[0]>c[1]?"female":"male",h.genderScore=c[0]>c[1]?Math.trunc(100*c[0])/100:Math.trunc(100*c[1])/100,Object.keys(p).forEach(f=>re(p[f])),u0[r]=h,MT=a,$T=oe(),u(h)}))}var Cr,d0=[],ob=Number.MAX_SAFE_INTEGER,zT=0,DT=0;async function _T(e){var t;return ce.initial&&(Cr=null),Cr?e.debug&&se("cached model:",Cr.modelUrl):Cr=await Ue((t=e.face.antispoof)==null?void 0:t.modelPath),Cr}async function lb(e,t,r,a){var i,o;if(!Cr)return 0;let n=(((i=t.face.antispoof)==null?void 0:i.skipTime)||0)>oe()-DT,s=ob<(((o=t.face.antispoof)==null?void 0:o.skipFrames)||0);return t.skipAllowed&&n&&s&&zT===a&&d0[r]?(ob++,d0[r]):(ob=0,new Promise(async l=>{let d=Ie.resizeBilinear(e,[(Cr==null?void 0:Cr.inputs[0].shape)?Cr.inputs[0].shape[2]:0,(Cr==null?void 0:Cr.inputs[0].shape)?Cr.inputs[0].shape[1]:0],!1),u=Cr==null?void 0:Cr.execute(d),p=(await u.data())[0];d0[r]=Math.round(100*p)/100,zT=a,DT=oe(),re([d,u]),l(d0[r])}))}var Ya={silhouette:[10,338,297,332,284,251,389,356,454,323,361,288,397,365,379,378,400,377,152,148,176,149,150,136,172,58,132,93,234,127,162,21,54,103,67,109],lipsUpperOuter:[61,185,40,39,37,0,267,269,270,409,291],lipsLowerOuter:[146,91,181,84,17,314,405,321,375,291],lipsUpperInner:[78,191,80,81,82,13,312,311,310,415,308],lipsLowerInner:[78,95,88,178,87,14,317,402,318,324,308],rightEyeUpper0:[246,161,160,159,158,157,173],rightEyeLower0:[33,7,163,144,145,153,154,155,133],rightEyeUpper1:[247,30,29,27,28,56,190],rightEyeLower1:[130,25,110,24,23,22,26,112,243],rightEyeUpper2:[113,225,224,223,222,221,189],rightEyeLower2:[226,31,228,229,230,231,232,233,244],rightEyeLower3:[143,111,117,118,119,120,121,128,245],rightEyebrowUpper:[156,70,63,105,66,107,55,193],rightEyebrowLower:[35,124,46,53,52,65],rightEyeIris:[473,474,475,476,477],leftEyeUpper0:[466,388,387,386,385,384,398],leftEyeLower0:[263,249,390,373,374,380,381,382,362],leftEyeUpper1:[467,260,259,257,258,286,414],leftEyeLower1:[359,255,339,254,253,252,256,341,463],leftEyeUpper2:[342,445,444,443,442,441,413],leftEyeLower2:[446,261,448,449,450,451,452,453,464],leftEyeLower3:[372,340,346,347,348,349,350,357,465],leftEyebrowUpper:[383,300,293,334,296,336,285,417],leftEyebrowLower:[265,353,276,283,282,295],leftEyeIris:[468,469,470,471,472],midwayBetweenEyes:[168],noseTip:[1],noseBottom:[2],noseRightCorner:[98],noseLeftCorner:[327],rightCheek:[205],leftCheek:[425]},ub={count:468,mouth:13,symmetryLine:[13,Ya.midwayBetweenEyes[0]]},Lh={leftEye:0,rightEye:1,nose:2,mouth:3,leftEar:4,rightEar:5,symmetryLine:[3,2]},db=[{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]}],Bh=[[.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]],El=[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 Nye=[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],Eye=[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],Rye=[33,133,362,263,1,78,308],wAe=Nye.map(e=>Bh[e]),kAe=Eye.map(e=>Bh[e]),IAe=Rye.map(e=>Bh[e]);var Id=e=>[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])],p0=e=>[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2,1],fb=(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],mb=(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],VT=(e,t)=>{let r=[e.startPoint[0]*t[0],e.startPoint[1]*t[1]],a=[e.endPoint[0]*t[0],e.endPoint[1]*t[1]];return{startPoint:r,endPoint:a,landmarks:e.landmarks,confidence:e.confidence}},hb=(e,t,r)=>{let a=t.shape[1],n=t.shape[2],s=[e.startPoint[1]/a,e.startPoint[0]/n,e.endPoint[1]/a,e.endPoint[0]/n],i=Ie.cropAndResize(t,[s],[0],r),o=pe(i,Xe.tf255);return re(i),o},h0=(e,t)=>{let r=p0(e),a=Id(e),n=[t*a[0]/2,t*a[1]/2];return{startPoint:[r[0]-n[0],r[1]-n[1]],endPoint:[r[0]+n[0],r[1]+n[1]],landmarks:e.landmarks,confidence:e.confidence}},c0=e=>{let t=p0(e),r=Id(e),a=Math.max(...r)/2;return{startPoint:[Math.round(t[0]-a),Math.round(t[1]-a)],endPoint:[Math.round(t[0]+a),Math.round(t[1]+a)],landmarks:e.landmarks,confidence:e.confidence}},UT=e=>{let t=e.map(a=>a[0]),r=e.map(a=>a[1]);return{startPoint:[Math.min(...t),Math.min(...r)],endPoint:[Math.max(...t),Math.max(...r)],landmarks:e}},cb=[[1,0,0],[0,1,0],[0,0,1]],Fye=e=>e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI)),Mye=(e,t)=>Fye(Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]));var BT=(e,t)=>[[1,0,e],[0,1,t],[0,0,1]],Rl=(e,t)=>{let r=0;for(let a=0;a<e.length;a++)r+=e[a]*t[a];return r},$ye=(e,t)=>{let r=[];for(let a=0;a<e.length;a++)r.push(e[a][t]);return r},WT=(e,t)=>{let r=[],a=e.length;for(let n=0;n<a;n++){r.push([]);for(let s=0;s<a;s++)r[n].push(Rl(e[n],$ye(t,s)))}return r},GT=(e,t)=>{let r=Math.cos(e),a=Math.sin(e),n=[[r,-a,0],[a,r,0],[0,0,1]],s=BT(t[0],t[1]),i=WT(s,n),o=BT(-t[0],-t[1]);return WT(i,o)},Pye=e=>{let t=[[e[0][0],e[1][0]],[e[0][1],e[1][1]]],r=[e[0][2],e[1][2]],a=[-Rl(t[0],r),-Rl(t[1],r)];return[t[0].concat(a[0]),t[1].concat(a[1]),[0,0,1]]},Oye=(e,t)=>[Rl(e,t[0]),Rl(e,t[1])];function jT(e){let t={strides:[e/16,e/8],anchors:[2,6]},r=[];for(let a=0;a<t.strides.length;a++){let n=t.strides[a],s=Math.floor((e+n-1)/n),i=Math.floor((e+n-1)/n),o=t.anchors[a];for(let l=0;l<s;l++){let d=n*(l+.5);for(let u=0;u<i;u++){let p=n*(u+.5);for(let h=0;h<o;h++)r.push([p,d])}}}return r}function HT(e,t,r,a,n){let s=Id(t),i=e.map(c=>[s[0]/n*(c[0]-n/2),s[1]/n*(c[1]-n/2),c[2]||0]),o=r&&r!==0&&Math.abs(r)>.2,l=o?GT(r,[0,0]):cb,d=o?i.map(c=>[...Oye(c,l),c[2]]):i,u=o?Pye(a):cb,p=p0(t),h=[Rl(p,u[0]),Rl(p,u[1])];return d.map(c=>[Math.trunc(c[0]+h[0]),Math.trunc(c[1]+h[1]),Math.trunc(c[2]||0)])}function qT(e,t,r,a){let n=t.landmarks.length>=ub.count?ub.symmetryLine:Lh.symmetryLine,s=0,i=cb,o;if(e&&ce.kernels.includes("rotatewithoffset"))if(s=Mye(t.landmarks[n[0]],t.landmarks[n[1]]),s&&s!==0&&Math.abs(s)>.2){let d=p0(t),u=[d[0]/r.shape[2],d[1]/r.shape[1]],p=Ie.rotateWithOffset(r,s,0,u);i=GT(-s,d),o=hb(t,p,[a,a]),re(p)}else o=hb(t,r,[a,a]);else o=hb(t,r,[a,a]);return[s,i,o]}var zye=e=>{let t=e.map(a=>a[0]),r=e.map(a=>a[1]);return[Math.min(...t)+(Math.max(...t)-Math.min(...t))/2,Math.min(...r)+(Math.max(...r)-Math.min(...r))/2]},KT=(e,t)=>{let r=zye(e),a=Id(t);return{startPoint:[r[0]-a[0]/2,r[1]-a[1]/2],endPoint:[r[0]+a[0]/2,r[1]+a[1]/2]}};var XT=6,Dye=1.2,$n,ZT=null,Ui=0,Wh=null,f0=()=>Ui;async function YT(e){var t;return ce.initial&&($n=null),$n?e.debug&&se("cached model:",$n.modelUrl):$n=await Ue((t=e.face.detector)==null?void 0:t.modelPath),Ui=$n.inputs[0].shape?$n.inputs[0].shape[2]:0,Wh=Se(Ui,"int32"),ZT=an(jT(Ui)),$n}function _ye(e){let t={};t.boxStarts=Oe(e,[0,1],[-1,2]),t.centers=ue(t.boxStarts,ZT),t.boxSizes=Oe(e,[0,3],[-1,2]),t.boxSizesNormalized=pe(t.boxSizes,Wh),t.centersNormalized=pe(t.centers,Wh),t.halfBoxSize=pe(t.boxSizesNormalized,Xe.tf2),t.starts=he(t.centersNormalized,t.halfBoxSize),t.ends=ue(t.centersNormalized,t.halfBoxSize),t.startNormalized=L(t.starts,Wh),t.endNormalized=L(t.ends,Wh);let r=ed([t.startNormalized,t.endNormalized],1);return Object.keys(t).forEach(a=>re(t[a])),r}async function JT(e,t){var o,l,d,u;if(!e||e.isDisposedInternal||e.shape.length!==4||e.shape[1]<1||e.shape[2]<1)return[];let r={};r.resized=Ie.resizeBilinear(e,[Ui,Ui]),r.div=pe(r.resized,Xe.tf127),r.normalized=he(r.div,Xe.tf05);let a=$n==null?void 0:$n.execute(r.normalized);if(Array.isArray(a)){let p=a.sort((h,c)=>h.size-c.size);r.concat384=kt([p[0],p[2]],2),r.concat512=kt([p[1],p[3]],2),r.concat=kt([r.concat512,r.concat384],1),r.batch=Ye(r.concat,0)}else r.batch=Ye(a);re(a),r.boxes=_ye(r.batch),r.logits=Oe(r.batch,[0,0],[-1,1]),r.sigmoid=Sr(r.logits),r.scores=Ye(r.sigmoid),r.nms=await Ie.nonMaxSuppressionAsync(r.boxes,r.scores,((o=t.face.detector)==null?void 0:o.maxDetected)||0,((l=t.face.detector)==null?void 0:l.iouThreshold)||0,((d=t.face.detector)==null?void 0:d.minConfidence)||0);let n=await r.nms.array(),s=[],i=await r.scores.data();for(let p=0;p<n.length;p++){let h=i[n[p]];if(h>(((u=t.face.detector)==null?void 0:u.minConfidence)||0)){let c={};c.bbox=Oe(r.boxes,[n[p],0],[1,-1]),c.slice=Oe(r.batch,[n[p],XT-1],[1,-1]),c.squeeze=Ye(c.slice),c.landmarks=U(c.squeeze,[XT,-1]);let f=await c.bbox.data(),m={startPoint:[f[0],f[1]],endPoint:[f[2],f[3]],landmarks:await c.landmarks.array(),confidence:h},g=VT(m,[(e.shape[2]||0)/Ui,(e.shape[1]||0)/Ui]),y=h0(g,t.face.scale||Dye),A=c0(y);s.push(A),Object.keys(c).forEach(x=>re(c[x]))}}return Object.keys(r).forEach(p=>re(r[p])),s}var m0={};Qd(m0,{connected:()=>Ab,kpt:()=>yb});var yb=["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"],Ab={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 eC=224,Lye,Bye=5,g0=[8,16,32,32,32];async function tC(){let e=[],t=0;for(;t<Bye;){let r=0,a=t;for(;a<g0.length&&g0[a]===g0[t];)r+=2,a++;let n=g0[t],s=Math.ceil(eC/n),i=Math.ceil(eC/n);for(let o=0;o<s;++o)for(let l=0;l<i;++l)for(let d=0;d<r;++d)e.push({x:(l+.5)/i,y:(o+.5)/s});t=a}Lye={x:St(e.map(r=>r.x)),y:St(e.map(r=>r.y))}}function ns(e,t=[1,1]){let r=[e.map(o=>o[0]),e.map(o=>o[1])],a=[Math.min(...r[0]),Math.min(...r[1])],n=[Math.max(...r[0]),Math.max(...r[1])],s=[a[0],a[1],n[0]-a[0],n[1]-a[1]],i=[s[0]/t[0],s[1]/t[1],s[2]/t[0],s[3]/t[1]];return{box:s,boxRaw:i}}function rC(e,t=[1,1]){let r=[e.map(d=>d[0]),e.map(d=>d[1])],a=[Math.min(...r[0]),Math.min(...r[1])],n=[Math.max(...r[0]),Math.max(...r[1])],s=[(a[0]+n[0])/2,(a[1]+n[1])/2],i=Math.max(s[0]-a[0],s[1]-a[1],-s[0]+n[0],-s[1]+n[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 y0(e,t){let r=[e[2]*t,e[3]*t];return[e[0]-(r[0]-e[2])/2,e[1]-(r[1]-e[3])/2,r[0],r[1]]}var sC={initial:!0},ga={detector:null,landmarks:null},Sd={detector:[224,224],landmarks:[256,256]},xb=Number.MAX_SAFE_INTEGER,Vye={landmarks:["ld_3d","activation_segmentation","activation_heatmap","world_3d","output_poseflag"],detector:[]},x0=null,Vh,Gi=[[0,0],[0,0],[0,0],[0,0]],aC=0,nC=e=>1-1/(1+Math.exp(e));async function iC(e){if(sC.initial&&(ga.detector=null),!ga.detector&&e.body.detector&&e.body.detector.modelPath){ga.detector=await Ue(e.body.detector.modelPath);let t=Object.values(ga.detector.modelSignature.inputs);Sd.detector[0]=Array.isArray(t)?parseInt(t[0].tensorShape.dim[1].size):0,Sd.detector[1]=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):0}else e.debug&&ga.detector&&se("cached model:",ga.detector.modelUrl);return await tC(),ga.detector}async function oC(e){if(sC.initial&&(ga.landmarks=null),ga.landmarks)e.debug&&se("cached model:",ga.landmarks.modelUrl);else{ga.landmarks=await Ue(e.body.modelPath);let t=Object.values(ga.landmarks.modelSignature.inputs);Sd.landmarks[0]=Array.isArray(t)?parseInt(t[0].tensorShape.dim[1].size):0,Sd.landmarks[1]=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):0}return ga.landmarks}async function Uye(e,t){let r={};if(!e.shape||!e.shape[1]||!e.shape[2])return e;let a;if(Vh&&(r.cropped=Ie.cropAndResize(e,[Vh],[0],[e.shape[1],e.shape[2]])),e.shape[1]!==e.shape[2]){let n=[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],s=[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];Gi=[[0,0],n,s,[0,0]],r.pad=ja(r.cropped||e,Gi),r.resize=Ie.resizeBilinear(r.pad,[t,t]),a=pe(r.resize,Xe.tf255)}else e.shape[1]!==t?(r.resize=Ie.resizeBilinear(r.cropped||e,[t,t]),a=pe(r.resize,Xe.tf255)):a=pe(r.cropped||e,Xe.tf255);return Object.keys(r).forEach(n=>re(r[n])),a}function Gye(e,t){for(let r of e)r.position=[Math.trunc(r.position[0]*(t[0]+Gi[2][0]+Gi[2][1])/t[0]-Gi[2][0]),Math.trunc(r.position[1]*(t[1]+Gi[1][0]+Gi[1][1])/t[1]-Gi[1][0]),r.position[2]],r.positionRaw=[r.position[0]/t[0],r.position[1]/t[1],2*r.position[2]/(t[0]+t[1])];if(Vh)for(let r of e)r.positionRaw=[r.positionRaw[0]+Vh[1],r.positionRaw[1]+Vh[0],r.positionRaw[2]],r.position=[Math.trunc(r.positionRaw[0]*t[0]),Math.trunc(r.positionRaw[1]*t[1]),r.positionRaw[2]];return e}async function jye(e){let t=e.find(o=>o.part==="leftPalm"),r=e.find(o=>o.part==="leftWrist"),a=e.find(o=>o.part==="leftIndex");t.position[2]=((r.position[2]||0)+(a.position[2]||0))/2;let n=e.find(o=>o.part==="rightPalm"),s=e.find(o=>o.part==="rightWrist"),i=e.find(o=>o.part==="rightIndex");n.position[2]=((s.position[2]||0)+(i.position[2]||0))/2}async function Hye(e,t,r){var f;let a={};[a.ld,a.segmentation,a.heatmap,a.world,a.poseflag]=(f=ga.landmarks)==null?void 0:f.execute(e,Vye.landmarks);let n=(await a.poseflag.data())[0],s=await a.ld.data(),i=await a.world.data();Object.keys(a).forEach(m=>re(a[m]));let o=[],l=5;for(let m=0;m<s.length/l;m++){let g=nC(s[l*m+3]),y=nC(s[l*m+4]),A=Math.trunc(100*g*y*n)/100,x=[s[l*m+0]/Sd.landmarks[0],s[l*m+1]/Sd.landmarks[1],s[l*m+2]+0],b=[Math.trunc(r[0]*x[0]),Math.trunc(r[1]*x[1]),x[2]],v=[i[l*m+0],i[l*m+1],i[l*m+2]+0];o.push({part:yb[m],positionRaw:x,position:b,distance:v,score:A})}if(n<(t.body.minConfidence||0))return null;jye(o);let d=Gye(o,r),u=d.map(m=>m.position),p=ns(u,[r[0],r[1]]),h={};for(let[m,g]of Object.entries(Ab)){let y=[];for(let A=0;A<g.length-1;A++){let x=d.find(v=>v.part===g[A]),b=d.find(v=>v.part===g[A+1]);x&&b&&y.push([x.position,b.position])}h[m]=y}return{id:0,score:Math.trunc(100*n)/100,box:p.box,boxRaw:p.boxRaw,keypoints:d,annotations:h}}async function bb(e,t){let r=[e.shape[2]||0,e.shape[1]||0],a=(t.body.skipTime||0)>oe()-aC,n=xb<(t.body.skipFrames||0);if(t.skipAllowed&&a&&n&&x0!==null)xb++;else{let s={};s.landmarks=await Uye(e,256),x0=await Hye(s.landmarks,t,r),Object.keys(s).forEach(i=>re(s[i])),aC=oe(),xb=0}return x0?[x0]:[]}var Td=[{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 ss,Fl=0,vb=[],uC=0,wb=Number.MAX_SAFE_INTEGER;async function dC(e){if(ce.initial&&(ss=null),ss)e.debug&&se("cached model:",ss.modelUrl);else{ss=await Ue(e.object.modelPath);let t=Object.values(ss.modelSignature.inputs);Fl=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):0}return ss}async function qye(e,t,r){if(!e)return[];let a={},n=[],s=await e.array();a.squeeze=Ye(e);let i=Kt(a.squeeze,6,1);a.stack=nr([i[1],i[0],i[3],i[2]],1),a.boxes=Ye(a.stack),a.scores=Ye(i[4]),a.classes=Ye(i[5]),re([e,...i]),a.nms=await Ie.nonMaxSuppressionAsync(a.boxes,a.scores,r.object.maxDetected,r.object.iouThreshold,r.object.minConfidence||0);let o=await a.nms.data(),l=0;for(let d of Array.from(o)){let u=Math.trunc(100*s[0][d][4])/100,p=s[0][d][5],h=Td[p].label,[c,f]=[s[0][d][0]/Fl,s[0][d][1]/Fl],m=[c,f,s[0][d][2]/Fl-c,s[0][d][3]/Fl-f],g=[Math.trunc(m[0]*t[0]),Math.trunc(m[1]*t[1]),Math.trunc(m[2]*t[0]),Math.trunc(m[3]*t[1])];n.push({id:l++,score:u,class:p,label:h,box:g,boxRaw:m})}return Object.keys(a).forEach(d=>re(a[d])),n}async function kb(e,t){let r=(t.object.skipTime||0)>oe()-uC,a=wb<(t.object.skipFrames||0);return t.skipAllowed&&r&&a&&vb.length>0?(wb++,vb):(wb=0,new Promise(async n=>{let s=[e.shape[2]||0,e.shape[1]||0],i=Ie.resizeBilinear(e,[Fl,Fl]),o=t.object.enabled?ss==null?void 0:ss.execute(i,["tower_0/detections"]):null;uC=oe(),re(i);let l=await qye(o,s,t);vb=l,n(l)}))}var b0={};Qd(b0,{connected:()=>Sb,kpt:()=>Ib});var Ib=["head","neck","rightShoulder","rightElbow","rightWrist","chest","leftShoulder","leftElbow","leftWrist","bodyCenter","rightHip","rightKnee","rightAnkle","leftHip","leftKnee","leftAnkle"],Sb={leftLeg:["leftHip","leftKnee","leftAnkle"],rightLeg:["rightHip","rightKnee","rightAnkle"],torso:["leftShoulder","rightShoulder","rightHip","leftHip","leftShoulder"],leftArm:["leftShoulder","leftElbow","leftWrist"],rightArm:["rightShoulder","rightElbow","rightWrist"],head:[]};var Nr,hC=0,Gr={id:0,keypoints:[],box:[0,0,0,0],boxRaw:[0,0,0,0],score:0,annotations:{}},Tb=Number.MAX_SAFE_INTEGER;async function cC(e){return ce.initial&&(Nr=null),Nr?e.debug&&se("cached model:",Nr.modelUrl):Nr=await Ue(e.body.modelPath),Nr}async function Kye(e,t){let[r,a]=e.shape,n=U(e,[a*r]),s=hr(n,0),i=(await s.data())[0];if(re([n,s]),i>t){let o=Ta(n,0),l=ad(o,r),d=(await l.data())[0],u=pe(o,Se(r,"int32")),p=(await u.data())[0];return re([l,u]),[d,p,i]}return[0,0,i]}async function Cb(e,t){let r=(t.body.skipTime||0)>oe()-hC,a=Tb<(t.body.skipFrames||0);return t.skipAllowed&&r&&a&&Object.keys(Gr.keypoints).length>0?(Tb++,[Gr]):(Tb=0,new Promise(async n=>{var p;let s=q(()=>{if(!(Nr==null?void 0:Nr.inputs[0].shape))return null;let h=Ie.resizeBilinear(e,[Nr.inputs[0].shape[2],Nr.inputs[0].shape[1]],!1),c=L(h,Xe.tf2);return he(c,Xe.tf1)}),i;if(t.body.enabled&&(i=Nr==null?void 0:Nr.execute(s)),hC=oe(),re(s),i){Gr.keypoints.length=0;let h=i.squeeze();re(i);let c=h.unstack(2);re(h);for(let f=0;f<c.length;f++){let[m,g,y]=await Kye(c[f],t.body.minConfidence);y>(((p=t.body)==null?void 0:p.minConfidence)||0)&&Gr.keypoints.push({score:Math.round(100*y)/100,part:Ib[f],positionRaw:[m/Nr.inputs[0].shape[2],g/Nr.inputs[0].shape[1]],position:[Math.round(e.shape[2]*m/Nr.inputs[0].shape[2]),Math.round(e.shape[1]*g/Nr.inputs[0].shape[1])]})}c.forEach(f=>re(f))}Gr.score=Gr.keypoints.reduce((h,c)=>c.score>h?c.score:h,0);let o=Gr.keypoints.map(h=>h.position[0]),l=Gr.keypoints.map(h=>h.position[1]);Gr.box=[Math.min(...o),Math.min(...l),Math.max(...o)-Math.min(...o),Math.max(...l)-Math.min(...l)];let d=Gr.keypoints.map(h=>h.positionRaw[0]),u=Gr.keypoints.map(h=>h.positionRaw[1]);Gr.boxRaw=[Math.min(...d),Math.min(...u),Math.max(...d)-Math.min(...d),Math.max(...u)-Math.min(...u)];for(let[h,c]of Object.entries(Sb)){let f=[];for(let m=0;m<c.length-1;m++){let g=Gr.keypoints.find(A=>A.part===c[m]),y=Gr.keypoints.find(A=>A.part===c[m+1]);g&&y&&g.score>(t.body.minConfidence||0)&&y.score>(t.body.minConfidence||0)&&f.push([g.position,y.position])}Gr.annotations[h]=f}n([Gr])}))}var Xye=["angry","disgust","fear","happy","sad","surprise","neutral"],Oa,v0=[],mC=0,gC=0,Nb=Number.MAX_SAFE_INTEGER;async function yC(e){var t;return ce.initial&&(Oa=null),Oa?e.debug&&se("cached model:",Oa.modelUrl):Oa=await Ue((t=e.face.emotion)==null?void 0:t.modelPath),Oa}async function Eb(e,t,r,a){var i,o;if(!Oa)return[];let n=Nb<(((i=t.face.emotion)==null?void 0:i.skipFrames)||0),s=(((o=t.face.emotion)==null?void 0:o.skipTime)||0)>oe()-gC;return t.skipAllowed&&s&&n&&mC===a&&v0[r]&&v0[r].length>0?(Nb++,v0[r]):(Nb=0,new Promise(async l=>{var u,p;let d=[];if((u=t.face.emotion)==null?void 0:u.enabled){let h={},c=(Oa==null?void 0:Oa.inputs[0].shape)?Oa.inputs[0].shape[2]:0;h.resize=Ie.resizeBilinear(e,[c,c],!1),h.channels=L(h.resize,Xe.rgb),h.grayscale=ke(h.channels,3,!0),h.grayscaleSub=he(h.grayscale,Xe.tf05),h.grayscaleMul=L(h.grayscaleSub,Xe.tf2),h.emotion=Oa==null?void 0:Oa.execute(h.grayscaleMul),gC=oe();let f=await h.emotion.data();for(let m=0;m<f.length;m++)f[m]>(((p=t.face.emotion)==null?void 0:p.minConfidence)||0)&&d.push({score:Math.min(.99,Math.trunc(100*f[m])/100),emotion:Xye[m]});d.sort((m,g)=>g.score-m.score),Object.keys(h).forEach(m=>re(h[m]))}v0[r]=d,mC=a,l(d)}))}var ya,Rb=[],xC=0,bC=0,vC=Number.MAX_SAFE_INTEGER;async function wC(e){return ce.initial&&(ya=null),ya?e.debug&&se("cached model:",ya.modelUrl):ya=await Ue(e.face.mobilefacenet.modelPath),ya}async function Fb(e,t,r,a){var i,o;if(!ya)return[];let n=vC<(((i=t.face.embedding)==null?void 0:i.skipFrames)||0),s=(((o=t.face.embedding)==null?void 0:o.skipTime)||0)>oe()-bC;return t.skipAllowed&&s&&n&&xC===a&&Rb[r]?(vC++,Rb[r]):new Promise(async l=>{var u;let d=[];if(((u=t.face.embedding)==null?void 0:u.enabled)&&(ya==null?void 0:ya.inputs[0].shape)){let p={};p.crop=Ie.resizeBilinear(e,[ya.inputs[0].shape[2],ya.inputs[0].shape[1]],!1),p.data=ya==null?void 0:ya.execute(p.crop);let h=await p.data.data();d=Array.from(h)}Rb[r]=d,xC=a,bC=oe(),l(d)})}var is,ji=0,Zye=2.3,Mb=Ya.leftEyeLower0,$b=Ya.rightEyeLower0,Cd={leftBounds:[Mb[0],Mb[Mb.length-1]],rightBounds:[$b[0],$b[$b.length-1]]},Nd={upperCenter:3,lowerCenter:4,index:71,numCoordinates:76};async function CC(e){var t;return ce.initial&&(is=null),is?e.debug&&se("cached model:",is.modelUrl):is=await Ue((t=e.face.iris)==null?void 0:t.modelPath),ji=is.inputs[0].shape?is.inputs[0].shape[2]:0,ji===-1&&(ji=64),is}function w0(e,t,r,a){for(let n=0;n<db.length;n++){let{key:s,indices:i}=db[n],o=Ya[`${r}${s}`];if(!a||a.includes(s))for(let l=0;l<i.length;l++){let d=i[l];e[o[l]]=[t[d][0],t[d][1],(t[d][2]+e[o[l]][2])/2]}}}var Yye=e=>{let t=e[Cd.leftBounds[0]][2],r=e[Cd.rightBounds[0]][2];return t-r},IC=(e,t,r,a,n,s=!1)=>{let i=c0(h0(UT([e[r],e[a]]),Zye)),o=Id(i),l=Ie.cropAndResize(t,[[i.startPoint[1]/n,i.startPoint[0]/n,i.endPoint[1]/n,i.endPoint[0]/n]],[0],[ji,ji]);if(s&&ce.kernels.includes("flipleftright")){let d=Ie.flipLeftRight(l);re(l),l=d}return{box:i,boxSize:o,crop:l}},SC=(e,t,r,a=!1)=>{let n=[];for(let s=0;s<Nd.numCoordinates;s++){let i=e[s*3],o=e[s*3+1],l=e[s*3+2];n.push([(a?1-i/ji:i/ji)*r[0]+t.startPoint[0],o/ji*r[1]+t.startPoint[1],l])}return{rawCoords:n,iris:n.slice(Nd.index)}},TC=(e,t,r)=>{let a=e[Ya[`${r}EyeUpper0`][Nd.upperCenter]][2],n=e[Ya[`${r}EyeLower0`][Nd.lowerCenter]][2],s=(a+n)/2;return t.map((i,o)=>{let l=s;return o===2?l=a:o===4&&(l=n),[i[0],i[1],l]})};async function NC(e,t,r,a){if(!is)return r.debug&&se("face mesh iris detection requested, but model is not loaded"),e;let{box:n,boxSize:s,crop:i}=IC(e,t,Cd.leftBounds[0],Cd.leftBounds[1],a,!0),{box:o,boxSize:l,crop:d}=IC(e,t,Cd.rightBounds[0],Cd.rightBounds[1],a,!0),u=kt([i,d]);re(i),re(d);let p=is.execute(u);re(u);let h=await p.data();re(p);let c=h.slice(0,Nd.numCoordinates*3),{rawCoords:f,iris:m}=SC(c,n,s,!0),g=h.slice(Nd.numCoordinates*3),{rawCoords:y,iris:A}=SC(g,o,l),x=Yye(e);Math.abs(x)<30?(w0(e,f,"left",null),w0(e,y,"right",null)):x<1?w0(e,f,"left",["EyeUpper0","EyeLower0"]):w0(e,y,"right",["EyeUpper0","EyeLower0"]);let b=TC(e,m,"left"),v=TC(e,A,"right");return e.concat(b).concat(v)}var Pn={boxes:[],skipped:Number.MAX_SAFE_INTEGER,timestamp:0},os=null,Ed=0;async function RC(e,t){var o,l,d,u,p,h,c,f,m;let r=(((o=t.face.detector)==null?void 0:o.skipTime)||0)>oe()-Pn.timestamp,a=Pn.skipped<(((l=t.face.detector)==null?void 0:l.skipFrames)||0);!t.skipAllowed||!r||!a||Pn.boxes.length===0?(Pn.boxes=await JT(e,t),Pn.timestamp=oe(),Pn.skipped=0):Pn.skipped++;let n=[],s=[],i=0;for(let g=0;g<Pn.boxes.length;g++){let y=Pn.boxes[g],A=0,x,b={id:i++,mesh:[],meshRaw:[],box:[0,0,0,0],boxRaw:[0,0,0,0],score:0,boxScore:0,faceScore:0,annotations:{}};if([A,x,b.tensor]=qT((d=t.face.detector)==null?void 0:d.rotation,y,e,((u=t.face.mesh)==null?void 0:u.enabled)?Ed:f0()),(p=t==null?void 0:t.filter)==null?void 0:p.equalization){let v=await i0(b.tensor);re(b.tensor),b.tensor=v}if(b.boxScore=Math.round(100*y.confidence)/100,(h=t.face.mesh)==null?void 0:h.enabled)if(!os)t.debug&&se("face mesh detection requested, but model is not loaded");else{let[v,C,T]=os.execute(b.tensor),E=await C.data();b.faceScore=Math.round(100*E[0])/100;let R=U(T,[-1,3]),z=await R.array();if(re([T,R,C,v]),b.faceScore<(((c=t.face.detector)==null?void 0:c.minConfidence)||1))y.confidence=b.faceScore;else{((f=t.face.iris)==null?void 0:f.enabled)&&(z=await NC(z,b.tensor,t,Ed)),b.mesh=HT(z,y,A,x,Ed),b.meshRaw=b.mesh.map(I=>[I[0]/(e.shape[2]||0),I[1]/(e.shape[1]||0),(I[2]||0)/Ed]);for(let I of Object.keys(Ya))b.annotations[I]=Ya[I].map(D=>b.mesh[D]);b.score=b.faceScore;let M={...KT(b.mesh,y),confidence:y.confidence,landmarks:y.landmarks};b.box=fb(M,e),b.boxRaw=mb(M,e),s.push(M)}}else{b.box=fb(y,e),b.boxRaw=mb(y,e),b.score=b.boxScore,b.mesh=y.landmarks.map(v=>[(y.startPoint[0]+y.endPoint[0])/2+(y.endPoint[0]+y.startPoint[0])*v[0]/f0(),(y.startPoint[1]+y.endPoint[1])/2+(y.endPoint[1]+y.startPoint[1])*v[1]/f0()]),b.meshRaw=b.mesh.map(v=>[v[0]/(e.shape[2]||0),v[1]/(e.shape[1]||0),(v[2]||0)/Ed]);for(let v of Object.keys(Lh))b.annotations[v]=[b.mesh[Lh[v]]]}b.score>(((m=t.face.detector)==null?void 0:m.minConfidence)||1)?n.push(b):re(b.tensor)}return Pn.boxes=s,n}async function FC(e){var t;return ce.initial&&(os=null),os?e.debug&&se("cached model:",os.modelUrl):os=await Ue((t=e.face.mesh)==null?void 0:t.modelPath),Ed=os.inputs[0].shape?os.inputs[0].shape[2]:0,os}var MC=El,$C=Bh;var Aa,k0=[],PC=0,OC=0,Ob=Number.MAX_SAFE_INTEGER;async function zC(e){var t;return ce.initial&&(Aa=null),Aa?e.debug&&se("cached model:",Aa.modelUrl):Aa=await Ue((t=e.face.description)==null?void 0:t.modelPath),Aa}function zb(e){let t=e.image||e.tensor||e;if(!(Aa==null?void 0:Aa.inputs[0].shape))return t;let r=Ie.resizeBilinear(t,[Aa.inputs[0].shape[2],Aa.inputs[0].shape[1]],!1),a=L(r,Xe.tf255);return re(r),a}async function Db(e,t,r,a){var i,o,l,d;if(!Aa)return{age:0,gender:"unknown",genderScore:0,descriptor:[]};let n=Ob<(((i=t.face.description)==null?void 0:i.skipFrames)||0),s=(((o=t.face.description)==null?void 0:o.skipTime)||0)>oe()-PC;return t.skipAllowed&&n&&s&&OC===a&&((l=k0[r])==null?void 0:l.age)&&((d=k0[r])==null?void 0:d.age)>0?(Ob++,k0[r]):(Ob=0,new Promise(async u=>{var h,c;let p={age:0,gender:"unknown",genderScore:0,descriptor:[]};if((h=t.face.description)==null?void 0:h.enabled){let f=zb(e),m=Aa==null?void 0:Aa.execute(f);PC=oe(),re(f);let y=await(await m.find(R=>R.shape[1]===1)).data(),A=Math.trunc(200*Math.abs(y[0]-.5))/100;A>(((c=t.face.description)==null?void 0:c.minConfidence)||0)&&(p.gender=y[0]<=.5?"female":"male",p.genderScore=Math.min(.99,A));let x=Ta(m.find(R=>R.shape[1]===100),1),b=(await x.data())[0];re(x);let C=await m.find(R=>R.shape[1]===100).data();p.age=Math.round(C[b-1]>C[b+1]?10*b-100*C[b-1]:10*b+100*C[b+1])/10;let T=m.find(R=>R.shape[1]===1024),E=T?await T.data():[];p.descriptor=Array.from(E),m.forEach(R=>re(R))}k0[r]=p,OC=a,u(p)}))}function I0(e){return[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])]}function Uh(e){return[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2]}function LC(e,t,r){let a=t.shape[1],n=t.shape[2],s=[[e.startPoint[1]/a,e.startPoint[0]/n,e.endPoint[1]/a,e.endPoint[0]/n]];return Ie.cropAndResize(t,s,[0],r)}function BC(e,t){let r=[e.startPoint[0]*t[0],e.startPoint[1]*t[1]],a=[e.endPoint[0]*t[0],e.endPoint[1]*t[1]],n=e.palmLandmarks.map(s=>[s[0]*t[0],s[1]*t[1]]);return{startPoint:r,endPoint:a,palmLandmarks:n,confidence:e.confidence}}function S0(e,t=1.5){let r=Uh(e),a=I0(e),n=[t*a[0]/2,t*a[1]/2],s=[r[0]-n[0],r[1]-n[1]],i=[r[0]+n[0],r[1]+n[1]];return{startPoint:s,endPoint:i,palmLandmarks:e.palmLandmarks}}function T0(e){let t=Uh(e),r=I0(e),n=Math.max(...r)/2,s=[t[0]-n,t[1]-n],i=[t[0]+n,t[1]+n];return{startPoint:s,endPoint:i,palmLandmarks:e.palmLandmarks}}function Jye(e){return e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI))}function WC(e,t){let r=Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]);return Jye(r)}var DC=(e,t)=>[[1,0,e],[0,1,t],[0,0,1]];function Hi(e,t){let r=0;for(let a=0;a<e.length;a++)r+=e[a]*t[a];return r}function Qye(e,t){let r=[];for(let a=0;a<e.length;a++)r.push(e[a][t]);return r}function _C(e,t){let r=[],a=e.length;for(let n=0;n<a;n++){r.push([]);for(let s=0;s<a;s++)r[n].push(Hi(e[n],Qye(t,s)))}return r}function Lb(e,t){let r=Math.cos(e),a=Math.sin(e),n=[[r,-a,0],[a,r,0],[0,0,1]],s=DC(t[0],t[1]),i=_C(s,n),o=DC(-t[0],-t[1]);return _C(i,o)}function VC(e){let t=[[e[0][0],e[1][0]],[e[0][1],e[1][1]]],r=[e[0][2],e[1][2]],a=[-Hi(t[0],r),-Hi(t[1],r)];return[t[0].concat(a[0]),t[1].concat(a[1]),[0,0,1]]}function Bb(e,t){return[Hi(e,t[0]),Hi(e,t[1])]}var GC=[{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 Wb=class{constructor(t){fe(this,"model");fe(this,"anchors");fe(this,"anchorsTensor");fe(this,"inputSize");fe(this,"inputSizeTensor");fe(this,"doubleInputSizeTensor");this.model=t,this.anchors=GC.map(r=>[r.x,r.y]),this.anchorsTensor=an(this.anchors),this.inputSize=this.model&&this.model.inputs&&this.model.inputs[0].shape?this.model.inputs[0].shape[2]:0,this.inputSizeTensor=St([this.inputSize,this.inputSize]),this.doubleInputSizeTensor=St([this.inputSize*2,this.inputSize*2])}normalizeBoxes(t){let r={};r.boxOffsets=Oe(t,[0,0],[-1,2]),r.boxSizes=Oe(t,[0,2],[-1,2]),r.div=pe(r.boxOffsets,this.inputSizeTensor),r.boxCenterPoints=ue(r.div,this.anchorsTensor),r.halfBoxSizes=pe(r.boxSizes,this.doubleInputSizeTensor),r.sub=he(r.boxCenterPoints,r.halfBoxSizes),r.startPoints=L(r.sub,this.inputSizeTensor),r.add=ue(r.boxCenterPoints,r.halfBoxSizes),r.endPoints=L(r.add,this.inputSizeTensor);let a=ed([r.startPoints,r.endPoints],1);return Object.keys(r).forEach(n=>re(r[n])),a}normalizeLandmarks(t,r){let a={};a.reshape=U(t,[-1,7,2]),a.div=pe(a.reshape,this.inputSizeTensor),a.landmarks=ue(a.div,this.anchors[r]);let n=L(a.landmarks,this.inputSizeTensor);return Object.keys(a).forEach(s=>re(a[s])),n}async predict(t,r){let a={};a.resize=Ie.resizeBilinear(t,[this.inputSize,this.inputSize]),a.div=pe(a.resize,Xe.tf127),a.image=he(a.div,Xe.tf1),a.batched=this.model.execute(a.image),a.predictions=Ye(a.batched),a.slice=Oe(a.predictions,[0,0],[-1,1]),a.sigmoid=Sr(a.slice),a.scores=Ye(a.sigmoid);let n=await a.scores.data();a.boxes=Oe(a.predictions,[0,1],[-1,4]),a.norm=this.normalizeBoxes(a.boxes),a.nms=await Ie.nonMaxSuppressionAsync(a.norm,a.scores,3*r.hand.maxDetected,r.hand.iouThreshold,r.hand.minConfidence);let s=await a.nms.array(),i=[];for(let o of s){let l={};l.box=Oe(a.norm,[o,0],[1,-1]),l.slice=Oe(a.predictions,[o,5],[1,14]),l.norm=this.normalizeLandmarks(l.slice,o),l.palmLandmarks=U(l.norm,[-1,2]);let d=await l.box.data(),u=d.slice(0,2),p=d.slice(2,4),h=await l.palmLandmarks.array(),c={startPoint:u,endPoint:p,palmLandmarks:h,confidence:n[o]},f=BC(c,[t.shape[2]/this.inputSize,t.shape[1]/this.inputSize]);i.push(f),Object.keys(l).forEach(m=>re(l[m]))}return Object.keys(a).forEach(o=>re(a[o])),i}};var r2e=5,jC=1.65,HC=[0,5,9,13,17,1,2],a2e=0,n2e=2,qC=0,Vb=class{constructor(t,r){fe(this,"handDetector");fe(this,"handPoseModel");fe(this,"inputSize");fe(this,"storedBoxes");fe(this,"skipped");fe(this,"detectedHands");this.handDetector=t,this.handPoseModel=r,this.inputSize=this.handPoseModel&&this.handPoseModel.inputs[0].shape?this.handPoseModel.inputs[0].shape[2]:0,this.storedBoxes=[],this.skipped=Number.MAX_SAFE_INTEGER,this.detectedHands=0}calculateLandmarksBoundingBox(t){let r=t.map(i=>i[0]),a=t.map(i=>i[1]),n=[Math.min(...r),Math.min(...a)],s=[Math.max(...r),Math.max(...a)];return{startPoint:n,endPoint:s}}getBoxForPalmLandmarks(t,r){let a=t.map(s=>Bb([...s,1],r)),n=this.calculateLandmarksBoundingBox(a);return S0(T0(n),r2e)}getBoxForHandLandmarks(t){let r=this.calculateLandmarksBoundingBox(t),a=S0(T0(r),jC);a.palmLandmarks=[];for(let n=0;n<HC.length;n++)a.palmLandmarks.push(t[HC[n]].slice(0,2));return a}transformRawCoords(t,r,a,n){let s=I0(r),i=[s[0]/this.inputSize,s[1]/this.inputSize,(s[0]+s[1])/this.inputSize/2],o=t.map(c=>[i[0]*(c[0]-this.inputSize/2),i[1]*(c[1]-this.inputSize/2),i[2]*c[2]]),l=Lb(a,[0,0]),d=o.map(c=>[...Bb(c,l),c[2]]),u=VC(n),p=[...Uh(r),1],h=[Hi(p,u[0]),Hi(p,u[1])];return d.map(c=>[Math.trunc(c[0]+h[0]),Math.trunc(c[1]+h[1]),Math.trunc(c[2])])}async estimateHands(t,r){let a=!1,n,s=(r.hand.skipTime||0)>oe()-qC,i=this.skipped<(r.hand.skipFrames||0);r.skipAllowed&&s&&i&&(n=await this.handDetector.predict(t,r),this.skipped=0),r.skipAllowed&&this.skipped++,n&&n.length>0&&(n.length!==this.detectedHands&&this.detectedHands!==r.hand.maxDetected||!r.hand.landmarks)&&(this.detectedHands=0,this.storedBoxes=[...n],this.storedBoxes.length>0&&(a=!0));let o=[];for(let l=0;l<this.storedBoxes.length;l++){let d=this.storedBoxes[l];if(!!d)if(r.hand.landmarks){let u=r.hand.rotation?WC(d.palmLandmarks[a2e],d.palmLandmarks[n2e]):0,p=Uh(d),h=[p[0]/t.shape[2],p[1]/t.shape[1]],c=r.hand.rotation&&ce.kernels.includes("rotatewithoffset")?Ie.rotateWithOffset(t,u,0,h):t.clone(),f=Lb(-u,p),m=a?this.getBoxForPalmLandmarks(d.palmLandmarks,f):d,g=LC(m,c,[this.inputSize,this.inputSize]),y=pe(g,Xe.tf255);re(g),re(c);let[A,x]=this.handPoseModel.execute(y);qC=oe(),re(y);let b=(await A.data())[0];if(re(A),b>=r.hand.minConfidence/4){let v=U(x,[-1,3]),C=await v.array();re(x),re(v);let T=this.transformRawCoords(C,m,u,f),E=this.getBoxForHandLandmarks(T);this.storedBoxes[l]={...E,confidence:b};let R={landmarks:T,confidence:b,boxConfidence:d.confidence,fingerConfidence:b,box:{topLeft:E.startPoint,bottomRight:E.endPoint}};o.push(R)}else this.storedBoxes[l]=null;re(x)}else{let u=S0(T0(d),jC),p={confidence:d.confidence,boxConfidence:d.confidence,fingerConfidence:0,box:{topLeft:u.startPoint,bottomRight:u.endPoint},landmarks:[]};o.push(p)}}return this.storedBoxes=this.storedBoxes.filter(l=>l!==null),this.detectedHands=o.length,o.length>r.hand.maxDetected&&(o.length=r.hand.maxDetected),o}};var jr={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=>jr.nameMapping[e],getPoints:e=>jr.pointsMapping[e]},qi={none:0,half:1,full:2,nameMapping:{0:"none",1:"half",2:"full"},getName:e=>qi.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]},Ml=class{constructor(t){fe(this,"name");fe(this,"curls");fe(this,"directions");fe(this,"weights");fe(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,r,a){typeof this.curls[t]=="undefined"&&(this.curls[t]=[]),this.curls[t].push([r,a])}direction(t,r,a){this.directions[t]||(this.directions[t]=[]),this.directions[t].push([r,a])}weight(t,r){this.weights[t]=r;let a=this.weights.reduce((n,s)=>n+s,0);this.weightsRelative=this.weights.map(n=>n*5/a)}matchAgainst(t,r){let a=0;for(let n in t){let s=t[n],i=this.curls[n];if(typeof i=="undefined"){a+=this.weightsRelative[n];continue}for(let[o,l]of i)if(s===o){a+=l*this.weightsRelative[n];break}}for(let n in r){let s=r[n],i=this.directions[n];if(typeof i=="undefined"){a+=this.weightsRelative[n];continue}for(let[o,l]of i)if(s===o){a+=l*this.weightsRelative[n];break}}return a/10}};var{thumb:mn,index:ls,middle:us,ring:$l,pinky:Pl}=jr,{none:gn,half:i2e,full:yn}=qi,{verticalUp:Rd,verticalDown:cxe,horizontalLeft:Ub,horizontalRight:o2e,diagonalUpRight:l2e,diagonalUpLeft:Fd,diagonalDownRight:fxe,diagonalDownLeft:mxe}=_t,Ki=new Ml("thumbs up");Ki.curl(mn,gn,1);Ki.direction(mn,Rd,1);Ki.direction(mn,Fd,.25);Ki.direction(mn,l2e,.25);for(let e of[jr.index,jr.middle,jr.ring,jr.pinky])Ki.curl(e,yn,1),Ki.direction(e,Ub,1),Ki.direction(e,o2e,1);var Yt=new Ml("victory");Yt.curl(mn,i2e,.5);Yt.curl(mn,gn,.5);Yt.direction(mn,Rd,1);Yt.direction(mn,Fd,1);Yt.curl(ls,gn,1);Yt.direction(ls,Rd,.75);Yt.direction(ls,Fd,1);Yt.curl(us,gn,1);Yt.direction(us,Rd,1);Yt.direction(us,Fd,.75);Yt.curl($l,yn,1);Yt.direction($l,Rd,.2);Yt.direction($l,Fd,1);Yt.direction($l,Ub,.2);Yt.curl(Pl,yn,1);Yt.direction(Pl,Rd,.2);Yt.direction(Pl,Fd,1);Yt.direction(Pl,Ub,.2);Yt.weight(ls,2);Yt.weight(us,2);var Xi=new Ml("point");Xi.curl(mn,yn,1);Xi.curl(ls,gn,.5);Xi.curl(us,yn,.5);Xi.curl($l,yn,.5);Xi.curl(Pl,yn,.5);Xi.weight(ls,2);Xi.weight(us,2);var Zi=new Ml("middle finger");Zi.curl(mn,gn,1);Zi.curl(ls,yn,.5);Zi.curl(us,yn,.5);Zi.curl($l,yn,.5);Zi.curl(Pl,yn,.5);Zi.weight(ls,2);Zi.weight(us,2);var Md=new Ml("open palm");Md.curl(mn,gn,.75);Md.curl(ls,gn,.75);Md.curl(us,gn,.75);Md.curl($l,gn,.75);Md.curl(Pl,gn,.75);var KC=[Ki,Yt,Xi,Zi,Md];var u2e=.7,Ol={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 XC(e,t,r,a){let n=(t-a)/(e-r),s=Math.atan(n)*180/Math.PI;return s<=0?s=-s:s>0&&(s=180-s),s}function YC(e,t){if(!e||!t)return[0,0];let r=XC(e[0],e[1],t[0],t[1]);if(e.length===2)return r;let a=XC(e[1],e[2],t[1],t[2]);return[r,a]}function ZC(e,t=1){let r=0,a=0,n=0;return e>=75&&e<=105?r=1*t:e>=25&&e<=155?a=1*t:n=1*t,[r,a,n]}function d2e(e,t,r){let a=e[0]-t[0],n=e[0]-r[0],s=t[0]-r[0],i=e[1]-t[1],o=e[1]-r[1],l=t[1]-r[1],d=e[2]-t[2],u=e[2]-r[2],p=t[2]-r[2],h=Math.sqrt(a*a+i*i+d*d),c=Math.sqrt(n*n+o*o+u*u),f=Math.sqrt(s*s+l*l+p*p),m=(f*f+h*h-c*c)/(2*f*h);m>1?m=1:m<-1&&(m=-1);let g=Math.acos(m);g=57.2958*g%180;let y;return g>Ol.NO_CURL_START_LIMIT?y=qi.none:g>Ol.HALF_CURL_START_LIMIT?y=qi.half:y=qi.full,y}function JC(e,t,r,a){let n;return a===Math.abs(e)?e>0?n=_t.horizontalLeft:n=_t.horizontalRight:a===Math.abs(t)?t>0?n=_t.horizontalLeft:n=_t.horizontalRight:r>0?n=_t.horizontalLeft:n=_t.horizontalRight,n}function QC(e,t,r,a){let n;return a===Math.abs(e)?e<0?n=_t.verticalDown:n=_t.verticalUp:a===Math.abs(t)?t<0?n=_t.verticalDown:n=_t.verticalUp:r<0?n=_t.verticalDown:n=_t.verticalUp,n}function p2e(e,t,r,a,n,s,i,o){let l,d=QC(e,t,r,a),u=JC(n,s,i,o);return d===_t.verticalUp?u===_t.horizontalLeft?l=_t.diagonalUpLeft:l=_t.diagonalUpRight:u===_t.horizontalLeft?l=_t.diagonalDownLeft:l=_t.diagonalDownRight,l}function h2e(e,t,r,a){let n=e[0]-t[0],s=e[0]-r[0],i=t[0]-r[0],o=e[1]-t[1],l=e[1]-r[1],d=t[1]-r[1],u=Math.max(Math.abs(n),Math.abs(s),Math.abs(i)),p=Math.max(Math.abs(o),Math.abs(l),Math.abs(d)),h=0,c=0,f=0,m=p/(u+1e-5);m>1.5?h+=Ol.DISTANCE_VOTE_POWER:m>.66?c+=Ol.DISTANCE_VOTE_POWER:f+=Ol.DISTANCE_VOTE_POWER;let g=Math.sqrt(n*n+o*o),y=Math.sqrt(s*s+l*l),A=Math.sqrt(i*i+d*d),x=Math.max(g,y,A),b=e[0],v=e[1],C=r[0],T=r[1];x===g?(C=r[0],T=r[1]):x===A&&(b=t[0],v=t[1]);let z=YC([b,v],[C,T]),M=ZC(z,Ol.TOTAL_ANGLE_VOTE_POWER);h+=M[0],c+=M[1],f+=M[2];for(let D of a){let O=ZC(D,Ol.SINGLE_ANGLE_VOTE_POWER);h+=O[0],c+=O[1],f+=O[2]}let I;return h===Math.max(h,c,f)?I=QC(l,o,d,p):f===Math.max(c,f)?I=JC(s,n,i,u):I=p2e(l,o,d,p,s,n,i,u),I}function eN(e){let t=[],r=[],a=[],n=[];if(!e)return{curls:a,directions:n};for(let s of jr.all){let i=jr.getPoints(s),o=[],l=[];for(let d of i){let u=e[d[0]],p=e[d[1]],h=YC(u,p),c=h[0],f=h[1];o.push(c),l.push(f)}t.push(o),r.push(l)}for(let s of jr.all){let i=s===jr.thumb?1:0,o=jr.getPoints(s),l=e[o[i][0]],d=e[o[i+1][1]],u=e[o[3][1]],p=d2e(l,d,u),h=h2e(l,d,u,t[s].slice(i));a[s]=p,n[s]=h}return{curls:a,directions:n}}function C0(e){if(!e||e.length===0)return null;let t=eN(e),r={};for(let a of jr.all)r[jr.getName(a)]={curl:qi.getName(t.curls[a]),direction:_t.getName(t.directions[a])};return r}function tN(e){let t=[];if(!e||e.length===0)return t;let r=eN(e);for(let a of KC){let n=a.matchAgainst(r.curls,r.directions);n>=u2e&&t.push({name:a.name,confidence:n})}return t}var rN={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]},$d,Pd,aN;async function jb(e,t){let r=await aN.estimateHands(e,t);if(!r)return[];let a=[];for(let n=0;n<r.length;n++){let s={};if(r[n].landmarks)for(let u of Object.keys(rN))s[u]=rN[u].map(p=>r[n].landmarks[p]);let i=r[n].landmarks,o=[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,0,0],l=[0,0,0,0];if(i&&i.length>0){for(let u of i)u[0]<o[0]&&(o[0]=u[0]),u[1]<o[1]&&(o[1]=u[1]),u[0]>o[2]&&(o[2]=u[0]),u[1]>o[3]&&(o[3]=u[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=r[n].box?[Math.trunc(Math.max(0,r[n].box.topLeft[0])),Math.trunc(Math.max(0,r[n].box.topLeft[1])),Math.trunc(Math.min(e.shape[2]||0,r[n].box.bottomRight[0])-Math.max(0,r[n].box.topLeft[0])),Math.trunc(Math.min(e.shape[1]||0,r[n].box.bottomRight[1])-Math.max(0,r[n].box.topLeft[1]))]:[0,0,0,0],l=[r[n].box.topLeft[0]/(e.shape[2]||0),r[n].box.topLeft[1]/(e.shape[1]||0),(r[n].box.bottomRight[0]-r[n].box.topLeft[0])/(e.shape[2]||0),(r[n].box.bottomRight[1]-r[n].box.topLeft[1])/(e.shape[1]||0)];let d=C0(i);a.push({id:n,score:Math.round(100*r[n].confidence)/100,boxScore:Math.round(100*r[n].boxConfidence)/100,fingerScore:Math.round(100*r[n].fingerConfidence)/100,label:"hand",box:o,boxRaw:l,keypoints:i,annotations:s,landmarks:d})}return a}async function Hb(e){var r,a;ce.initial&&($d=null,Pd=null),!$d||!Pd?[$d,Pd]=await Promise.all([e.hand.enabled?Ue((r=e.hand.detector)==null?void 0:r.modelPath):null,e.hand.landmarks?Ue((a=e.hand.skeleton)==null?void 0:a.modelPath):null]):(e.debug&&se("cached model:",$d.modelUrl),e.debug&&se("cached model:",Pd.modelUrl));let t=new Wb($d);return aN=new Vb(t,Pd),[$d,Pd]}var or=[null,null],c2e=["StatefulPartitionedCall/Postprocessor/Slice","StatefulPartitionedCall/Postprocessor/ExpandDims_1"],Yi=[[0,0],[0,0]],f2e=["hand","fist","pinch","point","face","tip","pinchtip"],sN=4,iN=1.6,m2e=512,g2e=1.4,N0=Number.MAX_SAFE_INTEGER,qb=0,ds=[0,0],jt={boxes:[],hands:[]},oN={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 lN(e){var t;if(ce.initial&&(or[0]=null),or[0])e.debug&&se("cached model:",or[0].modelUrl);else{E0(["tensorlistreserve","enter","tensorlistfromtensor","merge","loopcond","switch","exit","tensorliststack","nextiteration","tensorlistsetitem","tensorlistgetitem","reciprocal","shape","split","where"],e),or[0]=await Ue((t=e.hand.detector)==null?void 0:t.modelPath);let r=Object.values(or[0].modelSignature.inputs);Yi[0][0]=Array.isArray(r)?parseInt(r[0].tensorShape.dim[1].size):0,Yi[0][1]=Array.isArray(r)?parseInt(r[0].tensorShape.dim[2].size):0}return or[0]}async function uN(e){var t;if(ce.initial&&(or[1]=null),or[1])e.debug&&se("cached model:",or[1].modelUrl);else{or[1]=await Ue((t=e.hand.skeleton)==null?void 0:t.modelPath);let r=Object.values(or[1].modelSignature.inputs);Yi[1][0]=Array.isArray(r)?parseInt(r[0].tensorShape.dim[1].size):0,Yi[1][1]=Array.isArray(r)?parseInt(r[0].tensorShape.dim[2].size):0}return or[1]}async function y2e(e,t){let r=[];if(!e||!or[0])return r;let a={},n=(e.shape[2]||1)/(e.shape[1]||1),s=Math.min(Math.round((e.shape[1]||0)/8)*8,m2e),i=Math.round(s*n/8)*8;a.resize=Ie.resizeBilinear(e,[s,i]),a.cast=me(a.resize,"int32"),[a.rawScores,a.rawBoxes]=await or[0].executeAsync(a.cast,c2e),a.boxes=Ye(a.rawBoxes,[0,2]),a.scores=Ye(a.rawScores,[0]);let o=ra(a.scores,1);re(o[sN]),o.splice(sN,1),a.filtered=nr(o,1),re(o),a.max=hr(a.filtered,1),a.argmax=Ta(a.filtered,1);let l=0;a.nms=await Ie.nonMaxSuppressionAsync(a.boxes,a.max,(t.hand.maxDetected||0)+1,t.hand.iouThreshold||0,t.hand.minConfidence||1);let d=await a.nms.data(),u=await a.max.data(),p=await a.argmax.data();for(let h of Array.from(d)){let c=Oe(a.boxes,h,1),f=await c.data();re(c);let m=[f[1],f[0],f[3]-f[1],f[2]-f[0]],g=y0(m,g2e),y=[Math.trunc(m[0]*ds[0]),Math.trunc(m[1]*ds[1]),Math.trunc(m[2]*ds[0]),Math.trunc(m[3]*ds[1])],A=u[h],x=f2e[p[h]],b={id:l++,score:A,box:y,boxRaw:g,label:x};r.push(b)}return Object.keys(a).forEach(h=>re(a[h])),r.sort((h,c)=>c.score-h.score),r.length>(t.hand.maxDetected||1)&&(r.length=t.hand.maxDetected||1),r}async function Kb(e,t,r){let a={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&&or[1]&&r.hand.landmarks&&t.score>(r.hand.minConfidence||0)){let n={},s=[t.boxRaw[1],t.boxRaw[0],t.boxRaw[3]+t.boxRaw[1],t.boxRaw[2]+t.boxRaw[0]];n.crop=Ie.cropAndResize(e,[s],[0],[Yi[1][0],Yi[1][1]],"bilinear"),n.div=pe(n.crop,Xe.tf255),[n.score,n.keypoints]=or[1].execute(n.div,["Identity_1","Identity"]);let i=(await n.score.data())[0],o=(100-Math.trunc(100/(1+Math.exp(i))))/100;if(o>=(r.hand.minConfidence||0)){a.fingerScore=o,n.reshaped=U(n.keypoints,[-1,3]);let u=(await n.reshaped.array()).map(p=>[p[0]/Yi[1][1],p[1]/Yi[1][0],p[2]||0]).map(p=>[p[0]*t.boxRaw[2],p[1]*t.boxRaw[3],p[2]||0]);a.keypoints=u.map(p=>[ds[0]*(p[0]+t.boxRaw[0]),ds[1]*(p[1]+t.boxRaw[1]),p[2]||0]),a.landmarks=C0(a.keypoints);for(let p of Object.keys(oN))a.annotations[p]=oN[p].map(h=>a.landmarks&&a.keypoints[h]?a.keypoints[h]:null)}Object.keys(n).forEach(l=>re(n[l]))}return a}async function Xb(e,t){var n,s;if(!or[0]||!or[1]||!((n=or[0])==null?void 0:n.inputs[0].shape)||!((s=or[1])==null?void 0:s.inputs[0].shape))return[];ds=[e.shape[2]||0,e.shape[1]||0],N0++;let r=(t.hand.skipTime||0)>oe()-qb,a=N0<(t.hand.skipFrames||0);return t.skipAllowed&&r&&a?jt.hands:new Promise(async i=>{let o=3*(t.hand.skipTime||0)>oe()-qb,l=N0<3*(t.hand.skipFrames||0);t.skipAllowed&&jt.hands.length===t.hand.maxDetected?jt.hands=await Promise.all(jt.boxes.map(u=>Kb(e,u,t))):t.skipAllowed&&o&&l&&jt.hands.length>0?jt.hands=await Promise.all(jt.boxes.map(u=>Kb(e,u,t))):(jt.boxes=await y2e(e,t),qb=oe(),jt.hands=await Promise.all(jt.boxes.map(u=>Kb(e,u,t))),N0=0);let d=[...jt.boxes];if(jt.boxes.length=0,t.cacheSensitivity>0)for(let u=0;u<jt.hands.length;u++){let p=rC(jt.hands[u].keypoints,ds);if(p.box[2]/(e.shape[2]||1)>.05&&p.box[3]/(e.shape[1]||1)>.05&&jt.hands[u].fingerScore&&jt.hands[u].fingerScore>(t.hand.minConfidence||0)){let h=y0(p.box,iN),c=y0(p.boxRaw,iN);jt.boxes.push({...d[u],box:h,boxRaw:c})}}for(let u=0;u<jt.hands.length;u++){let p=ns(jt.hands[u].keypoints,ds);jt.hands[u].box=p.box,jt.hands[u].boxRaw=p.boxRaw}i(jt.hands)})}var Er,R0=[],Zb=Number.MAX_SAFE_INTEGER,pN=0,hN=0;async function cN(e){var t;return ce.initial&&(Er=null),Er?e.debug&&se("cached model:",Er.modelUrl):Er=await Ue((t=e.face.liveness)==null?void 0:t.modelPath),Er}async function Yb(e,t,r,a){var i,o;if(!Er)return 0;let n=(((i=t.face.liveness)==null?void 0:i.skipTime)||0)>oe()-hN,s=Zb<(((o=t.face.liveness)==null?void 0:o.skipFrames)||0);return t.skipAllowed&&n&&s&&pN===a&&R0[r]?(Zb++,R0[r]):(Zb=0,new Promise(async l=>{let d=Ie.resizeBilinear(e,[(Er==null?void 0:Er.inputs[0].shape)?Er.inputs[0].shape[2]:0,(Er==null?void 0:Er.inputs[0].shape)?Er.inputs[0].shape[1]:0],!1),u=Er==null?void 0:Er.execute(d),p=(await u.data())[0];R0[r]=Math.round(100*p)/100,pN=a,hN=oe(),re([d,u]),l(R0[r])}))}var Gh={};Qd(Gh,{connected:()=>M0,horizontal:()=>Jb,kpt:()=>F0,relative:()=>e5,vertical:()=>Qb});var F0=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],Jb=[["leftEye","rightEye"],["leftEar","rightEar"],["leftShoulder","rightShoulder"],["leftElbow","rightElbow"],["leftWrist","rightWrist"],["leftHip","rightHip"],["leftKnee","rightKnee"],["leftAnkle","rightAnkle"]],Qb=[["leftKnee","leftShoulder"],["rightKnee","rightShoulder"],["leftAnkle","leftKnee"],["rightAnkle","rightKnee"]],e5=[[["leftHip","rightHip"],["leftShoulder","rightShoulder"]],[["leftElbow","rightElbow"],["leftShoulder","rightShoulder"]]],M0={leftLeg:["leftHip","leftKnee","leftAnkle"],rightLeg:["rightHip","rightKnee","rightAnkle"],torso:["leftShoulder","rightShoulder","rightHip","leftHip","leftShoulder"],leftArm:["leftShoulder","leftElbow","leftWrist"],rightArm:["rightShoulder","rightElbow","rightWrist"],head:[]};var mN=.005,xa={keypoints:[],padding:[[0,0],[0,0],[0,0],[0,0]]};function t5(e){for(let t of Jb){let r=e.keypoints.findIndex(n=>n.part===t[0]),a=e.keypoints.findIndex(n=>n.part===t[1]);if(e.keypoints[r]&&e.keypoints[a]&&e.keypoints[r].position[0]<e.keypoints[a].position[0]){let n=e.keypoints[r];e.keypoints[r]=e.keypoints[a],e.keypoints[a]=n}}for(let t of Qb){let r=e.keypoints.findIndex(n=>n&&n.part===t[0]),a=e.keypoints.findIndex(n=>n&&n.part===t[1]);e.keypoints[r]&&e.keypoints[a]&&e.keypoints[r].position[1]<e.keypoints[a].position[1]&&e.keypoints.splice(r,1)}for(let[t,r]of e5){let a=e.keypoints.findIndex(d=>d&&d.part===t[0]),n=e.keypoints.findIndex(d=>d&&d.part===t[1]),s=e.keypoints.findIndex(d=>d&&d.part===r[0]),i=e.keypoints.findIndex(d=>d&&d.part===r[1]);if(!e.keypoints[s]||!e.keypoints[i])continue;let o=e.keypoints[a]?[Math.abs(e.keypoints[s].position[0]-e.keypoints[a].position[0]),Math.abs(e.keypoints[i].position[0]-e.keypoints[a].position[0])]:[0,0],l=e.keypoints[n]?[Math.abs(e.keypoints[i].position[0]-e.keypoints[n].position[0]),Math.abs(e.keypoints[s].position[0]-e.keypoints[n].position[0])]:[0,0];if(o[0]>o[1]||l[0]>l[1]){let d=e.keypoints[a];e.keypoints[a]=e.keypoints[n],e.keypoints[n]=d}}}function gN(e){for(let t=0;t<e.length;t++)if(e[t]&&xa.keypoints[t]){let r=[Math.abs(e[t].positionRaw[0]-xa.keypoints[t].positionRaw[0]),Math.abs(e[t].positionRaw[1]-xa.keypoints[t].positionRaw[1])];r[0]<mN&&r[1]<mN?e[t]=xa.keypoints[t]:xa.keypoints[t]=e[t]}else xa.keypoints[t]=e[t];return e}function yN(e,t){let r={};if(!e.shape||!e.shape[1]||!e.shape[2])return e;xa.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]],r.pad=ja(e,xa.padding),r.resize=Ie.resizeBilinear(r.pad,[t,t]);let a=me(r.resize,"int32");return Object.keys(r).forEach(n=>re(r[n])),a}function AN(e,t){e.keypoints=e.keypoints.filter(a=>a&&a.position);for(let a of e.keypoints)a.position=[a.position[0]*(t[0]+xa.padding[2][0]+xa.padding[2][1])/t[0]-xa.padding[2][0],a.position[1]*(t[1]+xa.padding[1][0]+xa.padding[1][1])/t[1]-xa.padding[1][0]],a.positionRaw=[a.position[0]/t[0],a.position[1]/t[1]];let r=ns(e.keypoints.map(a=>a.position),t);return e.box=r.box,e.boxRaw=r.boxRaw,e}var ba,$0=0,r5=Number.MAX_SAFE_INTEGER,zl={boxes:[],bodies:[],last:0};async function xN(e){return ce.initial&&(ba=null),ba?e.debug&&se("cached model:",ba.modelUrl):(E0(["size"],e),ba=await Ue(e.body.modelPath)),$0=ba.inputs[0].shape?ba.inputs[0].shape[2]:0,$0<64&&($0=256),ba}async function x2e(e,t,r){let a=e[0][0],n=[],s=0;for(let u=0;u<a.length;u++)if(s=a[u][2],s>t.body.minConfidence){let p=[a[u][1],a[u][0]];n.push({score:Math.round(100*s)/100,part:F0[u],positionRaw:p,position:[Math.round((r.shape[2]||0)*p[0]),Math.round((r.shape[1]||0)*p[1])]})}s=n.reduce((u,p)=>p.score>u?p.score:u,0);let i=[],o=ns(n.map(u=>u.position),[r.shape[2],r.shape[1]]),l={};for(let[u,p]of Object.entries(M0)){let h=[];for(let c=0;c<p.length-1;c++){let f=n.find(g=>g.part===p[c]),m=n.find(g=>g.part===p[c+1]);f&&m&&f.score>(t.body.minConfidence||0)&&m.score>(t.body.minConfidence||0)&&h.push([f.position,m.position])}l[u]=h}let d={id:0,score:s,box:o.box,boxRaw:o.boxRaw,keypoints:n,annotations:l};return t5(d),i.push(d),i}async function b2e(e,t,r){let a=[];for(let n=0;n<e[0].length;n++){let s=e[0][n],i=Math.round(100*s[51+4])/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 c=[s[3*p+1],s[3*p+0]];o.push({part:F0[p],score:Math.round(100*h)/100,positionRaw:c,position:[Math.round((r.shape[2]||0)*c[0]),Math.round((r.shape[1]||0)*c[1])]})}}let l=ns(o.map(p=>p.position),[r.shape[2],r.shape[1]]),d={};for(let[p,h]of Object.entries(M0)){let c=[];for(let f=0;f<h.length-1;f++){let m=o.find(y=>y.part===h[f]),g=o.find(y=>y.part===h[f+1]);m&&g&&m.score>(t.body.minConfidence||0)&&g.score>(t.body.minConfidence||0)&&c.push([m.position,g.position])}d[p]=c}let u={id:n,score:i,box:l.box,boxRaw:l.boxRaw,keypoints:[...o],annotations:d};t5(u),a.push(u)}}return a.sort((n,s)=>s.score-n.score),a.length>t.body.maxDetected&&(a.length=t.body.maxDetected),a}async function a5(e,t){if(!ba||!(ba==null?void 0:ba.inputs[0].shape))return[];t.skipAllowed||(zl.boxes.length=0),r5++;let r=(t.body.skipTime||0)>oe()-zl.last,a=r5<(t.body.skipFrames||0);return t.skipAllowed&&r&&a?zl.bodies:new Promise(async n=>{let s={};r5=0,s.input=yN(e,$0),s.res=ba==null?void 0:ba.execute(s.input),zl.last=oe();let i=await s.res.array();zl.bodies=s.res.shape[2]===17?await x2e(i,t,e):await b2e(i,t,e);for(let o of zl.bodies)AN(o,[e.shape[2]||1,e.shape[1]||1]),gN(o.keypoints);Object.keys(s).forEach(o=>re(s[o])),n(zl.bodies)})}var Od,P0=[],vN=0,n5=Number.MAX_SAFE_INTEGER,z0=0,O0=2.5;async function wN(e){if(!Od||ce.initial){Od=await Ue(e.object.modelPath);let t=Object.values(Od.modelSignature.inputs);z0=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):0}else e.debug&&se("cached model:",Od.modelUrl);return Od}async function v2e(e,t,r){let a=0,n=[];for(let l of[1,2,4])q(async()=>{let d=l*13,u=Ye(e.find(m=>m.shape[1]===d**2&&(m.shape[2]||0)===Td.length)),p=Ye(e.find(m=>m.shape[1]===d**2&&(m.shape[2]||0)<Td.length)),c=await p.reshape([-1,4,p.shape[1]/4]).argMax(2).array(),f=await u.array();for(let m=0;m<u.shape[0];m++)for(let g=0;g<u.shape[1];g++){let y=f[m][g];if(y>(r.object.minConfidence||0)&&g!==61){let A=(.5+Math.trunc(m%d))/d,x=(.5+Math.trunc(m/d))/d,b=c[m].map(I=>I*(d/l/z0)),[v,C]=[A-O0/l*b[0],x-O0/l*b[1]],[T,E]=[A+O0/l*b[2]-v,x+O0/l*b[3]-C],R=[v,C,T,E];R=R.map(I=>Math.max(0,Math.min(I,1)));let z=[R[0]*t[0],R[1]*t[1],R[2]*t[0],R[3]*t[1]],M={id:a++,score:Math.round(100*y)/100,class:g+1,label:Td[g].label,box:z.map(I=>Math.trunc(I)),boxRaw:R};n.push(M)}}});e.forEach(l=>re(l));let s=n.map(l=>[l.boxRaw[1],l.boxRaw[0],l.boxRaw[3],l.boxRaw[2]]),i=n.map(l=>l.score),o=[];if(s&&s.length>0){let l=await Ie.nonMaxSuppressionAsync(s,i,r.object.maxDetected,r.object.iouThreshold,r.object.minConfidence);o=await l.data(),re(l)}return n=n.filter((l,d)=>o.includes(d)).sort((l,d)=>d.score-l.score),n}async function s5(e,t){let r=(t.object.skipTime||0)>oe()-vN,a=n5<(t.object.skipFrames||0);return t.skipAllowed&&r&&a&&P0.length>0?(n5++,P0):(n5=0,!ce.kernels.includes("mod")||!ce.kernels.includes("sparsetodense")?P0:new Promise(async n=>{let s=[e.shape[2]||0,e.shape[1]||0],i=Ie.resizeBilinear(e,[z0,z0],!1),o=pe(i,Xe.tf255),l=o.transpose([0,3,1,2]);re(o),re(i);let d;t.object.enabled&&(d=Od.execute(l)),vN=oe(),re(l);let u=await v2e(d,s,t);P0=u,n(u)}))}var Hh=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],w2e=Hh.length,jh=Hh.reduce((e,t,r)=>(e[t]=r,e),{}),k2e=[["leftHip","leftShoulder"],["leftElbow","leftShoulder"],["leftElbow","leftWrist"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["rightHip","rightShoulder"],["rightElbow","rightShoulder"],["rightElbow","rightWrist"],["rightHip","rightKnee"],["rightKnee","rightAnkle"],["leftShoulder","rightShoulder"],["leftHip","rightHip"]],Lxe=k2e.map(([e,t])=>[jh[e],jh[t]]),IN=[["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 SN(e){let t=e.reduce(({maxX:r,maxY:a,minX:n,minY:s},{position:{x:i,y:o}})=>({maxX:Math.max(r,i),maxY:Math.max(a,o),minX:Math.min(n,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 TN(e,[t,r],[a,n]){let s=t/a,i=r/n,o=(d,u)=>({id:u,score:d.score,boxRaw:[d.box[0]/n,d.box[1]/a,d.box[2]/n,d.box[3]/a],box:[Math.trunc(d.box[0]*i),Math.trunc(d.box[1]*s),Math.trunc(d.box[2]*i),Math.trunc(d.box[3]*s)],keypoints:d.keypoints.map(({score:p,part:h,position:c})=>({score:p,part:h,position:[Math.trunc(c.x*i),Math.trunc(c.y*s)],positionRaw:[c.x/a,c.y/a]})),annotations:{}});return e.map((d,u)=>o(d,u))}var i5=class{constructor(t,r){fe(this,"priorityQueue");fe(this,"numberOfElements");fe(this,"getElementValue");this.priorityQueue=new Array(t),this.numberOfElements=-1,this.getElementValue=r}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 r=2*t;if(r<this.numberOfElements&&this.less(r,r+1)&&r++,!this.less(t,r))break;this.exchange(t,r),t=r}}getValueAt(t){return this.getElementValue(this.priorityQueue[t])}less(t,r){return this.getValueAt(t)<this.getValueAt(r)}exchange(t,r){let a=this.priorityQueue[t];this.priorityQueue[t]=this.priorityQueue[r],this.priorityQueue[r]=a}};function o5(e,t,r,a){return{y:a.get(e,t,r),x:a.get(e,t,r+w2e)}}function l5(e,t,r){let{heatmapY:a,heatmapX:n,id:s}=e,{y:i,x:o}=o5(a,n,s,r);return{x:e.heatmapX*t+o,y:e.heatmapY*t+i}}function u5(e,t,r){return e<t?t:e>r?r:e}function CN(e,t,r,a){let n=r-e,s=a-t;return n*n+s*s}function d5(e,t){return{x:e.x+t.x,y:e.y+t.y}}var An,S2e=["MobilenetV1/offset_2/BiasAdd","MobilenetV1/heatmap_2/BiasAdd","MobilenetV1/displacement_fwd_2/BiasAdd","MobilenetV1/displacement_bwd_2/BiasAdd"],D0=1,zd=16,T2e=50**2;function NN(e,t,r,a,n,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,A,x)=>({y:u5(Math.round(y.y/zd),0,A-1),x:u5(Math.round(y.x/zd),0,x-1)}),[d,u]=a.shape,p=l(t.position,d,u),h=o(p),f=d5(t.position,h);for(let y=0;y<i;y++){let A=l(f,d,u),x=o5(A.y,A.x,r,n);f=d5({x:A.x*zd,y:A.y*zd},{x:x.x,y:x.y})}let m=l(f,d,u),g=a.get(m.y,m.x,r);return{position:f,part:Hh[r],score:g}}function C2e(e,t,r,a,n){let s=IN.map(([h,c])=>[jh[h],jh[c]]),i=s.map(([,h])=>h),o=s.map(([h])=>h),l=t.shape[2],d=i.length,u=new Array(l),p=l5(e.part,zd,r);u[e.part.id]={score:e.score,part:Hh[e.part.id],position:p};for(let h=d-1;h>=0;--h){let c=i[h],f=o[h];u[c]&&!u[f]&&(u[f]=NN(h,u[c],f,t,r,n))}for(let h=0;h<d;++h){let c=o[h],f=i[h];u[c]&&!u[f]&&(u[f]=NN(h,u[c],f,t,r,a))}return u}function N2e(e,t,r,a,n){let[s,i]=n.shape,o=!0,l=Math.max(r-D0,0),d=Math.min(r+D0+1,s);for(let u=l;u<d;++u){let p=Math.max(a-D0,0),h=Math.min(a+D0+1,i);for(let c=p;c<h;++c)if(n.get(u,c,e)>t){o=!1;break}if(!o)break}return o}function E2e(e,t){let[r,a,n]=t.shape,s=new i5(r*a*n,({score:i})=>i);for(let i=0;i<r;++i)for(let o=0;o<a;++o)for(let l=0;l<n;++l){let d=t.get(i,o,l);d<e||N2e(l,d,i,o,t)&&s.enqueue({score:d,part:{heatmapY:i,heatmapX:o,id:l}})}return s}function EN(e,{x:t,y:r},a){return e.some(({keypoints:n})=>{var i;let s=(i=n[a])==null?void 0:i.position;return s?CN(r,t,s.y,s.x)<=T2e:!1})}function R2e(e,t){return t.reduce((a,{position:n,score:s},i)=>(EN(e,n,i)||(a+=s),a),0)/t.length}function F2e(e,t,r,a,n,s){let i=[],o=E2e(s,t);for(;i.length<n&&!o.empty();){let l=o.dequeue(),d=l5(l.part,zd,e);if(EN(i,d,l.part.id))continue;let u=C2e(l,t,e,r,a);u=u.filter(c=>c.score>s);let p=R2e(i,u),h=SN(u);p>s&&i.push({keypoints:u,box:h,score:Math.round(100*p)/100})}return i}async function p5(e,t){let r=q(()=>{if(!An.inputs[0].shape)return[];let i=Ie.resizeBilinear(e,[An.inputs[0].shape[2],An.inputs[0].shape[1]]),o=he(pe(me(i,"float32"),127.5),1),d=An.execute(o,S2e).map(u=>Ye(u,[0]));return d[1]=Sr(d[1]),d}),a=await Promise.all(r.map(i=>i.buffer()));for(let i of r)re(i);let n=await F2e(a[0],a[1],a[2],a[3],t.body.maxDetected,t.body.minConfidence);return An.inputs[0].shape?TN(n,[e.shape[1],e.shape[2]],[An.inputs[0].shape[2],An.inputs[0].shape[1]]):[]}async function RN(e){return!An||ce.initial?An=await Ue(e.body.modelPath):e.debug&&se("cached model:",An.modelUrl),An}var On,h5=!1;async function c5(e){return!On||ce.initial?On=await Ue(e.segmentation.modelPath):e.debug&&se("cached model:",On.modelUrl),On}async function MN(e,t,r){var m,g;if(h5)return{data:[],canvas:null,alpha:null};h5=!0,On||await c5(r);let a=await kd(e,r),n=((m=a.tensor)==null?void 0:m.shape[2])||0,s=((g=a.tensor)==null?void 0:g.shape[1])||0;if(!a.tensor)return{data:[],canvas:null,alpha:null};let i={};i.resize=Ie.resizeBilinear(a.tensor,[On.inputs[0].shape?On.inputs[0].shape[1]:0,On.inputs[0].shape?On.inputs[0].shape[2]:0],!1),re(a.tensor),i.norm=pe(i.resize,Xe.tf255),i.res=On.execute(i.norm),i.squeeze=Ye(i.res,0),i.squeeze.shape[2]===2?(i.softmax=sd(i.squeeze),[i.bg,i.fg]=ra(i.softmax,2),i.expand=Ht(i.fg,2),i.pad=Ht(i.expand,0),i.crop=Ie.cropAndResize(i.pad,[[0,0,.5,.5]],[0],[n,s]),i.data=Ye(i.crop,0)):i.data=Ie.resizeBilinear(i.squeeze,[s,n]);let o=Array.from(await i.data.data());if(ce.node&&!ce.Canvas&&typeof ImageData=="undefined")return r.debug&&se("canvas support missing"),Object.keys(i).forEach(y=>re(i[y])),{data:o,canvas:null,alpha:null};let l=Ur(n,s);$a&&await $a.toPixels(i.data,l);let d=l.getContext("2d");r.segmentation.blur&&r.segmentation.blur>0&&(d.filter=`blur(${r.segmentation.blur}px)`);let u=d.getImageData(0,0,n,s),p=Ur(n,s),h=p.getContext("2d");a.canvas&&h.drawImage(a.canvas,0,0),h.globalCompositeOperation="darken",r.segmentation.blur&&r.segmentation.blur>0&&(h.filter=`blur(${r.segmentation.blur}px)`),h.drawImage(l,0,0),h.globalCompositeOperation="source-over",h.filter="none";let c=h.getImageData(0,0,n,s);for(let y=0;y<n*s;y++)c.data[4*y+3]=u.data[4*y+0];h.putImageData(c,0,0);let f=null;if(t&&p){f=Ur(n,s);let y=await kd(t,r);re(y.tensor);let A=f.getContext("2d");A.drawImage(y.canvas,0,0,f.width,f.height),A.drawImage(p,0,0)}return Object.keys(i).forEach(y=>re(i[y])),h5=!1,{data:o,canvas:p,alpha:l}}var f5=class{constructor(){fe(this,"ssrnetage",null);fe(this,"gear",null);fe(this,"blazeposedetect",null);fe(this,"blazepose",null);fe(this,"centernet",null);fe(this,"efficientpose",null);fe(this,"mobilefacenet",null);fe(this,"emotion",null);fe(this,"facedetect",null);fe(this,"faceiris",null);fe(this,"facemesh",null);fe(this,"faceres",null);fe(this,"ssrnetgender",null);fe(this,"handpose",null);fe(this,"handskeleton",null);fe(this,"handtrack",null);fe(this,"liveness",null);fe(this,"movenet",null);fe(this,"nanodet",null);fe(this,"posenet",null);fe(this,"segmentation",null);fe(this,"antispoof",null)}};function m5(e){for(let t of Object.keys(e.models))e.models[t]=null}async function PN(e){var t,r,a,n,s,i,o,l,d,u,p,h,c,f,m,g,y,A,x,b,v,C,T,E,R,z,M,I,D,O;ce.initial&&m5(e),e.config.hand.enabled&&(!e.models.handpose&&((r=(t=e.config.hand.detector)==null?void 0:t.modelPath)==null?void 0:r.includes("handdetect"))&&([e.models.handpose,e.models.handskeleton]=await Hb(e.config)),!e.models.handskeleton&&e.config.hand.landmarks&&((n=(a=e.config.hand.detector)==null?void 0:a.modelPath)==null?void 0:n.includes("handdetect"))&&([e.models.handpose,e.models.handskeleton]=await Hb(e.config))),e.config.body.enabled&&!e.models.blazepose&&((i=(s=e.config.body)==null?void 0:s.modelPath)==null?void 0:i.includes("blazepose"))&&(e.models.blazepose=oC(e.config)),e.config.body.enabled&&!e.models.blazeposedetect&&e.config.body.detector&&e.config.body.detector.modelPath&&(e.models.blazeposedetect=iC(e.config)),e.config.body.enabled&&!e.models.efficientpose&&((l=(o=e.config.body)==null?void 0:o.modelPath)==null?void 0:l.includes("efficientpose"))&&(e.models.efficientpose=cC(e.config)),e.config.body.enabled&&!e.models.movenet&&((u=(d=e.config.body)==null?void 0:d.modelPath)==null?void 0:u.includes("movenet"))&&(e.models.movenet=xN(e.config)),e.config.body.enabled&&!e.models.posenet&&((h=(p=e.config.body)==null?void 0:p.modelPath)==null?void 0:h.includes("posenet"))&&(e.models.posenet=RN(e.config)),e.config.face.enabled&&!e.models.facedetect&&(e.models.facedetect=YT(e.config)),e.config.face.enabled&&((c=e.config.face.antispoof)==null?void 0:c.enabled)&&!e.models.antispoof&&(e.models.antispoof=_T(e.config)),e.config.face.enabled&&((f=e.config.face.liveness)==null?void 0:f.enabled)&&!e.models.liveness&&(e.models.liveness=cN(e.config)),e.config.face.enabled&&((m=e.config.face.description)==null?void 0:m.enabled)&&!e.models.faceres&&(e.models.faceres=zC(e.config)),e.config.face.enabled&&((g=e.config.face.emotion)==null?void 0:g.enabled)&&!e.models.emotion&&(e.models.emotion=yC(e.config)),e.config.face.enabled&&((y=e.config.face.iris)==null?void 0:y.enabled)&&!e.models.faceiris&&(e.models.faceiris=CC(e.config)),e.config.face.enabled&&((A=e.config.face.mesh)==null?void 0:A.enabled)&&!e.models.facemesh&&(e.models.facemesh=FC(e.config)),e.config.face.enabled&&((x=e.config.face.gear)==null?void 0:x.enabled)&&!e.models.gear&&(e.models.gear=ST(e.config)),e.config.face.enabled&&((b=e.config.face.ssrnet)==null?void 0:b.enabled)&&!e.models.ssrnetage&&(e.models.ssrnetage=RT(e.config)),e.config.face.enabled&&((v=e.config.face.ssrnet)==null?void 0:v.enabled)&&!e.models.ssrnetgender&&(e.models.ssrnetgender=PT(e.config)),e.config.face.enabled&&((C=e.config.face.mobilefacenet)==null?void 0:C.enabled)&&!e.models.mobilefacenet&&(e.models.mobilefacenet=wC(e.config)),e.config.hand.enabled&&!e.models.handtrack&&((E=(T=e.config.hand.detector)==null?void 0:T.modelPath)==null?void 0:E.includes("handtrack"))&&(e.models.handtrack=lN(e.config)),e.config.hand.enabled&&e.config.hand.landmarks&&!e.models.handskeleton&&((z=(R=e.config.hand.detector)==null?void 0:R.modelPath)==null?void 0:z.includes("handtrack"))&&(e.models.handskeleton=uN(e.config)),e.config.object.enabled&&!e.models.centernet&&((I=(M=e.config.object)==null?void 0:M.modelPath)==null?void 0:I.includes("centernet"))&&(e.models.centernet=dC(e.config)),e.config.object.enabled&&!e.models.nanodet&&((O=(D=e.config.object)==null?void 0:D.modelPath)==null?void 0:O.includes("nanodet"))&&(e.models.nanodet=wN(e.config)),e.config.segmentation.enabled&&!e.models.segmentation&&(e.models.segmentation=c5(e.config));for await(let j of Object.keys(e.models))e.models[j]&&typeof e.models[j]!="undefined"&&(e.models[j]=await e.models[j])}async function ON(e){let t=["const","placeholder","noop","pad","squeeze","add","sub","mul","div"];for(let r of Object.keys(e.models)){let a=e.models[r];if(!a)continue;let n=[],s=a==null?void 0:a.executor;if(s&&s.graph.nodes)for(let o of Object.values(s.graph.nodes)){let l=o.op.toLowerCase();n.includes(l)||n.push(l)}else!s&&e.config.debug&&se("model signature not determined:",r);let i=[];for(let o of n)!t.includes(o)&&!e.env.kernels.includes(o)&&!e.env.kernels.includes(o.replace("_",""))&&!e.env.kernels.includes(o.replace("native",""))&&!e.env.kernels.includes(o.replace("v2",""))&&i.push(o);e.config.debug&&i.length>0&&se("model validation failed:",r,i)}}var Nt={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 M2e(){let e=Nt.gl;!e||(Nt.extensions=e.getSupportedExtensions())}async function DN(e){var t;if(e.config.backend==="humangl"&&(Nt.name in kr().registry&&(!Nt.gl||!Nt.gl.getParameter(Nt.gl.VERSION))&&(se("error: humangl backend invalid context"),m5(e)),!e2(Nt.name))){try{Nt.canvas=await Ur(100,100)}catch(a){se("error: cannot create canvas:",a);return}try{if(Nt.gl=(t=Nt.canvas)==null?void 0:t.getContext("webgl2",Nt.webGLattr),!Nt.gl.getParameter(Nt.gl.VERSION).includes("2.0")){se("override: using fallback webgl backend as webgl 2.0 is not detected"),e.config.backend="webgl";return}Nt.canvas&&(Nt.canvas.addEventListener("webglcontextlost",async n=>{throw se("error: humangl:",n.type),se("possible browser memory leak using webgl or conflict with multiple backend registrations"),e.emit("error"),new Error("backend error: webgl context lost")}),Nt.canvas.addEventListener("webglcontextrestored",n=>{se("error: humangl context restored:",n)}),Nt.canvas.addEventListener("webglcontextcreationerror",n=>{se("error: humangl context create:",n)}))}catch(a){se("error: cannot get WebGL context:",a);return}try{Zm(2,Nt.gl)}catch(a){se("error: cannot set WebGL context:",a);return}try{let a=new uu(Nt.gl);Al(Nt.name,()=>new Nh(a),Nt.priority)}catch(a){se("error: cannot register WebGL backend:",a);return}try{Tn("webgl").forEach(n=>{let s={...n,backendName:Nt.name};Ga(s)})}catch(a){se("error: cannot update WebGL backend registration:",a);return}let r=cn().getGPGPUContext?cn().getGPGPUContext().gl:null;if(r)se(`humangl webgl version:${r.getParameter(r.VERSION)} renderer:${r.getParameter(r.RENDERER)}`);else{se("error: no current gl context:",r,Nt.gl);return}try{hn.set("WEBGL_VERSION",2)}catch(a){se("error: cannot set WebGL backend flags:",a);return}M2e(),se("backend registered:",Nt.name)}}function $2e(){if(!ce.kernels.includes("mod")){let e={kernelName:"Mod",backendName:ca(),kernelFunc:t=>q(()=>he(t.inputs.a,L(pe(t.inputs.a,t.inputs.b),t.inputs.b)))};Ga(e),ce.kernels.push("mod")}if(!ce.kernels.includes("floormod")){let e={kernelName:"FloorMod",backendName:ca(),kernelFunc:t=>q(()=>ih(t.inputs.a/t.inputs.b)*t.inputs.b+ad(t.inputs.a,t.inputs.b))};Ga(e),ce.kernels.push("floormod")}}async function _0(e,t=!1){if(e.state="backend",t||ce.initial||e.config.backend&&e.config.backend.length>0&&ca()!==e.config.backend){let r=oe();if(e.config.backend&&e.config.backend.length>0){if(typeof window=="undefined"&&typeof WorkerGlobalScope!="undefined"&&e.config.debug&&e.config.debug&&se("running inside web worker"),ce.browser&&e.config.backend==="tensorflow"&&(e.config.debug&&se("override: backend set to tensorflow while running in browser"),e.config.backend="humangl"),ce.node&&(e.config.backend==="webgl"||e.config.backend==="humangl")&&(e.config.debug&&se(`override: backend set to ${e.config.backend} while running in nodejs`),e.config.backend="tensorflow"),ce.browser&&e.config.backend==="webgpu")if(typeof navigator=="undefined"||typeof navigator.gpu=="undefined")se("override: backend set to webgpu but browser does not support webgpu"),e.config.backend="humangl";else{let n=await navigator.gpu.requestAdapter();e.config.debug&&se("enumerated webgpu adapter:",n)}e.config.backend==="humangl"&&await DN(e);let a=Object.keys(kr().registryFactory);if(e.config.debug&&se("available backends:",a),a.includes(e.config.backend)||(se(`error: backend ${e.config.backend} not found in registry`),e.config.backend=ce.node?"tensorflow":"webgl",e.config.debug&&se(`override: setting backend ${e.config.backend}`)),e.config.debug&&se("setting backend:",e.config.backend),e.config.backend==="wasm"){if(e.config.debug&&se("wasm path:",e.config.wasmPath),typeof(We==null?void 0:We.setWasmPaths)!="undefined")await Xx(e.config.wasmPath,e.config.wasmPlatformFetch);else throw new Error("backend error: attempting to use wasm backend but wasm path is not set");let n=await Y().getAsync("WASM_HAS_SIMD_SUPPORT"),s=await Y().getAsync("WASM_HAS_MULTITHREAD_SUPPORT");e.config.debug&&se(`wasm execution: ${n?"SIMD":"no SIMD"} ${s?"multithreaded":"singlethreaded"}`),e.config.debug&&!n&&se("warning: wasm simd support is not enabled")}try{await Qy(e.config.backend),await Qu(),CT()}catch(n){return se("error: cannot set backend:",e.config.backend,n),!1}}if(ca()==="humangl"&&(hn.set("CHECK_COMPUTATION_FOR_ERRORS",!1),hn.set("WEBGL_CPU_FORWARD",!0),hn.set("WEBGL_USE_SHAPES_UNIFORMS",!0),hn.set("CPU_HANDOFF_SIZE_THRESHOLD",256),typeof e.config.deallocate!="undefined"&&e.config.deallocate&&(se("changing webgl: WEBGL_DELETE_TEXTURE_THRESHOLD:",!0),hn.set("WEBGL_DELETE_TEXTURE_THRESHOLD",0)),cn().getGPGPUContext)){let a=await cn().getGPGPUContext().gl;e.config.debug&&se(`gl version:${a.getParameter(a.VERSION)} renderer:${a.getParameter(a.RENDERER)}`)}ca()==="webgpu",Yy(),await Qu(),e.performance.initBackend=Math.trunc(oe()-r),e.config.backend=ca(),await ce.updateBackend(),$2e()}return!0}function E0(e,t){for(let r of e){let a={kernelName:r,backendName:t.backend,kernelFunc:()=>{t.debug&&se("kernelFunc",r,t.backend)}};Ga(a)}ce.kernels=Tn(ca()).map(r=>r.kernelName.toLowerCase())}var ps={color:"rgba(173, 216, 230, 0.6)",labelColor:"rgba(173, 216, 230, 1)",shadowColor:"black",font:'small-caps 16px "Segoe UI"',lineHeight:18,lineWidth:4,pointSize:2,roundRect:8,drawPoints:!1,drawLabels:!0,drawBoxes:!0,drawGestures:!0,drawPolygons:!0,drawGaze:!0,fillPolygons:!1,useDepth:!0,useCurves:!1},g5=0,Dl=e=>{if(!e)se("draw error: invalid canvas");else if(!e.getContext)se("draw error: canvas context not defined");else{let t=e.getContext("2d");if(!t)se("draw error: cannot get canvas context");else return t}return null},Dd=e=>Math.round(e*180/Math.PI);function y5(e,t,r,a,n){a=a||0,e.fillStyle=n.useDepth&&a?`rgba(${127.5+2*a}, ${127.5-2*a}, 255, 0.3)`:n.color,e.beginPath(),e.arc(t,r,n.pointSize,0,2*Math.PI),e.fill()}function qh(e,t,r,a,n,s){if(e.beginPath(),e.lineWidth=s.lineWidth,s.useCurves){let i=(t+t+a)/2,o=(r+r+n)/2;e.ellipse(i,o,a/2,n/2,0,0,2*Math.PI)}else e.moveTo(t+s.roundRect,r),e.lineTo(t+a-s.roundRect,r),e.quadraticCurveTo(t+a,r,t+a,r+s.roundRect),e.lineTo(t+a,r+n-s.roundRect),e.quadraticCurveTo(t+a,r+n,t+a-s.roundRect,r+n),e.lineTo(t+s.roundRect,r+n),e.quadraticCurveTo(t,r+n,t,r+n-s.roundRect),e.lineTo(t,r+s.roundRect),e.quadraticCurveTo(t,r,t+s.roundRect,r),e.closePath();e.stroke()}function BN(e,t,r){if(!(t.length<2)){e.beginPath(),e.moveTo(t[0][0],t[0][1]);for(let a of t){let n=a[2]||0;e.strokeStyle=r.useDepth&&n!==0?`rgba(${127.5+2*n}, ${127.5-2*n}, 255, 0.3)`:r.color,e.fillStyle=r.useDepth&&n!==0?`rgba(${127.5+2*n}, ${127.5-2*n}, 255, 0.3)`:r.color,e.lineTo(a[0],Math.round(a[1]))}e.stroke(),r.fillPolygons&&(e.closePath(),e.fill())}}function O2e(e,t,r){if(!(t.length<2)){if(e.lineWidth=r.lineWidth,!r.useCurves||t.length<=2){BN(e,t,r);return}e.moveTo(t[0][0],t[0][1]);for(let a=0;a<t.length-2;a++){let n=(t[a][0]+t[a+1][0])/2,s=(t[a][1]+t[a+1][1])/2;e.quadraticCurveTo(t[a][0],t[a][1],n,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(),r.fillPolygons&&(e.closePath(),e.fill())}}function LN(e,t,r,a=5){let n,s,i;e.beginPath(),e.moveTo(t[0],t[1]),e.lineTo(r[0],r[1]),n=Math.atan2(r[1]-t[1],r[0]-t[0]),s=a*Math.cos(n)+r[0],i=a*Math.sin(n)+r[1],e.moveTo(s,i),n+=1/3*(2*Math.PI),s=a*Math.cos(n)+r[0],i=a*Math.sin(n)+r[1],e.lineTo(s,i),n+=1/3*(2*Math.PI),s=a*Math.cos(n)+r[0],i=a*Math.sin(n)+r[1],e.lineTo(s,i),e.closePath(),e.stroke(),e.fill()}async function A5(e,t,r){let a=vr(ps,r);if(!(!t||!e)&&a.drawGestures){let n=Dl(e);if(!n)return;n.font=a.font,n.fillStyle=a.color;let s=1;for(let i=0;i<t.length;i++){let o=[],l=[];if([o,l]=Object.entries(t[i]),l.length>1&&l[1].length>0){let d=o[1]>0?`#${o[1]}`:"",u=`${o[0]} ${d}: ${l[1]}`;a.shadowColor&&a.shadowColor!==""&&(n.fillStyle=a.shadowColor,n.fillText(u,8,2+s*a.lineHeight)),n.fillStyle=a.labelColor,n.fillText(u,6,0+s*a.lineHeight),s+=1}}}}async function x5(e,t,r){var s,i,o,l,d;let a=vr(ps,r);if(!t||!e)return;let n=Dl(e);if(!!n)for(let u of t){if(n.font=a.font,n.strokeStyle=a.color,n.fillStyle=a.color,a.drawBoxes&&qh(n,u.box[0],u.box[1],u.box[2],u.box[3],a),a.drawLabels){let p=[];if(p.push(`face: ${Math.trunc(100*u.score)}%`),u.genderScore&&p.push(`${u.gender||""} ${Math.trunc(100*u.genderScore)}%`),u.age&&p.push(`age: ${u.age||""}`),u.iris&&p.push(`distance: ${u.iris}`),u.real&&p.push(`real: ${Math.trunc(100*u.real)}%`),u.live&&p.push(`live: ${Math.trunc(100*u.live)}%`),u.emotion&&u.emotion.length>0){let h=u.emotion.map(c=>`${Math.trunc(100*c.score)}% ${c.emotion}`);h.length>3&&(h.length=3),p.push(h.join(" "))}u.rotation&&u.rotation.angle&&u.rotation.gaze&&(u.rotation.angle.roll&&p.push(`roll: ${Dd(u.rotation.angle.roll)}\xB0 yaw:${Dd(u.rotation.angle.yaw)}\xB0 pitch:${Dd(u.rotation.angle.pitch)}\xB0`),u.rotation.gaze.bearing&&p.push(`gaze: ${Dd(u.rotation.gaze.bearing)}\xB0`)),p.length===0&&p.push("face"),n.fillStyle=a.color;for(let h=p.length-1;h>=0;h--){let c=Math.max(u.box[0],0),f=h*a.lineHeight+u.box[1];a.shadowColor&&a.shadowColor!==""&&(n.fillStyle=a.shadowColor,n.fillText(p[h],c+5,f+16)),n.fillStyle=a.labelColor,n.fillText(p[h],c+4,f+15)}}if(n.lineWidth=2,u.mesh&&u.mesh.length>0){if(a.drawPoints)for(let p of u.mesh)y5(n,p[0],p[1],p[2],a);if(a.drawPolygons){if(u.mesh.length>450)for(let p=0;p<El.length/3;p++){let h=[El[p*3+0],El[p*3+1],El[p*3+2]].map(c=>u.mesh[c]);BN(n,h,a)}if(u.annotations&&u.annotations.leftEyeIris&&u.annotations.leftEyeIris[0]){n.strokeStyle=a.useDepth?"rgba(255, 200, 255, 0.3)":a.color,n.beginPath();let p=Math.abs(u.annotations.leftEyeIris[3][0]-u.annotations.leftEyeIris[1][0])/2,h=Math.abs(u.annotations.leftEyeIris[4][1]-u.annotations.leftEyeIris[2][1])/2;n.ellipse(u.annotations.leftEyeIris[0][0],u.annotations.leftEyeIris[0][1],p,h,0,0,2*Math.PI),n.stroke(),a.fillPolygons&&(n.fillStyle=a.useDepth?"rgba(255, 255, 200, 0.3)":a.color,n.fill())}if(u.annotations&&u.annotations.rightEyeIris&&u.annotations.rightEyeIris[0]){n.strokeStyle=a.useDepth?"rgba(255, 200, 255, 0.3)":a.color,n.beginPath();let p=Math.abs(u.annotations.rightEyeIris[3][0]-u.annotations.rightEyeIris[1][0])/2,h=Math.abs(u.annotations.rightEyeIris[4][1]-u.annotations.rightEyeIris[2][1])/2;n.ellipse(u.annotations.rightEyeIris[0][0],u.annotations.rightEyeIris[0][1],p,h,0,0,2*Math.PI),n.stroke(),a.fillPolygons&&(n.fillStyle=a.useDepth?"rgba(255, 255, 200, 0.3)":a.color,n.fill())}if(a.drawGaze&&((s=u.rotation)==null?void 0:s.angle)&&typeof Path2D!="undefined"){n.strokeStyle="pink";let p=u.box[0]+u.box[2]/2-u.box[3]*Dd(u.rotation.angle.yaw)/90,h=u.box[1]+u.box[3]/2+u.box[2]*Dd(u.rotation.angle.pitch)/90,c=new Path2D(`
|
|
M ${u.box[0]+u.box[2]/2} ${u.box[1]}
|
|
C
|
|
${p} ${u.box[1]},
|
|
${p} ${u.box[1]+u.box[3]},
|
|
${u.box[0]+u.box[2]/2} ${u.box[1]+u.box[3]}
|
|
`),f=new Path2D(`
|
|
M ${u.box[0]} ${u.box[1]+u.box[3]/2}
|
|
C
|
|
${u.box[0]} ${h},
|
|
${u.box[0]+u.box[2]} ${h},
|
|
${u.box[0]+u.box[2]} ${u.box[1]+u.box[3]/2}
|
|
`);n.stroke(f),n.stroke(c)}if(a.drawGaze&&((o=(i=u.rotation)==null?void 0:i.gaze)==null?void 0:o.strength)&&((d=(l=u.rotation)==null?void 0:l.gaze)==null?void 0:d.bearing)&&u.annotations.leftEyeIris&&u.annotations.rightEyeIris&&u.annotations.leftEyeIris[0]&&u.annotations.rightEyeIris[0]){n.strokeStyle="pink",n.fillStyle="pink";let p=[u.annotations.leftEyeIris[0][0]+Math.sin(u.rotation.gaze.bearing)*u.rotation.gaze.strength*u.box[3],u.annotations.leftEyeIris[0][1]+Math.cos(u.rotation.gaze.bearing)*u.rotation.gaze.strength*u.box[2]];LN(n,[u.annotations.leftEyeIris[0][0],u.annotations.leftEyeIris[0][1]],[p[0],p[1]],4);let h=[u.annotations.rightEyeIris[0][0]+Math.sin(u.rotation.gaze.bearing)*u.rotation.gaze.strength*u.box[3],u.annotations.rightEyeIris[0][1]+Math.cos(u.rotation.gaze.bearing)*u.rotation.gaze.strength*u.box[2]];LN(n,[u.annotations.rightEyeIris[0][0],u.annotations.rightEyeIris[0][1]],[h[0],h[1]],4)}}}}}async function b5(e,t,r){var s;let a=vr(ps,r);if(!t||!e)return;let n=Dl(e);if(!!n){n.lineJoin="round";for(let i=0;i<t.length;i++){if(n.strokeStyle=a.color,n.fillStyle=a.color,n.lineWidth=a.lineWidth,n.font=a.font,a.drawBoxes&&t[i].box&&((s=t[i].box)==null?void 0:s.length)===4&&(qh(n,t[i].box[0],t[i].box[1],t[i].box[2],t[i].box[3],a),a.drawLabels&&(a.shadowColor&&a.shadowColor!==""&&(n.fillStyle=a.shadowColor,n.fillText(`body ${100*t[i].score}%`,t[i].box[0]+3,1+t[i].box[1]+a.lineHeight,t[i].box[2])),n.fillStyle=a.labelColor,n.fillText(`body ${100*t[i].score}%`,t[i].box[0]+2,0+t[i].box[1]+a.lineHeight,t[i].box[2]))),a.drawPoints&&t[i].keypoints)for(let o=0;o<t[i].keypoints.length;o++)!t[i].keypoints[o].score||t[i].keypoints[o].score===0||(n.fillStyle=a.useDepth&&t[i].keypoints[o].position[2]?`rgba(${127.5+2*(t[i].keypoints[o].position[2]||0)}, ${127.5-2*(t[i].keypoints[o].position[2]||0)}, 255, 0.5)`:a.color,y5(n,t[i].keypoints[o].position[0],t[i].keypoints[o].position[1],0,a));if(a.drawLabels&&t[i].keypoints){n.font=a.font;for(let o of t[i].keypoints)!o.score||o.score===0||(n.fillStyle=a.useDepth&&o.position[2]?`rgba(${127.5+2*o.position[2]}, ${127.5-2*o.position[2]}, 255, 0.5)`:a.color,n.fillText(`${o.part} ${Math.trunc(100*o.score)}%`,o.position[0]+4,o.position[1]+4))}if(a.drawPolygons&&t[i].keypoints&&t[i].annotations)for(let o of Object.values(t[i].annotations))for(let l of o)O2e(n,l,a)}}}async function v5(e,t,r){let a=vr(ps,r);if(!t||!e)return;let n=Dl(e);if(!!n){n.lineJoin="round",n.font=a.font;for(let s of t){if(a.drawBoxes&&(n.strokeStyle=a.color,n.fillStyle=a.color,qh(n,s.box[0],s.box[1],s.box[2],s.box[3],a),a.drawLabels&&(a.shadowColor&&a.shadowColor!==""&&(n.fillStyle=a.shadowColor,n.fillText(`hand:${Math.trunc(100*s.score)}%`,s.box[0]+3,1+s.box[1]+a.lineHeight,s.box[2])),n.fillStyle=a.labelColor,n.fillText(`hand:${Math.trunc(100*s.score)}%`,s.box[0]+2,0+s.box[1]+a.lineHeight,s.box[2])),n.stroke()),a.drawPoints&&s.keypoints&&s.keypoints.length>0)for(let i of s.keypoints)n.fillStyle=a.useDepth?`rgba(${127.5+2*(i[2]||0)}, ${127.5-2*(i[2]||0)}, 255, 0.5)`:a.color,y5(n,i[0],i[1],0,a);if(a.drawLabels&&s.annotations){let i=(o,l)=>{if(!o||o.length===0||!o[0])return;let d=o[o.length-1][2]||0;n.fillStyle=a.useDepth?`rgba(${127.5+2*d}, ${127.5-2*d}, 255, 0.5)`:a.color,n.fillText(l,o[o.length-1][0]+4,o[o.length-1][1]+4)};n.font=a.font,i(s.annotations.index,"index"),i(s.annotations.middle,"middle"),i(s.annotations.ring,"ring"),i(s.annotations.pinky,"pinky"),i(s.annotations.thumb,"thumb"),i(s.annotations.palm,"palm")}if(a.drawPolygons&&s.annotations){let i=o=>{if(!(!o||o.length===0||!o[0]))for(let l=0;l<o.length;l++){n.beginPath();let d=o[l][2]||0;n.strokeStyle=a.useDepth?`rgba(${127.5+l*d}, ${127.5-l*d}, 255, 0.5)`:a.color,n.moveTo(o[l>0?l-1:0][0],o[l>0?l-1:0][1]),n.lineTo(o[l][0],o[l][1]),n.stroke()}};n.lineWidth=a.lineWidth,i(s.annotations.index),i(s.annotations.middle),i(s.annotations.ring),i(s.annotations.pinky),i(s.annotations.thumb)}}}}async function w5(e,t,r){let a=vr(ps,r);if(!t||!e)return;let n=Dl(e);if(!!n){n.lineJoin="round",n.font=a.font;for(let s of t)if(a.drawBoxes){if(n.strokeStyle=a.color,n.fillStyle=a.color,qh(n,s.box[0],s.box[1],s.box[2],s.box[3],a),a.drawLabels){let i=`${s.label} ${Math.round(100*s.score)}%`;a.shadowColor&&a.shadowColor!==""&&(n.fillStyle=a.shadowColor,n.fillText(i,s.box[0]+3,1+s.box[1]+a.lineHeight,s.box[2])),n.fillStyle=a.labelColor,n.fillText(i,s.box[0]+2,0+s.box[1]+a.lineHeight,s.box[2])}n.stroke()}}}async function WN(e,t,r){let a=vr(ps,r);if(!t||!e)return;let n=Dl(e);if(!!n){n.lineJoin="round",n.font=a.font;for(let s=0;s<t.length;s++)if(a.drawBoxes){if(n.strokeStyle=a.color,n.fillStyle=a.color,qh(n,t[s].box[0],t[s].box[1],t[s].box[2],t[s].box[3],a),a.drawLabels){let i=`person #${s}`;a.shadowColor&&a.shadowColor!==""&&(n.fillStyle=a.shadowColor,n.fillText(i,t[s].box[0]+3,1+t[s].box[1]+a.lineHeight,t[s].box[2])),n.fillStyle=a.labelColor,n.fillText(i,t[s].box[0]+2,0+t[s].box[1]+a.lineHeight,t[s].box[2])}n.stroke()}}}async function VN(e,t){if(!e||!t)return;let r=Dl(t);!r||r.drawImage(e,0,0)}async function UN(e,t,r){if(!t||!t.performance||!t||!e)return null;let a=oe(),n=vr(ps,r),s=Promise.all([x5(e,t.face,n),b5(e,t.body,n),v5(e,t.hand,n),w5(e,t.object,n),A5(e,t.gesture,n)]);return g5=ce.perfadd?g5+Math.round(oe()-a):Math.round(oe()-a),t.performance.draw=g5,s}var _d=.1,k5=.5;function D2e(e,t,r){let a=!1,n=r.length-1;for(let s=0;s<r.length;n=s++)r[s].y>t!=r[n].y>t&&e<(r[n].x-r[s].x)*(t-r[s].y)/(r[n].y-r[s].y)+r[s].x&&(a=!a);return a}async function GN(e){if(!e.tensor||!e.mesh||e.mesh.length<100)return e.tensor;let t=e.tensor.shape[2]||0,r=e.tensor.shape[1]||0,a=await e.tensor.buffer(),n=[];for(let i of Ya.silhouette)n.push({x:(e.mesh[i][0]-e.box[0])/e.box[2],y:(e.mesh[i][1]-e.box[1])/e.box[3]});_d&&_d>0&&(n=n.map(i=>({x:i.x>.5?i.x+_d:i.x-_d,y:i.y>.5?i.y+_d:i.y-_d})));for(let i=0;i<t;i++)for(let o=0;o<r;o++)D2e(i/t,o/t,n)||(a.set(k5*a.get(0,o,i,0),0,o,i,0),a.set(k5*a.get(0,o,i,1),0,o,i,1),a.set(k5*a.get(0,o,i,2),0,o,i,2));let s=a.toTensor();return re(a),s}var L2e=e=>{let t=(p,h)=>Math.atan2(p[1]-h[1],p[0]-h[0]);if(!e.annotations.rightEyeIris||!e.annotations.leftEyeIris)return{bearing:0,strength:0};let r=[0,-.1],a=1,n=(e.mesh[33][2]||0)>(e.mesh[263][2]||0),s=n?e.mesh[473]:e.mesh[468],i=n?[(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=n?[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]-r[0],a*(s[1]-i[1])/o[1]-r[1]],d=Math.sqrt(l[0]**2+l[1]**2);return d=Math.min(d,e.boxRaw[2]/2,e.boxRaw[3]/2),{bearing:(t([0,0],l)+Math.PI/2)%Math.PI,strength:d}},jN=(e,t)=>{let r=m=>{let g=Math.sqrt(m[0]*m[0]+m[1]*m[1]+m[2]*m[2]);return m[0]/=g,m[1]/=g,m[2]/=g,m},a=(m,g)=>{let y=m[0]-g[0],A=m[1]-g[1],x=m[2]-g[2];return[y,A,x]},n=(m,g)=>{let y=m[1]*g[2]-m[2]*g[1],A=m[2]*g[0]-m[0]*g[2],x=m[0]*g[1]-m[1]*g[0];return[y,A,x]},s=m=>{let[g,y,A,x,b,v,C,T,E]=m,R,z,M;return x<1?x>-1?(M=Math.asin(x),z=Math.atan2(-C,g),R=Math.atan2(-v,b)):(M=-Math.PI/2,z=-Math.atan2(T,E),R=0):(M=Math.PI/2,z=Math.atan2(T,E),R=0),isNaN(R)&&(R=0),isNaN(z)&&(z=0),isNaN(M)&&(M=0),{pitch:2*-R,yaw:2*-z,roll:2*-M}},i=e.meshRaw;if(!i||i.length<300)return{angle:{pitch:0,yaw:0,roll:0},matrix:[1,0,0,0,1,0,0,0,1],gaze:{bearing:0,strength:0}};let o=Math.max(e.boxRaw[2]*t[0],e.boxRaw[3]*t[1])/1.5,l=[i[10],i[152],i[234],i[454]].map(m=>[m[0]*t[0]/o,m[1]*t[1]/o,m[2]]),d=r(a(l[1],l[0])),u=r(a(l[3],l[2])),p=r(n(u,d));u=n(d,p);let h=[u[0],u[1],u[2],d[0],d[1],d[2],p[0],p[1],p[2]],c=s(h),f=i.length===478?L2e(e):{bearing:0,strength:0};return{angle:c,matrix:h,gaze:f}};var I5=async(e,t)=>{var c,f,m,g,y,A,x,b,v,C,T,E,R,z,M,I,D,O,j,X,_,K;let r=oe(),a,n,s,i,o,l,d,u,p=[];e.state="run:face";let h=await RC(t,e.config);if(e.performance.face=ce.perfadd?(e.performance.face||0)+Math.trunc(oe()-r):Math.trunc(oe()-r),!t.shape||t.shape.length!==4)return[];if(!h)return[];for(let W=0;W<h.length;W++){if(e.analyze("Get Face"),!h[W].tensor||h[W].tensor.isDisposedInternal){se("Face object is disposed:",h[W].tensor);continue}if((c=e.config.face.detector)==null?void 0:c.mask){let ae=await GN(h[W]);re(h[W].tensor),h[W].tensor=ae}let ee=h[W].mesh&&h[W].mesh.length>200?jN(h[W],[t.shape[2],t.shape[1]]):null;e.analyze("Start Emotion:"),e.config.async?i=((f=e.config.face.emotion)==null?void 0:f.enabled)?Eb(h[W].tensor||pt([]),e.config,W,h.length):[]:(e.state="run:emotion",r=oe(),i=((m=e.config.face.emotion)==null?void 0:m.enabled)?await Eb(h[W].tensor||pt([]),e.config,W,h.length):[],e.performance.emotion=ce.perfadd?(e.performance.emotion||0)+Math.trunc(oe()-r):Math.trunc(oe()-r)),e.analyze("End Emotion:"),e.analyze("Start AntiSpoof:"),e.config.async?l=((g=e.config.face.antispoof)==null?void 0:g.enabled)?lb(h[W].tensor||pt([]),e.config,W,h.length):0:(e.state="run:antispoof",r=oe(),l=((y=e.config.face.antispoof)==null?void 0:y.enabled)?await lb(h[W].tensor||pt([]),e.config,W,h.length):0,e.performance.antispoof=ce.perfadd?(e.performance.antispoof||0)+Math.trunc(oe()-r):Math.trunc(oe()-r)),e.analyze("End AntiSpoof:"),e.analyze("Start Liveness:"),e.config.async?d=((A=e.config.face.liveness)==null?void 0:A.enabled)?Yb(h[W].tensor||pt([]),e.config,W,h.length):0:(e.state="run:liveness",r=oe(),d=((x=e.config.face.liveness)==null?void 0:x.enabled)?await Yb(h[W].tensor||pt([]),e.config,W,h.length):0,e.performance.liveness=ce.perfadd?(e.performance.antispoof||0)+Math.trunc(oe()-r):Math.trunc(oe()-r)),e.analyze("End Liveness:"),e.analyze("Start GEAR:"),e.config.async?n=((b=e.config.face.gear)==null?void 0:b.enabled)?tb(h[W].tensor||pt([]),e.config,W,h.length):null:(e.state="run:gear",r=oe(),n=((v=e.config.face.gear)==null?void 0:v.enabled)?await tb(h[W].tensor||pt([]),e.config,W,h.length):null,e.performance.gear=Math.trunc(oe()-r)),e.analyze("End GEAR:"),e.analyze("Start SSRNet:"),e.config.async?(a=((C=e.config.face.ssrnet)==null?void 0:C.enabled)?ab(h[W].tensor||pt([]),e.config,W,h.length):null,s=((T=e.config.face.ssrnet)==null?void 0:T.enabled)?ib(h[W].tensor||pt([]),e.config,W,h.length):null):(e.state="run:ssrnet",r=oe(),a=((E=e.config.face.ssrnet)==null?void 0:E.enabled)?await ab(h[W].tensor||pt([]),e.config,W,h.length):null,s=((R=e.config.face.ssrnet)==null?void 0:R.enabled)?await ib(h[W].tensor||pt([]),e.config,W,h.length):null,e.performance.ssrnet=Math.trunc(oe()-r)),e.analyze("End SSRNet:"),e.analyze("Start MobileFaceNet:"),e.config.async?o=((z=e.config.face.mobilefacenet)==null?void 0:z.enabled)?Fb(h[W].tensor||pt([]),e.config,W,h.length):null:(e.state="run:mobilefacenet",r=oe(),o=((M=e.config.face.mobilefacenet)==null?void 0:M.enabled)?await Fb(h[W].tensor||pt([]),e.config,W,h.length):null,e.performance.mobilefacenet=Math.trunc(oe()-r)),e.analyze("End MobileFaceNet:"),e.analyze("Start Description:"),e.config.async?u=((I=e.config.face.description)==null?void 0:I.enabled)?Db(h[W].tensor||pt([]),e.config,W,h.length):null:(e.state="run:description",r=oe(),u=((D=e.config.face.description)==null?void 0:D.enabled)?await Db(h[W].tensor||pt([]),e.config,W,h.length):null,e.performance.description=ce.perfadd?(e.performance.description||0)+Math.trunc(oe()-r):Math.trunc(oe()-r)),e.analyze("End Description:"),e.config.async&&([a,s,i,o,u,n,l,d]=await Promise.all([a,s,i,o,u,n,l,d])),e.analyze("Finish Face:"),((O=e.config.face.ssrnet)==null?void 0:O.enabled)&&a&&s&&(u={...u,age:a.age,gender:s.gender,genderScore:s.genderScore}),((j=e.config.face.gear)==null?void 0:j.enabled)&&n&&(u={...u,age:n.age,gender:n.gender,genderScore:n.genderScore,race:n.race}),((X=e.config.face.mobilefacenet)==null?void 0:X.enabled)&&o&&(u.descriptor=o),!((_=e.config.face.iris)==null?void 0:_.enabled);let Q=h[W].annotations&&h[W].annotations.leftEyeIris&&h[W].annotations.leftEyeIris[0]&&h[W].annotations.rightEyeIris&&h[W].annotations.rightEyeIris[0]&&h[W].annotations.leftEyeIris.length>0&&h[W].annotations.rightEyeIris.length>0&&h[W].annotations.leftEyeIris[0]!==null&&h[W].annotations.rightEyeIris[0]!==null?Math.max(Math.abs(h[W].annotations.leftEyeIris[3][0]-h[W].annotations.leftEyeIris[1][0]),Math.abs(h[W].annotations.rightEyeIris[4][1]-h[W].annotations.rightEyeIris[2][1]))/t.shape[2]:0,ne=((K=e.config.face.detector)==null?void 0:K.return)?Ye(h[W].tensor):null;re(h[W].tensor),h[W].tensor&&delete h[W].tensor;let Z={...h[W],id:W};(u==null?void 0:u.age)&&(Z.age=u.age),(u==null?void 0:u.gender)&&(Z.gender=u.gender),(u==null?void 0:u.genderScore)&&(Z.genderScore=u==null?void 0:u.genderScore),(u==null?void 0:u.descriptor)&&(Z.embedding=u==null?void 0:u.descriptor),(u==null?void 0:u.race)&&(Z.race=u==null?void 0:u.race),i&&(Z.emotion=i),l&&(Z.real=l),d&&(Z.live=d),Q&&Q!==0&&(Z.iris=Math.trunc(500/Q/11.7)/100),ee&&(Z.rotation=ee),ne&&(Z.tensor=ne),p.push(Z),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 HN=e=>{if(!e)return[];let t=[];for(let r=0;r<e.length;r++){let a=e[r].keypoints.find(l=>l.part==="leftWrist"),n=e[r].keypoints.find(l=>l.part==="rightWrist"),s=e[r].keypoints.find(l=>l.part==="nose");s&&a&&n&&a.position[1]<s.position[1]&&n.position[1]<s.position[1]?t.push({body:r,gesture:"i give up"}):s&&a&&a.position[1]<s.position[1]?t.push({body:r,gesture:"raise left hand"}):s&&n&&n.position[1]<s.position[1]&&t.push({body:r,gesture:"raise right hand"});let i=e[r].keypoints.find(l=>l.part==="leftShoulder"),o=e[r].keypoints.find(l=>l.part==="rightShoulder");i&&o&&Math.abs(i.positionRaw[1]-o.positionRaw[1])>.1&&t.push({body:r,gesture:`leaning ${i.position[1]>o.position[1]?"left":"right"}`})}return t},qN=e=>{if(!e)return[];let t=[];for(let r=0;r<e.length;r++)if(e[r].mesh&&e[r].mesh.length>450){let a=(e[r].mesh[33][2]||0)-(e[r].mesh[263][2]||0),n=e[r].mesh[33][0]-e[r].mesh[263][0];Math.abs(a/n)<=.15?t.push({face:r,gesture:"facing center"}):t.push({face:r,gesture:`facing ${a<0?"left":"right"}`}),Math.abs(e[r].mesh[374][1]-e[r].mesh[386][1])/Math.abs(e[r].mesh[443][1]-e[r].mesh[450][1])<.2&&t.push({face:r,gesture:"blink left eye"}),Math.abs(e[r].mesh[145][1]-e[r].mesh[159][1])/Math.abs(e[r].mesh[223][1]-e[r].mesh[230][1])<.2&&t.push({face:r,gesture:"blink right eye"});let o=Math.min(100,500*Math.abs(e[r].mesh[13][1]-e[r].mesh[14][1])/Math.abs(e[r].mesh[10][1]-e[r].mesh[152][1]));o>10&&t.push({face:r,gesture:`mouth ${Math.trunc(o)}% open`});let l=e[r].mesh[152][2]||0;Math.abs(l)>10&&t.push({face:r,gesture:`head ${l<0?"up":"down"}`})}return t},KN=e=>{if(!e)return[];let t=[];for(let r=0;r<e.length;r++){if(!e[r].annotations||!e[r].annotations.leftEyeIris||!e[r].annotations.leftEyeIris[0]||!e[r].annotations.rightEyeIris||!e[r].annotations.rightEyeIris[0])continue;let a=e[r].annotations.leftEyeIris[3][0]-e[r].annotations.leftEyeIris[1][0],n=e[r].annotations.leftEyeIris[4][1]-e[r].annotations.leftEyeIris[2][1],s=Math.abs(a*n),i=e[r].annotations.rightEyeIris[3][0]-e[r].annotations.rightEyeIris[1][0],o=e[r].annotations.rightEyeIris[4][1]-e[r].annotations.rightEyeIris[2][1],l=Math.abs(i*o),d=!1;Math.abs(s-l)/Math.max(s,l)<.25&&(d=!0,t.push({iris:r,gesture:"facing center"}));let p=Math.abs(e[r].mesh[263][0]-e[r].annotations.leftEyeIris[0][0])/e[r].box[2],h=Math.abs(e[r].mesh[33][0]-e[r].annotations.rightEyeIris[0][0])/e[r].box[2];(p>.06||h>.06)&&(d=!1),p>h?p>.05&&t.push({iris:r,gesture:"looking right"}):h>.05&&t.push({iris:r,gesture:"looking left"});let c=Math.abs(e[r].mesh[145][1]-e[r].annotations.rightEyeIris[0][1])/e[r].box[3],f=Math.abs(e[r].mesh[374][1]-e[r].annotations.leftEyeIris[0][1])/e[r].box[3];(f<.01||c<.01||f>.022||c>.022)&&(d=!1),(f<.01||c<.01)&&t.push({iris:r,gesture:"looking down"}),(f>.022||c>.022)&&t.push({iris:r,gesture:"looking up"}),d&&t.push({iris:r,gesture:"looking center"})}return t},XN=e=>{if(!e)return[];let t=[];for(let r=0;r<e.length;r++){let a=[];if(e[r].annotations)for(let[n,s]of Object.entries(e[r].annotations))n!=="palmBase"&&Array.isArray(s)&&s[0]&&a.push({name:n.toLowerCase(),position:s[0]});if(a&&a.length>0){let n=a.reduce((i,o)=>(i.position[2]||0)<(o.position[2]||0)?i:o);t.push({hand:r,gesture:`${n.name} forward`});let s=a.reduce((i,o)=>i.position[1]<o.position[1]?i:o);t.push({hand:r,gesture:`${s.name} up`})}if(e[r].keypoints){let n=tN(e[r].keypoints);for(let s of n)t.push({hand:r,gesture:s.name})}}return t};var Ee={face:[],body:[],hand:[],gesture:[],object:[],persons:[],performance:{},timestamp:0,error:null},S5=0;function ZN(e,t){var i,o,l,d,u,p,h,c,f,m,g,y,A,x,b,v,C,T,E,R,z,M,I,D,O,j,X;let r=oe();if(!e)return{face:[],body:[],hand:[],gesture:[],object:[],persons:[],performance:{},timestamp:0,error:null};let a=Date.now()-e.timestamp,n=a<1e3?8-Math.log(a+1):1;if(e.canvas&&(Ee.canvas=e.canvas),e.error&&(Ee.error=e.error),!Ee.body||e.body.length!==Ee.body.length)Ee.body=JSON.parse(JSON.stringify(e.body));else for(let _=0;_<e.body.length;_++){let K=e.body[_].box.map((Z,ae)=>((n-1)*Ee.body[_].box[ae]+Z)/n),W=e.body[_].boxRaw.map((Z,ae)=>((n-1)*Ee.body[_].boxRaw[ae]+Z)/n),ee=e.body[_].keypoints.map((Z,ae)=>{var ie,xe,be,Te,Re,$e,_e,qe,Ze;return{score:Z.score,part:Z.part,position:[Ee.body[_].keypoints[ae]?((n-1)*(Ee.body[_].keypoints[ae].position[0]||0)+(Z.position[0]||0))/n:Z.position[0],Ee.body[_].keypoints[ae]?((n-1)*(Ee.body[_].keypoints[ae].position[1]||0)+(Z.position[1]||0))/n:Z.position[1],Ee.body[_].keypoints[ae]?((n-1)*(Ee.body[_].keypoints[ae].position[2]||0)+(Z.position[2]||0))/n:Z.position[2]],positionRaw:[Ee.body[_].keypoints[ae]?((n-1)*(Ee.body[_].keypoints[ae].positionRaw[0]||0)+(Z.positionRaw[0]||0))/n:Z.positionRaw[0],Ee.body[_].keypoints[ae]?((n-1)*(Ee.body[_].keypoints[ae].positionRaw[1]||0)+(Z.positionRaw[1]||0))/n:Z.positionRaw[1],Ee.body[_].keypoints[ae]?((n-1)*(Ee.body[_].keypoints[ae].positionRaw[2]||0)+(Z.positionRaw[2]||0))/n:Z.positionRaw[2]],distance:[Ee.body[_].keypoints[ae]?((n-1)*(((ie=Ee.body[_].keypoints[ae].distance)==null?void 0:ie[0])||0)+(((xe=Z.distance)==null?void 0:xe[0])||0))/n:(be=Z.distance)==null?void 0:be[0],Ee.body[_].keypoints[ae]?((n-1)*(((Te=Ee.body[_].keypoints[ae].distance)==null?void 0:Te[1])||0)+(((Re=Z.distance)==null?void 0:Re[1])||0))/n:($e=Z.distance)==null?void 0:$e[1],Ee.body[_].keypoints[ae]?((n-1)*(((_e=Ee.body[_].keypoints[ae].distance)==null?void 0:_e[2])||0)+(((qe=Z.distance)==null?void 0:qe[2])||0))/n:(Ze=Z.distance)==null?void 0:Ze[2]]}}),Q={},ne={connected:{}};((o=(i=t.body)==null?void 0:i.modelPath)==null?void 0:o.includes("efficientpose"))?ne=b0:((d=(l=t.body)==null?void 0:l.modelPath)==null?void 0:d.includes("blazepose"))?ne=m0:((p=(u=t.body)==null?void 0:u.modelPath)==null?void 0:p.includes("movenet"))&&(ne=Gh);for(let[Z,ae]of Object.entries(ne.connected)){let ie=[];for(let xe=0;xe<ae.length-1;xe++){let be=ee.find(Re=>Re.part===ae[xe]),Te=ee.find(Re=>Re.part===ae[xe+1]);be&&Te&&ie.push([be.position,Te.position])}Q[Z]=ie}Ee.body[_]={...e.body[_],box:K,boxRaw:W,keypoints:ee,annotations:Q}}if(!Ee.hand||e.hand.length!==Ee.hand.length)Ee.hand=JSON.parse(JSON.stringify(e.hand));else for(let _=0;_<e.hand.length;_++){let K=e.hand[_].box.map((ne,Z)=>((n-1)*Ee.hand[_].box[Z]+ne)/n),W=e.hand[_].boxRaw.map((ne,Z)=>((n-1)*Ee.hand[_].boxRaw[Z]+ne)/n);Ee.hand[_].keypoints.length!==e.hand[_].keypoints.length&&(Ee.hand[_].keypoints=e.hand[_].keypoints);let ee=e.hand[_].keypoints&&e.hand[_].keypoints.length>0?e.hand[_].keypoints.map((ne,Z)=>ne.map((ae,ie)=>((n-1)*(Ee.hand[_].keypoints[Z][ie]||1)+(ae||0))/n)):[],Q={};if(Object.keys(Ee.hand[_].annotations).length!==Object.keys(e.hand[_].annotations).length)Ee.hand[_].annotations=e.hand[_].annotations,Q=Ee.hand[_].annotations;else if(e.hand[_].annotations)for(let ne of Object.keys(e.hand[_].annotations))Q[ne]=e.hand[_].annotations[ne]&&e.hand[_].annotations[ne][0]?e.hand[_].annotations[ne].map((Z,ae)=>Z.map((ie,xe)=>((n-1)*Ee.hand[_].annotations[ne][ae][xe]+ie)/n)):null;Ee.hand[_]={...e.hand[_],box:K,boxRaw:W,keypoints:ee,annotations:Q}}if(!Ee.face||e.face.length!==Ee.face.length)Ee.face=JSON.parse(JSON.stringify(e.face));else for(let _=0;_<e.face.length;_++){let K=e.face[_].box.map((ee,Q)=>((n-1)*Ee.face[_].box[Q]+ee)/n),W=e.face[_].boxRaw.map((ee,Q)=>((n-1)*Ee.face[_].boxRaw[Q]+ee)/n);if(e.face[_].rotation){let ee={matrix:[0,0,0,0,0,0,0,0,0],angle:{roll:0,yaw:0,pitch:0},gaze:{bearing:0,strength:0}};ee.matrix=(h=e.face[_].rotation)==null?void 0:h.matrix,ee.angle={roll:((n-1)*(((f=(c=Ee.face[_].rotation)==null?void 0:c.angle)==null?void 0:f.roll)||0)+(((g=(m=e.face[_].rotation)==null?void 0:m.angle)==null?void 0:g.roll)||0))/n,yaw:((n-1)*(((A=(y=Ee.face[_].rotation)==null?void 0:y.angle)==null?void 0:A.yaw)||0)+(((b=(x=e.face[_].rotation)==null?void 0:x.angle)==null?void 0:b.yaw)||0))/n,pitch:((n-1)*(((C=(v=Ee.face[_].rotation)==null?void 0:v.angle)==null?void 0:C.pitch)||0)+(((E=(T=e.face[_].rotation)==null?void 0:T.angle)==null?void 0:E.pitch)||0))/n},ee.gaze={bearing:((n-1)*(((z=(R=Ee.face[_].rotation)==null?void 0:R.gaze)==null?void 0:z.bearing)||0)+(((I=(M=e.face[_].rotation)==null?void 0:M.gaze)==null?void 0:I.bearing)||0))/n,strength:((n-1)*(((O=(D=Ee.face[_].rotation)==null?void 0:D.gaze)==null?void 0:O.strength)||0)+(((X=(j=e.face[_].rotation)==null?void 0:j.gaze)==null?void 0:X.strength)||0))/n},Ee.face[_]={...e.face[_],rotation:ee,box:K,boxRaw:W}}Ee.face[_]={...e.face[_],box:K,boxRaw:W}}if(!Ee.object||e.object.length!==Ee.object.length)Ee.object=JSON.parse(JSON.stringify(e.object));else for(let _=0;_<e.object.length;_++){let K=e.object[_].box.map((ee,Q)=>((n-1)*Ee.object[_].box[Q]+ee)/n),W=e.object[_].boxRaw.map((ee,Q)=>((n-1)*Ee.object[_].boxRaw[Q]+ee)/n);Ee.object[_]={...e.object[_],box:K,boxRaw:W}}if(e.persons){let _=e.persons;if(!Ee.persons||_.length!==Ee.persons.length)Ee.persons=JSON.parse(JSON.stringify(_));else for(let K=0;K<_.length;K++)Ee.persons[K].box=_[K].box.map((W,ee)=>((n-1)*Ee.persons[K].box[ee]+W)/n)}e.gesture&&(Ee.gesture=e.gesture);let s=oe();return S5=ce.perfadd?S5+Math.round(s-r):Math.round(s-r),e.performance&&(Ee.performance={...e.performance,interpolate:S5}),Ee}function L0(e,t,r={order:2,multiplier:25}){let a=0;for(let n=0;n<e.length;n++){let s=!r.order||r.order===2?e[n]-t[n]:Math.abs(e[n]-t[n]);a+=!r.order||r.order===2?s*s:s**r.order}return(r.multiplier||20)*a}var YN=(e,t,r,a)=>{if(e===0)return 1;let n=t===2?Math.sqrt(e):e**(1/t),s=(1-n/100-r)/(a-r);return Math.max(Math.min(s,1),0)};function JN(e,t,r={order:2,multiplier:25,min:.2,max:.8}){let a=L0(e,t,r);return YN(a,r.order||2,r.min||0,r.max||1)}function QN(e,t,r={order:2,multiplier:25,threshold:0,min:.2,max:.8}){if(!Array.isArray(e)||!Array.isArray(t)||e.length<64||t.length===0||e.length!==t[0].length)return{index:-1,distance:Number.POSITIVE_INFINITY,similarity:0};let a=Number.MAX_SAFE_INTEGER,n=-1;for(let i=0;i<t.length;i++){let o=L0(e,t[i],r);if(o<a&&(a=o,n=i),a<(r.threshold||0))break}let s=YN(a,r.order||2,r.min||0,r.max||1);return{index:n,distance:a,similarity:s}}function e9(e,t,r,a,n){var o,l,d,u,p,h,c,f,m,g,y,A,x,b,v,C;let s=0,i=[];for(let T of e){let E={id:s++,face:T,body:null,hands:{left:null,right:null},gestures:[],box:[0,0,0,0]};for(let O of t)T.box[0]>O.box[0]&&T.box[0]<O.box[0]+O.box[2]&&T.box[1]+T.box[3]>O.box[1]&&T.box[1]+T.box[3]<O.box[1]+O.box[3]&&(E.body=O);if(E.body)for(let O of r)O.box[0]+O.box[2]>E.body.box[0]&&O.box[0]+O.box[2]<E.body.box[0]+E.body.box[2]&&O.box[1]+O.box[3]>E.body.box[1]&&O.box[1]+O.box[3]<E.body.box[1]+E.body.box[3]&&E.hands&&(E.hands.left=O),O.box[0]<E.body.box[0]+E.body.box[2]&&O.box[0]>E.body.box[0]&&O.box[1]+O.box[3]>E.body.box[1]&&O.box[1]+O.box[3]<E.body.box[1]+E.body.box[3]&&E.hands&&(E.hands.right=O);for(let O of a)O.face!==void 0&&O.face===T.id?(o=E.gestures)==null||o.push(O):O.iris!==void 0&&O.iris===T.id?(l=E.gestures)==null||l.push(O):O.body!==void 0&&O.body===((d=E.body)==null?void 0:d.id)?(u=E.gestures)==null||u.push(O):O.hand!==void 0&&O.hand===((h=(p=E.hands)==null?void 0:p.left)==null?void 0:h.id)?(c=E.gestures)==null||c.push(O):O.hand!==void 0&&O.hand===((m=(f=E.hands)==null?void 0:f.right)==null?void 0:m.id)&&((g=E.gestures)==null||g.push(O));let R=[],z=[],M=O=>{O&&O.length===4&&(R.push(O[0],O[0]+O[2]),z.push(O[1],O[1]+O[3]))};M((y=E.face)==null?void 0:y.box),M((A=E.body)==null?void 0:A.box),M((b=(x=E.hands)==null?void 0:x.left)==null?void 0:b.box),M((C=(v=E.hands)==null?void 0:v.right)==null?void 0:C.box);let I=Math.min(...R),D=Math.min(...z);E.box=[I,D,Math.max(...R)-I,Math.max(...z)-D],n&&n[1]&&n[2]&&(E.boxRaw=[E.box[0]/n[2],E.box[1]/n[1],E.box[2]/n[2],E.box[3]/n[1]]),i.push(E)}return i}var B0=`
|
|
/9j/4AAQSkZJRgABAQEAYABgAAD/4QBoRXhpZgAATU0AKgAAAAgABAEaAAUAAAABAAAAPgEbAAUA
|
|
AAABAAAARgEoAAMAAAABAAIAAAExAAIAAAARAAAATgAAAAAAAABgAAAAAQAAAGAAAAABcGFpbnQu
|
|
bmV0IDQuMi4xMwAA/9sAQwAGBAUGBQQGBgUGBwcGCAoQCgoJCQoUDg8MEBcUGBgXFBYWGh0lHxob
|
|
IxwWFiAsICMmJykqKRkfLTAtKDAlKCko/9sAQwEHBwcKCAoTCgoTKBoWGigoKCgoKCgoKCgoKCgo
|
|
KCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo/8AAEQgBAAEAAwEhAAIRAQMRAf/E
|
|
AB8AAAEFAQEBAQEBAAAAAAAAAAABAgMEBQYHCAkKC//EALUQAAIBAwMCBAMFBQQEAAABfQECAwAE
|
|
EQUSITFBBhNRYQcicRQygZGhCCNCscEVUtHwJDNicoIJChYXGBkaJSYnKCkqNDU2Nzg5OkNERUZH
|
|
SElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6g4SFhoeIiYqSk5SVlpeYmZqio6Slpqeoqaqys7S1
|
|
tre4ubrCw8TFxsfIycrS09TV1tfY2drh4uPk5ebn6Onq8fLz9PX29/j5+v/EAB8BAAMBAQEBAQEB
|
|
AQEAAAAAAAABAgMEBQYHCAkKC//EALURAAIBAgQEAwQHBQQEAAECdwABAgMRBAUhMQYSQVEHYXET
|
|
IjKBCBRCkaGxwQkjM1LwFWJy0QoWJDThJfEXGBkaJicoKSo1Njc4OTpDREVGR0hJSlNUVVZXWFla
|
|
Y2RlZmdoaWpzdHV2d3h5eoKDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXG
|
|
x8jJytLT1NXW19jZ2uLj5OXm5+jp6vLz9PX29/j5+v/aAAwDAQACEQMRAD8A+qaKACigApGOKAML
|
|
Xp8xlF5A7V4X8RtYs7PzfNImnx8sa8Kp9z3q2tEgp6angWs62ZZ5CTGoJ6DArGNz5p+UrID6EUrF
|
|
PUlW1EuN0XNW7PQ2L5j3JnoKXN0KijqNP0eYoqXBdgPuuo+ZPeupisWn2Jd4+0r924XgsQOCff3/
|
|
AJ1FzRKxDqGii6m3siiQ8F1XGfXI6YNWLfRbiRQMkcZI9fpTDluT2/h6Qy8gDPbtmtG38JeY480Z
|
|
5zSLUTZg8M28YwYxjAArXtdPt402qgHbpSaLWhma3o0Uqk7Nx9DWLaaVblgPs6qRyds2M/gRSQp9
|
|
zZOni2iWS2hlQ+kjYz9OMGrdjq89vIPPVhj+8M/lQyDq9P1WOYBlMZz1AOD+VdDaTiReOKulK0jO
|
|
tHmi0WDTlr0TyxRVhT8tJjIX+9SUxHXUV553BRQAVBcPhSBTSuxPY86+IGti0s5I7dsORy9fM3i6
|
|
8e8mfDO5P90ZrWWiJicNPpZZtxV/xrW0jQt4DOv6Vk2dEEdTY6BHuB25rpbPSo0QARjP0qTRI17W
|
|
wA/hFaMWmoQMgflQXYsDS142rU9tpqqenfNA7GgtihxkdKuRW6qMY/GkDZY8sY4Ap4hXbyB+VArk
|
|
EtuH4wPyrk/EGkOm+a3jw3suRQLc5i38SX9hJ9nnY+XnBUdPyNdFY6pa3KkkAE9l6f8AfJ/pSJT6
|
|
GhDmI+Zb4ZRycdv6ium0nUhKFydrelTsNnS2829RnrVgV6NKXNG55lWPLIM81Op+WrZkRMfmNNzT
|
|
A7GivPO4KKAEY4XNYWt3vkwPg4OK0giJdjw/xrqhm87Zs8tc7pX5A+leSajf6aHYJ50kn4AZpTep
|
|
rBWRm2Vobm4BXfyehPFdnpmnBFUY5rI2SN63tlToK0YI+KZpFF+3QdavwoKTLtoW0Toaswpk5pCb
|
|
LCxipAhoIuP2dKevHXoaYDylRyxhlwRQI4nxVoCXWZI1GfpXGtbSWjYPGP73+NIGupt6TqMsLruZ
|
|
ih4xnP5V09mQ+JLd8gn0xSYJnVaVdkook69K34zuUGunDS3Rx4qOzHVIp4rrOMY3NJQI7GivPO8K
|
|
KAILt9kZrz3xlebYiu8KCCWb0XvW0NFch6ysfO3jLVjfXLIn+pQkKorl7WxNxIPl71g2dUUdpo+l
|
|
pBGvHPet23iC8ihFosrxirkHQUFo0IF4FXI1O726CpKLacCrMJoJLYHAPpTwucHpSRJJ5e4AZI9x
|
|
UqpxzVpCuOC8cUpQUMRnXttuB4rjNdsYyeVwfXpmpGmcvcQyafMCFJjPY10eg34BUg4DcZP8jUO4
|
|
HaRq3lLNF+IHet7R7jz7c56rwa2wz9+xhiVeFy/T1PFegeaNPWigDsc0ZrzzvDNIaAM7VpNqdegr
|
|
xL4l6kywyRhseZ19lrdfAZL4jxYg3Fw20d63tJsdrDI5rm3Z3R0R0Mce1eKnQYAplIkWrMJ45oZS
|
|
NO3PHbNXIyfpSGWowSOasxLUiZdjFSqtNEMkUemKlAGKsRJjAppFAiORMjmsTVrNZEO4cfSoZSOD
|
|
1eJ7WXBUzQZ+7nkfSo7e2Ei+ZaMzxntjBX2NSU1Y6/wxqojiEFzkA8KTXYaUoWRyv3W5rSjpNHPX
|
|
+BmpSg8V6J5gUUAdhRXnneFFAGHrTfu5PpXzj8S70/aZtxzztXFbv4DKHxHI+H4GZiz9zxXXW8G3
|
|
GBXMjvLRXAx0oPGPSmMVeOnWrMTYpFI0bcg1fh54xmgovRcD3qxETSIZcRvzp+/BpEkqsBUqsM9K
|
|
q4Em4Gkxk0yRGXrVW6i8yFhkg+tJjRxGsWrxllkUMh9eK5uMz6bcebbnfG33kPcVkay2OntPKuo0
|
|
nhXI67c8qa7Lw3c+adjcEDGK1paSRhVV4s6A0or0jyRRQ1AHX0V553hRQBz+vNtt5z3xXzX8Qbdm
|
|
uic5YnOMdK3l8JnTXvlbwpYl+WySOgrp5YfLOOB9O1c62O7qQkc+9RsKChFPWp4DluOlSykaNruH
|
|
ArUgHShFNF2NT1qxGO3NBmyxGcE1N2560CFzjrUysO9JAPDDjFOVuKoQuSRTWouBkazbCa3cd8cV
|
|
wF7IISQccHBzUSWpV9C3o1x5b5GAjdQD1rs9DjC3kckbEhqKfxIzn8LOupRXqnkPccBSkUAzraK8
|
|
87wooA5rxMSI3HqK8B8bQl9Q8sffY5b/AAraXwkUviNrw9pH2W1ViMMRTdRjw4HpWNtDti9TPc4P
|
|
FQs2M5qdyyMHLcfjV63HTAoBGtap0wK0YxigpsuRDtVhVYd6GQydVwwIqdRnqKCR23I5pCMUW6gD
|
|
YNKuetAEise9KTxQBWuFyhrznxNZkXjFeN3I+tTIZg2OqmzmxNF0PO3vXp/g2+hukVl4zyPanTXv
|
|
JmVR+60dpThXpnlPceopWFAbnV0V553hSGgRynjC5FujOey14Ssp1HxNmTnc+a3kvcIpv37HoEYQ
|
|
QmMdVHSsnVbYJF5jVk0dsNzlruVIsl2wKxbjWrVHILjg1CRbZJb+ILHPzyhfStODWLQgFJFYd+el
|
|
UJM27HUIXxhga1Y5lLVLKLkMnoauxnPPrSEx7ShF+Y/n2qrc6xBbhizDAqkK1zJuvG9nbg8ZA681
|
|
ly/Ei052RO3uKAsZlx8QGd8xxvt9Aa1NH8dK7AXMcip64zigdkdrZX8F7EJLdwwNXMkrz1qRMRly
|
|
CK4TxmpidWI49felPYSOMmi80NIoOV6qRzXYeA5SskYPfirpfEjGr8LPWVHyD6U4CvQPL3ZItOYc
|
|
UDOoNFeed4Uhpks4H4iE/Z5MeleMeGULeLgjds10S+BGdL+Jc9OSBU2Huc5Nc74yvUtrcDBrJnZF
|
|
63PJdXvLy/lKWw46bvQVz82jXhkLO5Y+9ZlsYthcRnbIjY9R3q3awTRkEM3WmJI6C0ea3dGRsr1x
|
|
XY6TqW9FLHnjrUs0izpLK5DDjofSta3ckH09KRUkZuuTvFGdvPauE1Y3U6Mqbssf/rUxHPTaJPK2
|
|
ZmJPbBqzY6DCZh5xJC9s9aBJHU6dpemJjfEmfetJtI0+VPkUr/unFOxdiextHs33W07YHQHk11mk
|
|
Xb3KbZ1xIvcd6LEyWho4Nct41sTPYb16ipexCPPZN+wYGCvH1rrPAEJmvkPoc1VL4kZVvgZ6yFwK
|
|
cBXoHkkqinFaVyzo80GuE7WJRQSziPiGdthK5HQV4x4J/wBI8WPIewNdEvgRNL42emO/yj1UHNef
|
|
eNpRczbC+I17DvWT2OqJxc0sMK4TCisy41q0hfEkqj8aixdwTXNOlwvmqD9anS9tXH7uVG+hosO4
|
|
/wC0oOhrR0+6G4YNIEzsNEuCxAPNdjZruA4xxUmjINSjURksOlcbqFykbnjFA1sYGoassaknCqO5
|
|
rl7rxhGm7yBnBxuJq0rkSlYpw+NLlsfd5P8AerVsvHEqSBHwPVgcgVpyMyVXU3rXxcHYETAk+hru
|
|
/DWti6ZSTyOKzZqndHaxvvUGq2rQ+dYyqR24qWI8dvbr7LqDxyDAzXpvw6FvIxePGSM06Xxoyr/A
|
|
zviKFHNegeX1J41zUhXioGbuaSuM6wpCaBHG/EcA6HN/exxXjXw2jL67cv8A3Qa6H8CFR+NnoWpO
|
|
I4XI44rxLxrqjQzSEsQM1gdSPM9U1uR1YbmWIdXHf2rmpIb67YS28UrRlsLI3c/jW0VZGUpO5pW1
|
|
jfLNOjahawzwReYI5cjzMkDavHJ5/SrVv9uhtPtVxCPLBwzxnlT9KGghLU3tKvvPjHzbl7EGuisJ
|
|
GRxWLOg7nRXJEbDjmvSNK+aFSfSoZr0KutRkphc4NcRrdkVjL9aVio7Hk3iqS8ubhrWzUlsZY9kG
|
|
cZNc5D4aee5MclzJIFTzHAO0MfatqSOWu7bFS1srDUZEis0vIZoUxPvfcC+4/dx2xjr712XiTwXb
|
|
WmlQ6hol3cRhoFd4rlg3zY5wR0GelavQwjq7GD4etdVvSnk2wAB+9v8A8mvcfA2kXiRo0/UdcDis
|
|
ZnTTulqeoWqbUAJqWUb42X1FZlnjfjSwlGrr5S/eNdD4RkvLAAQ4yRyaUZcruVKl7TQ9I0G+mnzH
|
|
ckFwM8VuIK7ac3KF2eXiKapz5UWYxipNtMyNejNch0jSar3cjR27uoyQCRVRWom9DxTx54gu5fMi
|
|
lbKdMVjfCZPNlv5v9rFbVHpYqjGzbOn8SzFI9o715L4u0r7arYzk+lYdTqSujy7U/C0u4vHk+WwO
|
|
xuh9q3J9dgvbdVukMV1EwbDDgn04rZMwlHoZ+orZ6hfQ3RWVnQYCgZAq+8U0ln5NtBsV2yxYcfgK
|
|
JtW0CnB31LlroVwJ1nQLGDjeP7w+lb0dsFxjrWB0tHS6NuWPJ6A16ToUm63T3Gallr4S7cxiTjrX
|
|
PaxaF7dlVeSMUhxZ5jd+H7qCa4eF3DSE5x3zXN3Wk6jbyeaiFWUY6ZyPStYS5SalPmVipFbX0E4c
|
|
W0alvmPHJrag0rVvEE6LdljGpG2NRtQD+tW5XMI0uU9M8NeFo9PiQhecDIIrtrOMIoG3H4VlJm9t
|
|
C6CB06VPGM1IHLeItGS6uw+ORT7e3jsbQvj7gzUNam0JaWE+HN7NqOqX80n3FO1RXo8YzXdS+BHk
|
|
4z+KyzGPapcU2YIv7qQtiuaxvcaWqG4O6FwfSrS1JbPnrxoxkv7qIfejcitj4V2f2exumI+8+aKn
|
|
xHTT+G5d8Txlm4rjLxMsQwzWT3OiK0Mm6sEkVsAcjFc1d+FEmlGwEDPQVopaEuOpr6f4ZWNAu3tW
|
|
vHpAj5ZQcUFIWaDjGMVUMQ3cVDBmvbhY7QAV2nh+T/R1yeKhlrY31+b61FcQK6nIoJMi401WblRi
|
|
qr6PCw5UYq9y+YgOgWzNkRrx3xWjp+nx2v3FQcelAbmko9anQ4GBUNisPHWr1qMrQhS2K11HvmYV
|
|
hamcxSRZ5xRIqluS/DKAQQXZxyXrvo2FdlL4EeZjH+/ZbjNSZpswLNBrE1Gt7VE4ODVIlnh/j61F
|
|
j4lmeTGyUbq6LwdEqWbeX0YbhSqfEddP4Bddj4JIrhL5d8h7VjI6oLQqKNzelWre3yc4/ClFjaL6
|
|
wqBxxUUxwCKu5BmXRA6c+9ZjP83FSBoQuPs4BrsNBlUW659KmRrDY6G1lyQtW3Hy0lqQ1qVJnAbm
|
|
oy3b9KYJCqRj3o4zRctIlhjLHmpSuOBRbQOpLGpPFaES7UqkZzKN1KsEc87/AHUUmvPLTVGv72aQ
|
|
k7WJwKmRrQ3ud74Ltilgz4++2a6iNDXdS0gjyMU71my7GpqTbxSbMki3SViajTTHqkSeR/GeyZmg
|
|
nQHkEE1S+F+oPPavBL96I4/Cia1udVF+4dVrkW+Fq8+v4tjMDWUkdVJ6WM0cNV+F+MVmjUcZgqnP
|
|
1qpNNnkcVRLiZtxIS1UzzIF7mghlxUZpVQdq6nTVdAoAOKzkbQWhvwM6gMM1twOJYx3NOJE11Kt1
|
|
H1/pVVlwBkk+9NocXoOQ45FPj+fkUJFF2NSB700v/hTEty5ZpkjvVyUgcCq6GM9zC14/8Se6GcZQ
|
|
1574Xs5WkI2HBPHFQ1dm1KSSZ7Rotn9l0+KPHIHNacae1dy0Vjxaj5ptlhVp+2s2CJ9ppCKzuWNx
|
|
zSFc1SYrHNeNdIGpaYw25ZeRXmvheyk0jVpEdcLJ0q3ZxNKTa0O3vQHg/DNcHrsJDmsmjspnNzNt
|
|
fFIJ24GazOhC+azDmgZIOOKBsp3J2qSaZodubq58yQ4QAnmhGT3NO18pb7BORmu205LfYpyKVkWp
|
|
Oxr5gKYWoIZWgfGfloFq1qTPLubnGO1RPtxg4P0oBAkY/hBz6VNDDkZ6AU0W2WSdqkdKr9ZOaGSj
|
|
VtcLHmnOcgmmYvcz7mBLy3MbdD1q9ouiRK6bUAVeelOC1InPlidSsWMDFOCEdq3uefykqrinYqGy
|
|
rFvApMVka2DAowKAsMkRXQqwyDXn/iWyitNQ3qPl6itIvRoF8RXinW4tQ6HI6GuW8SIVBPalc6qe
|
|
5x9x97r3qruwTjrWZ0ksZ9TUmcDNAmZ9/wAoao63rR0+w22MLPtAzt6mghmfofiB76LdJBJBIp5D
|
|
d/oa7bSdWLIPnpDi9TM8TeKdas51XTbIyxd3J/pXS+E/EFxqNoFu7do5OmD60maHWrnZyDRkn/69
|
|
MlEyOR0xntVoNx+FUgYjPxg4FLCuWDZyKQr2RoRnP0qO+nEFpJITgAUzLqZnhu6+0rknOTXpOmwJ
|
|
Fbrt5yMmnHYyr6Oxb2ijaKLnPYMClwKQWK3n0hn+lachHOJ9pNNN0apQFzsY10a4v4hXQh0xpieQ
|
|
MA1XLZNjhK80cT8OdV+3Wl3A7ZZJCw+hrR1qLcjZ/CsbnfHRnFXseHJArOYYbrUs1uPhYbuatqFP
|
|
ByfSkMq3UIINYkto+87Tx6GkSxfsDbflGD7CtTw/pk4nzITtPIFMFudsukh4Rxz71paTpKwP5jcn
|
|
0qTRy0NORMDgVCqewoJTJgAoxjntTiTu7fWmFxAcnn1q3EPl+X8KZMi4gKqB1Peob/Tv7Us5bfeU
|
|
yOoq4R5nYxqT5I8xieH9J1DTbvyJELRg8ODwa9Ms5mSFV9BWiptbnNVrKdmif7Q1KLg96XIZc5Is
|
|
pNL5pqeUrmMtZs0jzV08phchaY00zH1p2ZNxjS1g+LdJOt6U9ssmxjyGp2urDjLlaZzng/wUPDqz
|
|
TSTmWeTrjpVjVk3Rvjr2rnqQ5dDvo1XUd2cTqSNk9OKxXGCeKxZ1DAxHTr2q5C/y8GokUhsz54qu
|
|
uCxzSQjQ0+FZblR2ro4bZYiMVQ0dBb7Qi5x0qzuG5QOh71LYErDufpSeWrHnimIXbjkUjLkH1Hem
|
|
gGxryc+tXI19KYmWegq9YLiLJ7mtqS945cS7QsWehqxA9dEjz4krPSxyZqbFFhGxUm6smjRM55Lk
|
|
HvSvNxXTY57kLT+9MNwKdhXGm5FIbkU7Bca1wMEVhaiuQcVhXWiZ14R6tHGanGBI2OtYkqEHjgVy
|
|
s9ErEeo6UBsHipKEZs5qpPdRxcbhx70NCSuybTNWihc5brW9Fq6vjMnFSdEIdDRi8RRKygZbHFbu
|
|
m6nb3RA3gMegNJhOm0jbXGOoxTuCc1Rz3FyoGKawz9KaAVcZqeMgCmIkB4FaUTbYwB6V00Fuzixb
|
|
0SFMuDU8Mlbs4UPeXHeiOXkUrDuXYnyKk3cVk0ap6HMxxketSMhrcwRC0dMMZFMQ3yzSeVQAeUaz
|
|
9Vj8uPd271nVV4m+GdpnHX67pCeKyLtBtNcR6xlk9RVeWTb3qRnO6trgttyIfm71z7ai8j7/AJmN
|
|
DNqUVa5Yi1AnjynHuBV+11YJhWWXcP8AZNSzqgmaEerSsf3NtIQP4mGKtRavdRgMIpVI9KjU0a7n
|
|
R6T43uYQI7qN2Tpkqciu503VVuQGAYZHQjFVc4alPlZrpKGAznpTwxOc9+lWjIlUACnM4XApiLNk
|
|
nmvnsK0NvpXZRVonmYqV52GsmanhXitTmFkSiJTSAvwrxUxXIrJ7miOfjf1pzNWxkRlqYWpgJupu
|
|
6gQbuahvIxPA6eo4pNXVioS5WmefakGhndH4INZs5DJXA10PaTurmLO21uKpSZqGMoXGnRzBiyjd
|
|
9Kx5rcQS428fSkjanLoaOliHGZFB56VswW+mtPufcBsGOAfmxz+tFkd8HpoaUx09FAtFY8DO71qb
|
|
Sms/Nb7RbecG6AEjFLS5c78t+p0djpVs9wsyQiJAdyr1rW+zqjErzSe559Sbk9S3C+MA1bjbgE1S
|
|
MSXzMVG0vNUI2tPKrAuCMnrVzNd0PhR49W/O2xrHmp4TxVMzQshpIzzQBehqesnuaI5VGzT2bitz
|
|
FEbNTC1ADS1JupgG6l3UAc14s04yR/aYRll+8BXCtLncDXFWjys9TCz5oW7GddH5qqNzWDOgQnC8
|
|
VSuo1kHzAGkPYopEY2+RWxV23Vzj5G/Kg3jWaNazhZuqNXS6TaKhB2c0jR1nJWOlhOxRxU4YkCgx
|
|
Y0OQatQyDbyaaFYe8uF4NY3iC9ltbVGj43NTIL3h7WzMihjzXVQXYYDdW9Cf2WcOJpfaRZ3g9KsQ
|
|
mupnCLIabGeaAL0LcVY3cVmzRHIxtUhetzEjZqjLUAIWpN1ArhupwagAfDKQ3Q1594v0c2bm6tx+
|
|
5Y8j+6ayrR5onThp8s7dzkZjuqAAmuBnqC7c0iwgtzSA0rWzjfGRW3ZadDu4AoNYo2rfS4v7orSh
|
|
05UA2r0pDbsTm29KRottBNyJ0wpJ9KhD7f6U0ikNWffIFBz60zVUW52ow4UcUN6EPcx44WsbgOmd
|
|
ua7TT5Bd24KHnFKnLlZFSN4koluLdueRWvp14swweG9DXoxldHlTjYtzGoo25qzEvwtUxas2jRPQ
|
|
5CNqkLVsYoYzUzdQA3dSFqBBmnqaBhuqhriCXTpVIzxUz+Fl03aSPI9QTypW2/dz0qKNw3SvOPZR
|
|
Mqin8VLKRcs3O4Cuk0w/MDjt1NBtHY6O2IIHY1pxgFaETIRwMkjtVSUEk4570MlFW5bap6dKzWm8
|
|
1tqH8aY+hp2FvGoGayNevVt7/ap4xzUvYjqTLtvLPcvJxSaVcyWsxTnFZlnT2t15xHmCtOBYwQy4
|
|
B9q7cPO+jPPxFO2qLEj5HWo42+aus4HpoX4W4FTF+KlotbHII9SFuK0MUNZqiLUDE3UbqBBupwag
|
|
Bc1DefPbyD/ZND2KjujyPWlKzuPesRZjHJXms9lMuw3StjnmphKDSLTJ7OfE3JrpbO4GQc9qlnRA
|
|
3LO82k5NbFvdADkjBoCSHyXIIIzgVQvdRigT7wzjgUzO1jHknlvG7qnp61etYFQDIpCZoqVijzXn
|
|
3iC8EmsOuaCGb/heR/s0ijkVv6fbxy3QMg5xmsnuX0Ldzut3+UYTPWk+2GJSe+M1pFtamcldalmx
|
|
1eO4XaThhWnC+TXqR2PHqL3maUJ4qRjxSEjj42qXdxVmaGs1MJoATfSbqBAG5p6mgAzTJTmNvpQU
|
|
tzzHXY83D/U1zF5FhjgV5r3Pa6FMsV5HWnLe7RhqBRdmTwagN2d2K2rPU1C5LAnPrUs6Iysbdrq6
|
|
f3gK0BrUKj/WClY05iM6xLOcQAj3NT29uznfKSzHuadzNu7NSBFjHNSm5VO9IRnajqoWMhTzXFtA
|
|
bvUfMduSeg702Qz0rS7FbTToQFwzjJqaGTFyfK5PQViyzUuFmuIdgGABya5u/vTaN5cnUHFUmLoZ
|
|
zyskwlgJweSK6zQdUEwVJeGr0aUrxPLxEfe0OrhPAqVjxWhznGRtUwatDK4jNxURbmkAm6jNABup
|
|
6tQAFqhupNtu59qUnZFwV5JHnWsHdIx96w5lz15rzT2uhRmt85xWbcxMnUGmZlB0bdxmrNvFIcfM
|
|
350mWjbs7YkDJY/jW5ZWW4jikWkdNp9mqYJFaJdEHHakUULu/VB1rLn1Ld/FgetMGYd/qWSQmSa0
|
|
/AemS32pfa7piLeLkg9z6UmQtz0W7uQ2cZx0A9BVzR7cAea6j2rPqX0L99KRat5A6Dk1wOoKZ52a
|
|
YfMORTYRLujiGWEq6/NWza2yKQVHNdOHerRy4laJo6TTnbbtb8KuM3Fdh5z3OJjbmpt3FaMxAtUZ
|
|
agBN1GaQBzTwaAAms3VbjERUGsa07RsdeFpuUuY4jUjljWTKK4j02RE4IpJYFk6imQkVl0xWarsO
|
|
mAEcUi0bNnZBR0rWtoguMCkUi21wI161mXuocEKaYXMS4u+pY/hVCSWSY4HT0pEmlouiSahdpEBl
|
|
mOceleiwWcNjClvHgJH97Hc1EmVFFi3Czy7mwIl/WtJbjP7uLgd/apQ2VNVvtsBhiPzdK5S4nAuR
|
|
nqOCaTGi9pcytPlU+XpmumtWII44rah8ZjiNIXRuWeNvvViQ/LXpJWPJbu7nCRvVkNxVsxBmqJmo
|
|
EPiXca0YLMuOlJsuKuPlsSi5IrNuG8s4HWs5VEkbwoOTKsk+FJY4rC1K53k1xTk5O7PSpwVNWRzt
|
|
4cms+WpKICtSLTETQj5q0YeBSGiys23pUguGxQMq3E59ayrm4x3yaAKiRtO2WPHcmhruKFxFajzZ
|
|
ScA44qRHoXhuMaLpxaUg6hcDLMf4F9KlhuDeXGASIl+8azZslYma68y48m1+7nFW5rtbRNhb5z1p
|
|
iMKbUg0zuW4A4rPgb7VdKXOMmpA7HRbMS7nUYiUda0lkQOBngVrS+JGdbWLRt2bAx5BqeQ/LXpnj
|
|
PQ4GJ+ashuK0MhWaoWcA0AaOmASMK7jRNPWYBmHyiuepO2x10qfcv6vYxCzYqoGK4HVYVTJrmb5l
|
|
c6oaM5TUJ8EgGsG4kLNUHT0M64OaqMMikSRsuKbnFMRLG3zVehOaGNE445NNlnVFpDMu6uie9Vo1
|
|
8z5mOAOST2pDK91cNN+5tsrH3PrW54a06KxT7fdrlh/q1Pc+tJ6IUdZGvHPLezMcnBOWbsPap5r3
|
|
ylFtbdT1xUWNWzU0/Zbwlgfmx8zGsHWtRHmMqE59aAMyNifvHPc1f0gtPdqkY5JosJHeNci2tktY
|
|
euPnNY+oXWZEVJNrZ9aun8SIq/CzodHuriIokhDIR1ronbKZr0o6o8ipoz//2Q==`,W0=`
|
|
/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAsICAoIBwsKCQoNDAsNERwSEQ8PESIZGhQcKSQrKigk
|
|
JyctMkA3LTA9MCcnOEw5PUNFSElIKzZPVU5GVEBHSEX/2wBDAQwNDREPESESEiFFLicuRUVFRUVF
|
|
RUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUVFRUX/wAARCASwBLADASIA
|
|
AhEBAxEB/8QAGwABAAIDAQEAAAAAAAAAAAAAAAEDAgQFBgf/xABDEAEAAgECBAMECQIDBgUFAQAA
|
|
AQIDBBEFEiExE0FRBiJhcRQjMkJSgZGhsWLBJDNyFSVTY3OSNEPR4fAHFjWCokT/xAAYAQEAAwEA
|
|
AAAAAAAAAAAAAAAAAQIDBP/EACARAQEBAQADAQEBAQEBAAAAAAABAhEDITFBEjJRIhP/2gAMAwEA
|
|
AhEDEQA/APqYAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAKNTq8OkxzfNkisQC8eb1XtRNbzXT4q7eU2nu0MntRq/D8StMccvW29ZmdvgjsTyvZjxOLj
|
|
+s8WLxn8TFPXs6Oj9oct7c14rkxz22nrB2I49KOdTjelmszfmpMeUxv/AA28OqwZ4icWWtt/SUi4
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAmdo3nsPNe0Pt
|
|
Fh09Z0+DNWL7+9O/7A3eJcZppsV5raI27esvH6jX5ddM25p79Ilo59VbUZOe2Tm/PeGvfPfT2iKR
|
|
PLv1+DO678XmW/a97U6TtOyzTbTF538/T9WjTNecm9a7126tqk3rSYxY5ta1plRZqZNXGjyZcPXl
|
|
mZmsx+qjBrsuO16xM7eXRt04JrdTltk5OWJnfaWf0a2lty5MdZnfzSn+WOHiOutFpjHa9e8bQ2fp
|
|
+alYy462pk7zXbuxjPesbRS0f6ZZV1ET1tErzXFLHo+A+1ddZf6NrI8PJHa1vN6iJi0bxMTHwfOa
|
|
zhzd61v1846utwniM6DUdb3nBaNrVmd9vjC/ZVePYirBqMWppz4rxaPgtEAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAItaK1m09ojcHnvarjM8P0vh49+a/eY8ng9D
|
|
h1fGM1rxjtGPfvbzdbjuTJxHX48cTPNltM/KsS9Dw7S49Jp6UpHaGe2vjz1y9J7LYK13vHWe7bj2
|
|
ex1tvM80ekuxW3RnW3Vm6P5jRx8H0+OYmMcb+bapo8GKPdpC6bQwtdHU8JpWkdJ/JweL6e23iU67
|
|
d4dubSqyVi9Zi0bwIs68XGp36TtEq7ZJmZmevzdbifCKWtbJinkt6eTgZPFw32t+sRurbWVzxs1y
|
|
Rv6T8V1NZNPtfq0seTm+Kevr+SZuxXjvaPiV8N4viycto9HseG6+uu08W6Rkj7UPmFck1tE1nlmP
|
|
Ld3eA8V8HVVi1pjq6Ma/pnqce/ERMTETHaUrKgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAADW19+TQ5p/p2bLS4v04Zmt5VjeQeJ4bjnLqsupv+Ka1+ERLv4reTmcNxcuC
|
|
vy3l0qdI2hlr66sT02ot0ZV7qqrInruzrVZLGSZ37JjqgYTG0K5lbaFVhDT1Ub456RPweY4hixWi
|
|
eSdpjvD1eWejz3FNHWYtkpvFo9EIseb3tS3SerOms22rfpPqZKzvvHSYUz70TExG6Gdbs2rljeJ/
|
|
Mx5L0vEzPaelnOi98c9J2bFNTFpit47+a+PVUvx9T9nOIfT+GV5p3yY/ds67wvsXqpxau+G09Lx+
|
|
r3TqrEAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADV4ljnLw3U0jvO
|
|
O0fs2lWqyUw6XLkyfYrWZkHldBEV09eveG3Fq1mI3jd4vPrOIaid8G9MP3Y38k6fNrt/rMk9Ou8s
|
|
tfXXn49rGWInuy8SO/k5Gl1E3rG/fzbOe94wTy99mbRvTrMOOvNfJWsesywniukrG/jU6fF43WYN
|
|
TmtEeJtEQ06aSmK2+bNtEd+qfSO17unF9Hmvy1y13XWyVmN4tExLxVK8PmNq5NrT58zawam+m/yc
|
|
0Xj8NpRYSvQZ7xEOdqI3rPozxayNRXe0ct/ON03jmrKB5nV4q1yTO20Obmv4c+cx8HoeI6WZpNoj
|
|
q83niYmYscU0r8aJ6T1n49zeJ+Meqm1drb9J+Kd5p136StGVem9l9TbHxLDFp7W7+sS+q1nesT6w
|
|
+PcAzVjiGHftzQ+v4f8AJpv6On8jH9ZgIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAABp8VrW/C9TW0ztOO3b5Nxp8VmI4bn37TWYB8f1HFtTfUfR9FWJmsdZ9I7MtJxDX5s
|
|
d8ta1y0xzteaR2277rcuhycP12SceLxMeWNpjttHwlu8I0mfQ1y+D7k5YmJmY36T36Ka43z/AF1t
|
|
cI1ds+qxVj7/AEej19PCw9HJ4NoK4OIU5Y35YmZdzVTGebVZabx5jJS+Tmns81rNLm1Wrzc9rVw4
|
|
Yibbem72mXTTS0w0M3BvEta1bWrM95ie5EanY87wXgNOL6XPfxraXLhra/W28bR/dzYzarBqJxRe
|
|
bzE7Rt5vWU9n8mPHOGmS0Ypnea1naJb+k9ncNLR7u2y/WcxXO4TOoyUrN6zD0FaW5Y3hu49FiwUi
|
|
KxCvLMR0hlW0jn6ukWw3iXjOJzbDlneOj3GaN6zDzfFOH+LE7SRGo83XNSZ2lbG2/WfdlvaT2cy6
|
|
rNFInlrv1mfJ37cK4PwTTxOoidRm2+/2/KFuyMp47XB4LivXiunrH2b2iH2qn2K/J8x4fGDNxTSZ
|
|
9Nh8OviRvTyfT6xtWI+DeXs9MNZubypASqAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAOZx6/LoOWPvWiHTcf2hiZ0e8fc2mf1E5+vP/AEeuSd7RC2uKtI6QjHfeINTfwtPf
|
|
Jvty9WPfbt/lucP03gxfJf7d/wBoReYpm97zaNeLb4Ims9Nt94auDjem1Wo5PFi1onylS+1o7l8V
|
|
bxvtupjDMdNkYtXS1+Stt+m63xImEJ4xjHER2ZxMUjeUTO3VRmydBbjLJqPi08mbeVOXJPq1sl5Q
|
|
Vbkz9+rRy35rxHqzmZlVEe/Ez5LRlW5iyfR6zffaIjq1OSNZps2a21rZInafSPJhxGMl9LStLRWM
|
|
lorM/A4dkrWbYfLZC2W/7K6eubX6b4RzT+W76K8b7G6X62cu3Sten59nsm3j+OXz3/0ANGIAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA0OIYfpOHPijvNNo+fdvtXJO18k/
|
|
/OwPFYbz2ls3jx8VqW6xMdWPEdP9D4lkx/dt79flLLHbkxTPwY6nt2512ORTRzE2x4/dpE7cvkme
|
|
E4IrW3hRMxO8THRtU1FKWtvtvK2upx22rzRCtXkqzh2jtF7ZbT122b01ndnpuWuP3Z3+Ky20qDVv
|
|
fauzVy3mejZzNK8dVjqi87KLRLYtXruqvXzkQp7Qoid88R6rcl+WGlW0/Sa22mfhCZOq2x082ix6
|
|
jkm822pO8VrPdr4dNObVeDo8XW3uzMbzK+mvxT7szE27cvnu9j7PcNjSaXx8mOIzZevbrEeic5tN
|
|
+SZnpt8J4fHD9HXHO3PPW0x/DeBtJxx29vaAJQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAKNRim9Z5e89Nl4DzXtVh5babURHrSf7f3ec1+qnDorWrvvt5Pccb0n0zhmWk
|
|
Rvevv1+cPE2rGTFNZU26PFfxwa5dVkjelI2772nZnX6bbrEUq3o0d678u8wmuDL2ittvVjXdneeK
|
|
cGv4jpJ6U56+kS7+j118+GLXpakzHaWlp9NNY3tv+bbiYiNoQy1y30uyZJlrWmZnuym6q1iIJnop
|
|
yW2Te8bdWnnypQqzZOadokiIpSZntWN5lrxki19vNRxrUeBwnNNd+fJEY6/OejXLn3Xe/wDp9wyn
|
|
E8uo4lqqxblv7lJ26T6vpD5X7G8QycKzeBMbzMRM1/FH/wA/h9QwZ6ajDXLitvWzRgsAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAeL45w+dDrZvWv1OWd4+E+j2jX
|
|
12jx67TWw5Y6T2nzifU+rZ1y9eHwzDYxxEy18+DJodXfT5o96vafWPVbjyxDn1OOzHudbM0rt2UW
|
|
iI69mVtRXZq5tREb9VUoy2iIlRbJ0UX1VZ6btTLrI7V6yk62M2oisT1c7JmtkttVMUyZp6x0beDS
|
|
RWOvdKijDimvWd3G9pNRMfRcNfvZOb9Hpb0itJeP47k/3hgjaZnbaP1XxWW3T0movbNS0W645nbf
|
|
0nrMPpXs3xamoxdJiLbe/X1n8Uf3fKsOTw4jbaXo+EarJhtGTHMxeJ6xH7Sti9Zaj6x3HM4NxXFx
|
|
DS1mtoi8dJrv2l011QAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AGjxLhODieOIye7kr9m8d4eM4to9RwjPXFa0ZIvG9bR0fQXmPbDFvTTZPOJmEWS/V8bs9R43NxLL
|
|
G8eFbePg1bajU5/s0l1ceKLx1hbjwRE9mOpx0y2uRTSZsm3PMw2aaKtIjo6kYo9EXpET0hVLXxYK
|
|
xC6MZvyx1lFs0RHfaPiCnU12pLyHGNDbUajBekWma2npWN3p8+opa20e9LSyZLxExTlpM+vdOdcZ
|
|
a9tPS8MyUvFrzWlI6727u1pYxYrbVmb7x+TQx6au3Nqcl7/0rcmW9axGnwZJj1novmxnZXV0fFp4
|
|
ZxLBPgTGK8xzXr5fOH0bFlpmxVyY7Rato3iYfNuG2x56Wrqa8s2jz+7Lu8O12bS6jkwzN6THNNI6
|
|
tvrN68Y4rxlx1vHa0bskAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAA4XtTTm0OKfTJ/aXdcL2pyRGjwU362yb7fkJz9eTxxyZJjyltRXzUZK7TFtl9Lbwy06YzrHwa+
|
|
fJFd/wCVt8m0bQ0eS2qzcm+1K/an+zNZFL5M1pjFXeI72ky48eGnPkvNp27+TPU6nHpMfLXaIjpE
|
|
erk5dRMxOfN1mPeisfshW1ne1a1577Y6x5R3U0zze31FOWI6ze0byU098kRlzbxM9qrMlPDpyRMR
|
|
Md5Vt/Ihp5898mWZm1pjftE91uCt7fCI7dWeHDEW3t723l6rslqxWZnasR+SYhFbzhnfxJ2jyeq9
|
|
lcGXWZcmW0zWKxHLaI7794eJx5fpfEKabT8t8l5isddo3l9S4VjrwrRUwzSJt3tav3pdOL6Y6dXD
|
|
j8HFWm+/KsU4NRXPvtWazHquWVAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAa+fXYNP9u8b+kdZBsDkZOO135cWOZn4y5Wu4xqctbe9y19Kp4njt6vi+PDm8DFMWybbzPlV
|
|
5PiGtz67UxbNbeKTtWIjaIXYpnwuaftT5tXJT3vmi1pMsrU5qIrG1V1a+5DCa7b9GFbRr5J6Wnbt
|
|
Cu+Wmk0m8956z8ZWZNorbfzcbX5rZslazPux3hUt41NTntktObJ13+zX1bek01r4/HzVm0bxPXy/
|
|
+bNfDgjVa2uOY92kdfg6ufJOKvLXtttVVSqbcta2vM7zXtHpLQy5ZtMd+vWd+7Zy3mdJHXra3f0c
|
|
vUarw7zFY5rT2hH1Lavnrgx81p3U49Pk4nE5L35MO/StfNRXR5tXnrS8W67WvfyiPSPi7uLHFK1p
|
|
jrtSsbR5Lc4RzsXBaYreP4l45esRD2HD9fnw6evvWvO3Tfr0aGk0U55ra0TFInv6uzgrXFXlx0i0
|
|
77RPlC83Yj+JW7oddqr6vHzTTw9/f6dod+L1t9m0T8pcbFSmPHER3892W0zPuz+jSbVvidkcqmfP
|
|
Sel7bekrI4n4dZnPWIrHeYnZee2Wpy8dEaml4npNZblw5qzb8M9JbYgAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAABEzFYmZnaI7yCXL1XGa0jJXT0571nbee27DiXEprp8nhbxG20W8
|
|
5cbD0ikfnKO+urTPvjoZdXqctdsmTaPSvRpWmsdZ6yztfaGplvv3lWW1tyRlz1x0vkn7Vo5atTNe
|
|
Y0+1o79V2KsZsvX7Ne5mwxnyTNvsx2iGneM/rCdRSuOsTasTt5kRFtpjqmOH4t4nk7estiMNa97R
|
|
Hwhna0iuKTEdmGWa4672nZtRele1N59Zlq6vLOSsYorEc07qcW65euzRvtXvPZy52naZ7ujr6fXV
|
|
rWdukREK8+njHgmZmPc67bq6ivVWhxxgxZLztNrT1mZ/SP4VZs0zaOvfp84WUtNsXLvtv3699+rU
|
|
z7+Jtt5qURqMnPpctaR1rMSw4ZoK57eNk6xHaJRh97Ltt7lo5Z+L1HAPZvVauZ2nFTSzMTzeJEz8
|
|
to6xPfvsZntPZ9rXxabmxzefdrv0j1dXh/BcmstW1qxTHHasR3+b0GPhGl+kWmd64dNEVjf73T7X
|
|
y8vy+Ddx6O3iRakxTH5RXrMw1/lX+3Itw2MFIraN48qRHdZi0cUjmmPen9noox1iO0fNzdXEYrTt
|
|
stcmd9aX0bJ+HePmiKTitO8TMLZ1cVjrMfqpz6ys4pjfrPRWZ9rXXptUit6zO+23VyaRHEc05L1/
|
|
w9J9ys/en1ljqdVbwYw452tlnl3jyjzbmmiMeKtYjpEbLeTXPUU8ee/+qjJpsV5rbkrFqzE1tEbT
|
|
DpYNbW21Mnu29fKWna0KbqTdjXXjld0cvQ63ltGHNPSfs2n+HUbS9c2s2UASqAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAOVxPWe99HpP8ArmP4b+r1EabT3yT3iOkesvMVtN7za07zad5l
|
|
XV5GmM9vVfEstvDx0jtaVVMlq+UJ18b5cMRvPeSuK87bUt+i2Z3PtG7zXpjkzXt6R+TXyTMzvM7t
|
|
ydHqZ+zhv1+Cv/ZuqvPTHMfOYaTMil1a1K2vHSLTELq2v+KWzThGo84rH5rq8JzedqR+ZeI7WnOS
|
|
34pYTafWXR/2Pln/AMyrKOCWnvmiPyR6O1y9585lhWJvl557Q6eo4T4dYiMvW3b3UanhldHpJtGX
|
|
e09unmjsT7eb1l4trI2t0hsZfrdNO0bzy+nzU20/+NmkzO9esz+TZxWis9dttvPv+Tn21jjaW8zn
|
|
26bTG3mp1M/Wzv3t0jyWXiKZJmsTERaZhXXDbNl8WaztWenxZLstPp5pau8frDtVrNMM5cfTfpMf
|
|
3aunxxbes9d/R09Dp8ebJi09ptFr3jtt2WyrW9wy1Jx132mK+Xq9PotT0iIU19ntLtExa3T47T+q
|
|
6nBaYvsZstZ+cT/LeMnUi0TXffo1s2m8Ws2/OIMWk5Jib5L328rS2t94Sh5TV4ppklpW6PT6rh+P
|
|
NbebTHyas8E081mZy5P2W6OFhjxNTE/hr/LoRO0Kvo9dPqctKzMxEx1la5t3tdnjnMs4noievcrO
|
|
yZjeFF1OSnNV0OG62cn1GWffj7Mz5w05joovzY7xes7TE7w0xrjPeex6Ua+j1UarBFu1o6Wj0lsN
|
|
3JfQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACrU5o0+nvlt92P3BxuM6nxNRGCs+7Tv8
|
|
2hToxm1r3m9utrTvMsonqyt7XTmcja0u3O6FMfi5t/u0/lzdJM81p9O3zdvHTwsUR5+bfPqOfX1h
|
|
dqV+3O7bs1+T31oqmI3TEM4rvCdkDGIIhlFd2daboS0NXG2bD6bufxXU1vlmu/u4us/N0+L1tTSx
|
|
kr9qk7w89j1FNZMV3jxLzvaJ8mer+LSOZqK2xZotbvljfr/89U453rXt9lse081xZtNjx7TGKu0t
|
|
DHlrevSevaN5Y6+tJ8c7VRNMt63n3ub+6/R54rERMztDYy4a5omclYmfxKcenrjtHLvtPrCnVmdb
|
|
eFe3JXmjy6eS/DrMuLVYsta9Mdt++6qLxO+0dEc8UmInr18iUfReHcXrqccb9Z27Q61Lb13eJ9nc
|
|
1Z35rTvE9avY4bTkpG8xEfB05vYxqybc07R281naGMREdoT5JQqy9mply7Q3bV3iXG1eXw7TWSka
|
|
c258t7+tpT5/BjT7MfHqndz12Z+M4lMMKyziUJJiN1WSu9fku23RaOgKNJqbaTU1t9yelo+D0cTE
|
|
xEx1iXmM1Nt3W4PqvFweDaffx9vjDbGvxz+TP66QDRiAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAOJxzU73rp6z296zsZMkYsdr2naKxvLyObNOfNfJbvad1dXkaeOdpvsc2yuZVzfbfqybutwu
|
|
s5s8R92J3dvJb3tnO4HSMegtmt3nfZvYp8SZl0z45NfSK7onH1bNcfRFqnUKJr0Y7dVtq7prjEsK
|
|
0XVpEM6028mW20IHK41aPo3J6zs4ODhdcvPnvExFevNXpMOrxi/PlrTee7PLX6Pwa09uaNlKtHg9
|
|
dM3z5d7ReOu02nu0JzZMfblrv5R5uvrcdImZ26T1mYhxs1Os7RH93PZ7axuafNfLitvbaYU3yZYt
|
|
PXs9NwHhui1HBa5LVicsb81onrEuVqNNSuS8Y67dZ6xPZa59Il9uX41vEitImZme3q2Kxbxora0T
|
|
Md/ROSa4Ztkj7c9OafL5LuGYubmyX3iu/TfbdSfVnpvZLT/XZK233+Mbbva1xRXyiPk8pwbH4N6T
|
|
adq5a71n0tD1WDL4tPe6Xr0tDpz8YVnJHWEXYxbqlBedoef4tW0XraO09HdyztSZcbUz43C+ee9b
|
|
SVMaeOfqq7+jGckQ1Yz7+7v2RN/WXPXZPjci2+2yyJaVMuy+uSJlA2d+pNoVRbeDcSxyTE+TDDlt
|
|
pdRXLTynrHrDOyiyZeVFnY9TjvXJjres71tG8MnJ4Nqt4tp7T1jrV1nRL1x2cvABKAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAHJ49qfD09cNZ97JPX5PPw2uI6j6Vrsl/ux7tfk1mWr7dOM8iLdm
|
|
vfebREefRsWldw7SxqNbWbR7lPesrn3Vteo7dYjDpMGCvfbeXQ0uLlxRLRxROfUc34p6fCHYrXlr
|
|
EejqrjY8uzCYW7MZjdVKqK9VlaxCYrsnYExBMRMJRPZA8/xPHtmpP9W2xx76vhWOInvt/C7ike7N
|
|
vwzE9kcapGfhlevTaFbFo8RqJ5vy8/RoW09ek0msxHfp3dzNoLzp4zUmZpMbT8HJyYJi20X2n0lh
|
|
ZY1li/RaidBF4w2mK3jrHaFGp1lN+tptPp5IjBkid5mIp16TKu0abBPv33vPlM7z+iPdFNcWXU5I
|
|
tkrNce/b1W5db1nTaf3ax9q0fxDW1ebNk2phty1mOu09VOm8W19orEz23j1TwfSeERFuEYMddptW
|
|
d43dvBn21eKJ75KbW+cf/JcTgMxXTb3nbljz+TpcPmc2uyZO1KRtVtGVdi0bx07qJnllsRO6rNTe
|
|
N4XVamsy8mnvPwc3R2jPwe8TPbdlxXNOPSZfhWWpwO85OFzv57qrODkzeHntSe8Sn6Rv0a3EZ218
|
|
8nXekfr1a0ZLVnqx19dWb6demXybOO7lYMvNMdW9S/VVLo0us7tPHdtUtEwJiZU3jq2Jhham8CVG
|
|
PNODNTJXvWd3qcWSubFXJWd4tG8PK3pPd1OB6veLaa89Y61/u2xfxh5c/rsgNHOAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAANLimq+i6O0xPv392rdeZ4rq/pOqnlnelOkIt5F8Z7Wj27I2I6sb25YY
|
|
V1ImY3dbQ08LRc23vZp2j5OJG+XJWle9p2h6HHtbJXFT7OOIpX+7TxT31j5rycdTh+Dpz+XaG/sw
|
|
w18PHWseULN2trBE9UcrJKBhFU7JAQi0dEomegNDUYovM7x3jb5tO1ZvpbaTLtzRExWfWPJ08kbT
|
|
Ex5NXWYYyV5omYtHWJieyeDzuizfRs19Jn6TM7Ru1uMcJxZqTkw+5f4ebqa7SV1MR4tdrx2vEfy1
|
|
axqsNOTLjnLXytVXi3Xj8+nmsxTLM16d5npPyUzpekTtSK+U7vS6vQ/SYmK1vWPS1HOn2dvvvvE/
|
|
tDO5XlcO+LbfHSd/W3o6/BdDOXPTnj3Kz38rS6Wm4FNrRyRzTH3p6RH/AKvR8L4dXSzE3jmtHn5I
|
|
mbfqLV+m4dbLSsZInHjr3iI6zLpYaxS01rHuxHRHiT9mv6s67Vj1aqL6326MrWiYa+/Q54BxPaGe
|
|
XRZpj8MquB4+Xg8zPnB7SX30to379GxpK1xcHiKz5IS8xr8PLPixH2bftLTy05o6dHYyVjLhy0t1
|
|
izjZa3pMVv3iO/qz1G2L+NbSajbNyW7xLsY8kTDz+fJXFqKZN4iZnafi6WHL0iYlStI7OO+7axW2
|
|
crFl7dW9jvE9ULN+J3ZbdFGOy+AYWpEqN7afNXLj+1Wd23KrJVMvCzseh0+auow1yU7WhY4fCdV4
|
|
OadPefcvPuz6S7jol649Tl4AJVAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAV581NPhtkvO0R+4NPi2
|
|
r8DB4dJ9+/7Q83Po2NTqLanNbLfvPaPSFDHV66sZ5ET0hRknyW2lTtMyouz0c8usx2n7s7vScKwx
|
|
zc1vu/y85p+maJh6Th+SOWeveXR4/wDLm8v+nX5mUWa9bbrInolmu5jdTNkxYFk2Isr3TuCzeGMz
|
|
+THdEyDDJO9Ja823rt2XWnya946pGvktDXta0ztWu/ybvLE9dkcoOf4GbJPWK1j49VmLh9JtE33v
|
|
Mevb9G7WsW8l1ccREISophiJ2jpDYpijbaOjOuOJ8ujOdqxsgVcsUjaETYvbaFFrgu5lVsm0yUtu
|
|
ryg43H5m+GIj1XcJzePoL4pnrWGtxmfchr8JvfHS1622if3QljzTTLes+qrNjrkiYtCzPMxnm095
|
|
YZJ6boS5teB49Tqscza97VtvWvlv8V/FOF34RrIxTM2xXjelp/eHoeA6XnzReY3ivX/0dfivDcfE
|
|
9HbDbaLx1pb0lOs+jO7K8Lis3cN+0NKcd9PmthzV5clJ2mF9J9GHHVL108dm1SznYr/Ft0tuhLb8
|
|
mNohFbMhLWy0mJ3rPXvDvcO1karBG8/WV6Wj+7kWrvDDBlvpdRGSnbzj1hpjX4z8mOx6UYYstc2O
|
|
uSk71tG7Ns5AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACZ2jeXneJ62dVl5KT9VTt8Z9W9xbWclPo+O
|
|
fft9qfSHEU1pv48ftYST23ZTDC/p0YtlVuvVjMbM5+LCZjYGWGdrTPxiHY4ffaf3cjTxz1v6xMS6
|
|
Olty2iXVj/Dk8n+ndrkhnGRo1v8AFdW3RCrZ5uiYsqrboncSu508yjmZRYQt50TfowYTbYGVrKrT
|
|
uTZjvukQnYhMIGVY2ZxPVWyrHVCWzXpVXkt3TE7Va+W4K7X3jv1auTNy3jdba0RZpamfroQN7Hk3
|
|
6wr1GTaN2OOJiu6Mu98NvgDi8Wy74d/yZ8PiPAiO2zU4nb6qIn1bugjfFE/ASp1ke9u15mbbRDZ1
|
|
Mb823kx0Ontn1OOkedoJCvT8I03gaKsz9q/WW+isRWsVjtHRKyrhe0XCfpWL6Vgr9fjjrEfeh5fF
|
|
feH0V5Dj3DPoOo+k4a/U5J6xH3ZZ7z3228evytOk7NvFbo0cdols47bSybt7HbddHVqUs2aW3Qnq
|
|
xVeu8LILR3SlZw3V/R8nhXn6u0/pLuPMXjeHT4Zruf6jLPvR9mZ8/g1xrvpz+TH7HUAaMAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAABRq9VXSYJyW79qx6yvmdo3l5viGs+maqYrO+OnSvx+KLeLZz2te1rZL2v
|
|
ed7WneZYWnZl5K72YV1xEyxmeqJljzIEWlVkszvbZp5soN3h2SJz3pP3odCnuWmPRxuERfJrZmtZ
|
|
mtY96fR28kbX3dXj/wAuTyf6bmK+9YX1s0cNtm3Sd4LFY2K23W1s16StiUJW7bp22RW3RluBuruz
|
|
mWEgrmCGWyNkoExKE1QlPmsqRDKeyBjaejWy2W3ttDUyz1QKslvehVqKTNosyyTvELabXptIJpaP
|
|
B39Ia2mz+JGpr51jdZefDx2hzuHZObNq58poJaGtjxJ2+LoaKP8ADRPo5+T3skx5OhpOmC0fBNQ0
|
|
5yTbn+bt8A0u9raiY6RHLVwY62mI6zMvaaHBGn0mPHt1iN5+aYVsACBXqMFNTgviyxvW0bSsAeE1
|
|
mkvw7V2w5Ote9besJx2er4rw2nEdNNekZa9aW9JeQjnxZLYskTW9Z2mJY7zz26fHrrdpbZsY7NGt
|
|
mxjvso1b9NmUwpx33XRO4K7VUTE1nmrvEx1bVo2VWiJE/XY4frY1WPlt0y17x6/FuPM0m+HJGTHO
|
|
1qu9pNVXVYt46Xj7VfRtnXXL5MfzexsALsgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHM4jxOMFJphmJv529Dq
|
|
ZLfjDjPEIx450+K3v2+1MeUOHSOWFc3nJkmZnf4yujpVlqunOeFpV2nctLCZUXRM7MJtsWlRkv3Q
|
|
ky5NmpWt9RnrixVm17TtEQnJabXisRMzPSIew9n+CRoccajURvqLx5/chfOest642OGcIpoOG2w7
|
|
ROW9d72+LQvXevyejcPUU5M+SvpLeOataraw2a0dLbLqTtK1G3Es4lVWWUSoldFtmcXUbpidgXzK
|
|
GEW3TuCUSncnsDFMMLSms9EC6J6FpVzbZE5ALy0809ZbFr9GtfrEoFMzuuwz0Ueey3HbaBLDXe7i
|
|
tMOfwWnP9I+NZbuttvhs1uBRtXPb4SDm3iIvf57N7Dbl0VrS5+XrltEd+Z1Jx7cNms9N4TURRw3T
|
|
+PrcO3WszEvZOD7P6aYiMlvu16S7y1QAIAABxOPcLnUY/pWCv1tI96I+9DtgmXl68Biy7/NtUu3+
|
|
O8HnFa2s0tfd75KR5fFyMWTdhrPHVnX9R0cd21S3Rzsdm1iuqs256wrmGcT0RYSx5d047X02SMmO
|
|
esd49YRE9WcdSXhZ2O1p89NRji9J+cei1xMc3wXi+KZj1j1dTTaqmor06WjvWW+ddcu8XK8BZmAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAMMmWmKu952UZ9XFZmuP3revlDTtzWnmvO8q3XGmfHb9ZanV3yxtWeWn7y4es
|
|
vPNtDqZJ6Ts5mppvdl/XXRMyfGvSNlu/RVvtOzLfoipLT1VTKbSpvfogRkvtDVyZOhkyvQcA4Dzz
|
|
XV6yvTvTHMfvK+c9U3rkW+zvA/D21urr789cdZ8vi9KDb45rejl8Rry6iJ/FV1HP4vXbBTJEfYt1
|
|
+UpiHM295bXsqrO9l8QkZ0lZEqqLeyBZHZLGvZkhIndADKJ3TMoqWQMZ6pjsxll2jsCLSrmU2lFY
|
|
36gieyu0LJk3jbsga0wdqzK20QpyztQGprL/AFMrOE05NLkt6qdVWZxNrSe5o9vWBLiUjnzXn0vL
|
|
q555dHt8HOwV928/1z/LpzXxbYccRvzTB+jucOwxh0dI22mY3ltIrHLWIjyjZKyoAAAAACJiJjaY
|
|
3iXleM8InR5J1GniZw2n3oj7s/8Ao9Wi9a3rNbRE1mNpifNFnVs65XhcWTdt47bnFuF24dm8TFEz
|
|
p7T0/pn0a+HJux1OOrOux08d1ndqY7tillVkzExLOk7yd4YxGwluViJhE45raL0na0dtlWO0+bZr
|
|
1TKi+2zptZGTamT3b/tLacvJjiY3XaTWdYxZZ6/dtPm1zrv1z78fPcbwC7EAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABhkyV
|
|
xUm152iAZWtFazNp2iGhm1Vss8uP3aevnKrNntqLdelI7VRHRnrX/HRjx/tZREVjZXeybW6KbWZt
|
|
pCZ6S08tN7Nmbb7zCrJtyoS5145bSx5mWafelr3tsKmS/o08uXyhlly7RPV2+AcBnPNdZrK+53pS
|
|
fP4ytnPVda4y4BwHxOXV6uvu96Unz+MvVxG0bQRG0bR2G0nHLb2gCUDX12LxtFmpHeazt82wT1gH
|
|
mMN4tWs+rcr2aEV8DU5sM/cvO3yb+O0csLUTSdrLphRE8tlkZI7Atr2ZMazDJVKTYSCawi7Ksq7z
|
|
1QERvLK3ZGPrKbyCrbdnMcsbeaa18/RhvvM7oGEwTG0JmYYTIML22a2e28xELM19oURPNO4lOem+
|
|
n3ZY5+prVnMc2GYU4/L4A0a15cNf6rz/AC6fC6+NxCPOuOu/5tHJTbHj+F5/l1+BYumXJMd9o3/d
|
|
MRXYASgAAAAAAABhlxUz4rY8lYtS0bTEvH8R4ffhmo6bzhtPu29Pg9mq1Gnx6rDbFmrzVsizq2df
|
|
zXkMWTeIbNL7tbXaHLwzUctvexWn3bmPL8WFnHVL326VZ91MfFVjvvVlz79kLrcf2m7j7bNHH3bl
|
|
J2SirLQoy4t1++7G0dBC/RanxI8PJPv18/WG241+alovSdrV6w6mDNGfFF4/OPSW2b1zeTPL1aAs
|
|
zAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAVZ9RXBTe3WZ7R6iZOpzZq4ac1p+UermZMl89+a/byj0Ra9815ted59PQ32hlrXXRjH
|
|
DpCLX6ML5NlNsm/ZRqstfdXzbsZt06sLZNvNB1Za8RDWyZdo7q8udq5Mu/mIMt4md2lmy7JzZuWJ
|
|
dHgfBL8RvGo1MTXTxPSPx/8AstJ1XWpIs4BwSdbeNVqq/URPu0n73/s9hEREbRG0QUpWlYrWIisR
|
|
tER5JbSccur2gCUAAAAPM8Sry8Uyz67fwuxbzVPGsE49XGbvF42V4M0TEL33ERnktsxpk3sumK2j
|
|
admFdPFZ33VS2Mdui2J3UU6LYlFSsN2O5NkCyJ6K7T1TEsbAsxdpReerKkTFGMxvYEz0rsqtbbpC
|
|
b2VT1QEzuwtbaGUxspuJU3neWdKoiu8rq12gCI92YatLcublnzbEz1aOptyZqTuDHLfxN6R0+t5X
|
|
qdJhjBp6UiPLeXl9NSMnEKxHa1+bb8nrlvxUAAAAAAAAAAABTqtNj1eC2LLXeto/R43VabJw/VTh
|
|
ydY+7b1h7ho8V4dXiGlmvbJXrS3xRZ1fGv5rzeHN02bEW3cys3xZJx5ImtqztMS3MeTeGFjqlb2O
|
|
8btql3NpbZtYsnSBLeiWfdTjtutid+ghherHS5p0+f3vsX6T8Fkw181d4lMvEWdnHaGnw/UeNh5L
|
|
T7+PpPxbjdyWcvAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAo1Oprgr63ntAmTqdRqK4K9etp7Q5d7Wy2m953lNrWyWm953mVd77R0
|
|
Za1104xxlN9lV8qnJl2a9s3xUXX2ybsJyRDWtl3YWydEC+2VRkzeW6q+T4tbJm+KRdfK1cmWZnlr
|
|
vNp7RC/R6HU8SycmCk7ed57Q9ZwvgOn4fEXtHi5/O9o7fJaZ6z1uRyOEezVstq6jiEbV71xevzer
|
|
rWtKxWsRFY6REeSRrJxz22gCUAAAAAANbX6aNVpL0npMRvWfSXlKamsRMVvXm+EvZXjmpaPWHzfL
|
|
oNRjzXicfWJ8phfPxFejx72x7xMzK+sXiNoiXlq+Pi6fWV/VfTNqfLJl/WTg9Pji8R70LqvMV1Gq
|
|
j/zcv6yz+lanzzZP1lWpelTET6S81Gp1P/Gyf90s412rjtnyfqql6asREdWM9+jz9eJ6yP8Az7uh
|
|
odZqMt458tpB1JvEViI3/RhzRt13/R1MNaziiZiJn5K9ZNceKZiIiQcu/WekT+iYrWI3lzdTrs+8
|
|
8uW0fJzcur1Np/zsn6g79phVaIeetqNR/wAXJ/3SwnUaj/i5P+6UD0ldonum161h5mNRqP8Ai5P1
|
|
lNtRqJjacuT9Qd22WN5aGeZyZd/KHJy59RHbLf8AVq31Gp/4uT9ZEvS8Lr/vSs2npzRtL1z53wK+
|
|
oza/HW2XJNd99pmX0Rb8VAAAAAAAAAAAAAAcHj/C5yV+l4I9+v24jzj1cLFk8nu5jeNpeW41wmdL
|
|
knU6ev1Vp96sfdn/ANFdTrXG+eq1q5F2LLtbZoY8m8d11bbSydErsYsm+zZrO/zcnBm226uhiyRK
|
|
EtrvCrJDOJTeu8A1MWX6Lqq5N/dnpb5O5ExMbx2cPNTeJb/DM/iYPDtPvY+nzhri/jDy5/W6AuwA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAa2p1UYo5adbz+xbxMlvqJ1OqjDHLXree0ejmzNrWm953tPmTPWbWneZ7yoy5YhjrXXTjH8s75N
|
|
mtkyxt0VZM2/m175N1V03yTKubMLXVXybeYLLX2VXy7eam+b0bOg4VquJW+rry4/O9uyZOq3UjVm
|
|
9r25axMzPaIdvhns1kzbZddM0p5Y47z8/R2+HcF03Doi1a8+Xzvbv+TotJnjDXkt+K8ODHp8cY8N
|
|
IpSO0RCwF2YAAAAAAAAACvUZYw6fJkntWN3k8dfHz2vLucdz8mkjFE9bz1+UOZosX1UzPm0nqI/W
|
|
MYo9FlcPNklfFGeH/NshLGun+Cz6PtHZtVZWlRLS+jxPkRpIn7rdoupHTdA5s6SI+7H6Mfo+32Y2
|
|
+To3neSIiZ7A0IjPXpXLePlMotGW3272t85datKzHZjbTVnsDj+FG/2Y/RlGP4R+jo20u7H6N1Ql
|
|
o+H8I/REY957R+jpfReiK6eOYHLtj2tttH6KrY/6Y/R2c+kjeJiFVtLG24hxpw7/AHY/RRkw9O37
|
|
O99Hrt1YX0tfOBLjcGp4XF8c+u8fs9c4dcVcGemSI61nd3IneN1orQAAAAAAAAAAAAABFqxes1tE
|
|
TE9JiUgPKcX4RbRXnNgiZwWnrH4XPi28PdXpW9JraImsxtMS8pxXhF9DecuGJtgmf+1TWW2N/la1
|
|
L7N7T5e3Vy6W3hsYcvLbqzbO9jvvCzvDR0+XeO7crO6FmGSvRThy/RtVXJ92elvk2rRvDUzU7pl4
|
|
izsd2J3jeBpcNz+Lg5LT7+Pp+Xk3W7js5eAAgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADs0NTrN96Yp6edkW8Wzm6+LNTq4pvTHO9vOfRoWtt
|
|
1mes95YWvs1s2fZldddOczLPLn2ju0MmebT3YZc2/mpm3qqllN1drsbZIhr3yzvtHf4AsvlYYseb
|
|
V5Yx4KTe0+UQ6nDvZ3UazbJqd8OKeu33peq0eh0+hxcmnxxWPOfOfm0mP+steT/ji8N9mKY9suum
|
|
L37+HHaPm9DSlaVitKxWsdohI0Y22gAgAAAAAAAAAABXnyRhw3yT92Nwef4xm8bVzET0rPJH5d12
|
|
CvLhho3rN9RWs9Z23n5y6O21YhrVYbdGOCfrrLPJRpv863zVS6FS09SvZj3lVZZRdPSqmnSWdrIE
|
|
ebOkK4ldTsgW1WKqd1oMZhEVZyRAImOjGI6rJ7IiATNd46qL02bHkiaxaoNGY2n4ImPgtyV2n0Vo
|
|
Gvlx7x2beiyTk08RPevSVUxux00+Fn2n7N+n5rRFb4AAAAAAAAAAAAAAACLVres1tETWekxKQHlu
|
|
L8InR2nPp43wz3j8P/s5dLveWrFqzW0bxPeJeV4xwmdFec+CJnDM9Y/CrY1xv8qvTZ+WYdbDk5oh
|
|
5zHk283U0eo3jaZZ2N5XYjrCnLSJhOK+8d1kxvCqzSwZvousrb7k9LfJ3nB1OLeJdLhufx9LEWn3
|
|
6e7LXN9Ofy5/W4AuxAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAETaKxMzO0Qi9646Ta07RDmZ9VbPbaOlI7Qi3i+c3TPUaqcu9adKfy0722ZXvFa9
|
|
XO1OrjrESxt66ZJmcjPUanlidmhkzTZVfLN5VWvsC2b7R3U3yqrZZtO1esz2h2+F+zWTUcuXXTNM
|
|
feKR3n5+iZLVbqRzNJo9TxHLyaekz62ntD1fDOA6fQbZL7Zc/wCKY6R8odLBgxabFGPDSKUjyiFj
|
|
SZkYa3aALKAAAAAAAAAAAAAADQ4pl2pTFH3p3n5Q33E12Tn1eSfKscsLZ+orS00eJqbW+Lfnu1tF
|
|
XaJnZsz3WpCfsyp00fWSvmPdVYOmSUDd8kR3InoQosy7JmUX7MdwZ17ro7KKT1XRPRAsrO0rYndr
|
|
79V1ZBaQiJ6JgCSIJASwrO07MpV2nqBlrv1a1o2bf2qtfLXaQUTO0sb05o3jv3ZXhjS20xEphW5h
|
|
yeJjjf7UdJWNKLziyRePsz0lux1SgAQAAAAAAAAAAAAAADG9K5KTS8Rato2mJZAPIcU4ZbQZuekT
|
|
OC3afT4NXFkmlntc2GmoxWx5K71tG0vHa/RX0GpmlutJ61t6wrY2xr8dXS5uesN+tt4ef0eaa223
|
|
2dnHk3juyreM81OaFGiy/RtZET9jJ7s/2bdutd2jqKeic3iNTsd8a2h1H0jTVtP2o6W+bZbOO+gA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABje9cdJt
|
|
adohGTLXFTmvO0fy52bJfU23t0pHaqLeL5xdK9Rnvqb+cUjtCi94xxvK3JetKuHrdZvaa1ljb10y
|
|
cnIs1Wt3naJc++TmVWvMz1YWybfMGdsm3eWek0mo4jm8PT0mfW3lDf4V7P5tdMZdRviwfvZ6/TaX
|
|
DpMMYsFIpWPTzXmf+steT8jn8L4Dp+HxF77Zc/4pjpHydYGjC3oAAAAAAAAAAAAAAAAADG9opS1p
|
|
7RG7zszN6WtPe0zLua+3Joss/wBOzhzG2OsL5+IrY09dsSyYRijbHEMvOChb7KjF0yS2LQ169Mso
|
|
S24noyrPVXWejNVKbTuw3T3REdQWU6LYlVvsyiUDPfqupPRr79VuOQX1lZEqoZxIMksd0gT2VT0l
|
|
bPZVbuCaW8i8bwr32WxbcGnkjaZa9p2ndv5qbw5+aNugLItF6TEtvTX5sMb969HMpfazc0d9stqe
|
|
vVZDdAQAAAAAAAAAAAAAAAADV1+iprtPOO/2u9bektoB4TJTJpNRbHkja1Z6uto8viVht+0HDvpG
|
|
H6Tjj6zHHvbecONw7Ltfkmeqmo6Ma69DXbbZTkr1mGWO3RneOaGbZRoM30fVzSelMnT83aef1FZ7
|
|
x3h1tBqfpGnjmn369LNc3sc3kzy9bQCzIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAa+q1dNNXr7157VhGp1Xh70x+9f9ocy283m1p5rz3mVbrjXHjt91lz
|
|
5c9+fJ1nyjyhdM8lZlOOIiqrUXikd+kMreunnI5XEdX4dZiZcG+XmtNl/F83PeeWWHDOGanieSKY
|
|
q+5H2rz2hMzWd1Iqx1yajJXHhrNrW6REeb1nCPZumn2z62Ivl7xTyr/6uhwzhGn4Zj2xxzZJ+1kn
|
|
vLoNJnjHW7TbbsAszAAAAAAAAAAAAAAAAAAAAaPFrbaSK/itEOXt0rDf4xb/ACa/GZacRvaF58Q2
|
|
IjasQnzPIhCU92tMbZGzHmotG10C6nZkwpPRmipIllEbMIZIE7solgmJBnCyk9VMM6z1BtVllEqK
|
|
z0WRILYlluriWcSDJVbusV27gwInaSWM9ECyZ3hqamnSWxFmOSOaqRx725bNnSZNs9J+OynVY+WZ
|
|
YYr7TE+nVaIr0Ais81Yn1hKAAAAAAAAAAAAAAAAAABExvG09peU4nov9n66L0j6q/WPg9Y1OJaON
|
|
ZpL0+9HWs/EWzeVz9PbmrEtnyc3h9reHy26TWdnSr2YX6657ijLXpLX0+onSamL/AHJ6W+Tbv2aW
|
|
ekTv16JzeI1Ox6KJiYiY7Slz+E6jxdN4dp3vj6fl5Og2clnKACAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACZ2jeQRMxEbzO0Q08uqtkma4ulfO3r8lefUePMxWf
|
|
cjy9WvlzVxV6T1Z61/x0Y8f7Wc7Ur1lqVy+LqOWJ2hp6rXddon5rOF1tfmz5OkT0qzb8dWbxjp1c
|
|
biuuilJ5Z6r+IcQrixzEy8zl1E6rNt1tMztFY81sztU1eRucN4ffi2p5esRM72n0h7rS6XFo8FcO
|
|
CkVpX082nwXh3+z9FWLxHi36328vg6TZyW9ABAAAAAAAAAAAAAAAAAAAAAADj8Unm1tK/hqppHvw
|
|
y1k8/EMk+m0GOPeafiFpCZYwolnXspvHvLa9mF46gmnZmwozRUiUCBKYYsoBLOFbKAX0llEqqyzi
|
|
QXRLOJVRLOOwLIljZMEgrlhKyYYTAK5nZPN0RZjugUanHzVlz6xtLq361c+9eXItPpXX0dubTU+E
|
|
bL2lw2++O1fSW6m/VYAISAAAAAAAAAAAAAAAAAp1GbwcfTreelYEydcuMcRrM/L9nnlsV6wqpi2r
|
|
tv133mfWVkRyRtEdGFva7MzkYZNoamWN4bV4mYa9qztKIujhVppxGI8r1mJegeZpknBqKZY+7L0t
|
|
LRekWrO8TG8Ns/HJ5ZypAWZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAADS12fp4VJ6z9qVuq1HgUiI+3bpDl589cOKZmevqprXPTbx477rDJlrhr1nq4+s182tMRP
|
|
RqaziXiZJrWekNG17ZbxWJ336M5LXRbI3dLTJrs07RMY6fan1dHLrowY+X7MVjt6N3R6Kul0EbWm
|
|
s7bz8Z+LnabQX43r7Y53php/mXj+Dnv0f1JO1x/8ZxbUzj02O15mfLtD13AvZqnDds+pmMmo26el
|
|
XX0Wh0/D8EYtNjilY7+s/NstpOOTW7QBKgAAAAAAAAAAAAAAAAAAAAAADG88tLW9I3BwJtz6nNf1
|
|
vK/DHVqYJ3pzT5y3MPZeojOWMQylEKpTVjZnDCwkqzYQyRRICATCITAJZQxhMAshnEq4ZQC2srKq
|
|
qrIBZCWNZZgwswmFloVyCu0dFcx1WyrtCBhv5NTPHXds2U5o3hIz4ffbPt+KHUcTSW5c9Jme0u2v
|
|
VYAKpAAAAAAAAAAAAAAAAYZctcVOa35R6tLrltN795/YvknNqrfhpPLH92V5isd9mWq6fHjk6rn0
|
|
ZxG8KK5Jm/wbVZiYZtqrmkqL023bkxvCiY3lJHNyRG81mHS4Rn5sNsNp64+3yaWaNrzOzHBl+i6q
|
|
mT7s9J+S+ay8mex6EIneN47SNXKAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAImYiJme0JafEs3h6fkidrZOn5eaLeJk7eOdm1Hi2vmtPTry/CHmOJcUvmvOPF1n09Pm
|
|
6HF9ZGm01qxO3R5vSY7XwzmzTy47zzTEd7en5Mfvt2/PURWdo3tvPrPlKymbktFqTtMTvHzbOLDG
|
|
f63JXbFX7FdnoODcDprZpq9TjiMMTvSn4vj8l5fxnrk91saPSa7i2hpOfbTVt5x1m0fLydzR6PDo
|
|
dPGHBXasd585n1lsRERG0dIF5OOe6tAEqgAAAAAAAAAAAAAAAAAAAAAAADX11+TRZrf0y2Gjxe22
|
|
gtH4piP3TPpXKwxtjhuYo9xq442iIblI2pC1RET2ILd9kxCqRjZmwlCSEohIJAQAAJZISDKGUd2M
|
|
MoBnVbVVCyAWVWeSuqyOwIlXZZKue4MJV2WWYT2QKbKL9YlfdRdIo35b7/Hd3KTzUrPrDh27uxpb
|
|
c2mpPwX/ABX9XAKpAAAAAAAAAAAAAACekTIp1eTwtJmv+GkyJn1oafeazbfpMzLR4jq/o8b823zX
|
|
6XNF8ERCvTcNpxLV5LauvPhx9Irv3lhztdtv8TtaWLicXrt03jzjzb2k1nid56ty3s/w+a7Uwzjn
|
|
1raejlarhmbhl/FpbxMO/fzj5p/ixSeXOvTtRfeI280ZI26tfDm3pWe63LaZx7qtGvniJ6tPLvOK
|
|
fOa9WzbJvTbza02jl3n5SSljscK1MajSxWZ96nSW88xw/VfQ9XMT9nfa3yemid43jtLeXsce88qQ
|
|
EqAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADia3UTm1l4j7OP3Y/u
|
|
7Vp2rM+kPJW1PhYcmS0+9MzKm/jbwz31weMzbV8UppazPL9q0/BF4rk1GLDSNqxPWPhCnHmnNrtT
|
|
qPKteWPm6U6OdHaZvO+SaRNvhv12Ub/q3FhtrNVj0uKOt56z6R5y9zix1w4qY6RtWsREOJ7L6OKa
|
|
S2rvX6zNM7T6Vh3mmZyOfya7eACzIAAAAAAAAAAAAAAAAAAAAAAAAAAczjVvqMVfW/8AZ03I41bf
|
|
Lp6/OVs/UVrY47NyOzUxd4bUJpEbb3Z7IiOrKIVSjZhMLJYyhKIgmGUQSDESIEbJEgQmCITEAmGU
|
|
IiGUAyhZVhDOoM4Wx2VQtqBKuyyWEgqlhKyyuyBVaGtkbNmvk7A15l1eH2300R6TMORPSXT4ZO+O
|
|
8fFefEX63gEAAAAAAAAAAAAAAAq1WPxdLlp+Kkx+y1Fvsz8gjhaDauGK8sx07y3OE3m1tT6RaP4c
|
|
vU6yMNKUx73zT0ilY3l2eF6a+m0kRl/zbzz3+Ez5M8z26fJruW6wzYq5sV8d43raNpZjRzPPaTmx
|
|
5b6bJ9rHO3zb2WJ8GWPEscY9bgzxH2t62n19GWW0eHOzHU5XbjXZ1x8WTnz2iZ7S2M1IjH2+LX0V
|
|
KTqs8zO9ot0j8nUthi1J3UaOFMTfLFo6xMbS9BwHWTqdHOO8+/hnln5eTjYMFo1WTH5VnePzXcIm
|
|
2k4zlpPSmXy/hfF5eMfJns69OA2cgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAADG/2LfJ874rW845mubliY7bPoto5qzHrDz0+yePNF41OotaJ7RWNtpV1OtfHqZ715fhu
|
|
j8adNpcVfeyzE2/vLuanhOu1nEctIxTTFa/+ZPbZ3eHcF0vDbTfFE2yzG03t32+DokynXl9+leDB
|
|
TTYKYccbUpWIhYCzEAAAAAAAAAAAAAAAAAAAAAAAAAAAAcXjE/4zDH9M/wAu04XF5/3jj/0f3Wz9
|
|
RUYmzDWxS2I7FSyjuzY1ZKpRKEygEwiWUIkGIk2QJNhKQhMIhkCYZQxhlAMoZwwZwgWQshVCyATL
|
|
CWc9ldpBhZXLOVdpQK7NfJPRdaWvknoDVvPvOnwuel4+TlXn3nS4VPvXj4QtEV0wAAAAAAAAAAAA
|
|
AAAAAVV02CmTxK4qRf8AFFeq0AAAanEsfPpZmO9Ji0NDLfkwdOsulrumiyzHlVzJrz4Ovoy26vB8
|
|
cTBa9NffLtMY77Rv8Yegx5ImkKdJoY1HC81Y+3OSbVn0mGGkmbY45u6tnrrTOu2xGO0RxCd+nNVj
|
|
qKxTV1vH2pjaGtnyzXXYdo96ZmGXEMk15b7/AGZiVerWPTYckZcNbx5wzc7hGbnxXxzPWk7x8pdF
|
|
0S9jh1OXgAlUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAcPjEf4/FP9H93ccXjMf4vDP9Mx+62fqKrx+S+GvibEFSsqyYwlVK
|
|
ZYsmIMoRKYJQIPIEiQ2ATCUQygCGUIhMAyhnDCGUIFkLIV1ZxIMpVWWSrsCuyqyyyq09ECq8tfJK
|
|
66jJ2Bp5J6upwn7dv9Lk5J951uE/av8AJaIrqAAAAAAAAAAAAAAAAAAAAAAq1Mc2myxPnWf4cmtu
|
|
XT9fR0tffk0WSe28bfq5Wbamm3326MtunwfK6PCv/AxPraZ/dz9PO97/AOqf5dHhdZrw7Dv3mOb9
|
|
XOxRFM+avpe38mvkPHf/AFWlrKba7Tzt99ZxKkfR7euyNXMTrtPHfa0z+zPiM/UR8Zj+Wbdu8HpN
|
|
M2bfzrV13M4dO2pyR61dNvj44/J/oAWZgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADj8bj63BPzdhyeNx0wz8ZWz9RWri7Nmv
|
|
VrYu0NmqaRZHZlDGGSiwxZSgCEkCBCQSCQBMJRCYgEsoYx3Z17AlMIhlCBnDOGEM4AlhZZKq4KrK
|
|
7LLKrIFN2vdfZReAaObu6/CO9vk5OePR1uEd7fJeIrqAIAAAAAAAAAAAAAAAAAAAAGtxCk5NFliI
|
|
3mI32+XVyNTyZOHTee946PQKPoeDffw4777eW/yVs60xv+ZxOnr4Okx1t05KRv8Ao41Z5q3yed5m
|
|
XY1szXRZ5jvFJ/hxItP0aOSN9q7yrtr4f2tHFM5+KT16Yq/vK/iGSbXw4vO14UcPx5MGfNbPG18m
|
|
1oj4THRsTw7VanPXVYpi3gzMcnrvCnG11JOupwuN8+a3pEQ6jT4divjxWnJExa09pbjbM5HHu90A
|
|
JUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAHM41H1GOf6nTc/jEf4Ws+lls/UX45uGekNujTwdm5RNIthKIZKLDFlsiQIShIC
|
|
EgCUJ7AmGTGO7IDzZQhMSDJMMYZQgZwzhhDOATuqssmVdgVWVWWyqtCBTeVF19lF+wNLNG7q8I+9
|
|
8nLyupwnt+S8RXUAQAAAAAAAAAAAAAAAAAAAAAAItWL1mto3iY2lyrcLyUxzix2ia2nvPeK+jrCL
|
|
OrTVnxpanhuPPemSs8l6RtE7dJj0ldpNP9GwRSZ3neZmV4cR/Vs4AJQAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAANHi1d9H
|
|
M+kt5ra+vPoskfDdOfqK4mn7Q3aNHBPZu0W0RdDOGFWcKLCJZeTGQQlCQSgASBsCYZQxhlAJTAmA
|
|
TsmAgGcM4YQyjsgRLC3VnaVcgwsrt3Z2V2QK7tbJ1bN5a9waeWO7p8Knt8nNyebpcK8vkvlFdQBA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAK9RXmwZI+ErEWjesx6wQeZwejeo0cccuW8
|
|
elpblJaaRGxVnCuss4ZrMvJEgCAASISCQIBlCYYpieoM0wx8k7gzIRueYM4Z79FcSy3QEsLJmWFp
|
|
BjaVVpZWlXMoGNmvkXXlr3kGtknu6XCf7OXkl1OEdl8orqgIAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAHmskcmtzV/rls0U62OXiWX4zErcc9GmkRfWVkSqqziWayxCPIANwBIhIJSxS
|
|
CRG6dwZwlhEs4BluMdzfqgZxLLdXuy3AmVdpZTKuZBjaVVpWWV2QlhZRdfZRcGpl7urwfrzfJy8r
|
|
rcH61vPyWitdMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHA4nHLxKZ9awnH2ZcY
|
|
jbW459aq8fZpfiI2IZwrqzhmsz3Ebm4JN0AMhCQSIASndiAziWUSriWcAyRujc80DM3RCfIETLCW
|
|
UsZEsJYSslXZAwlTddPZTkBp5e7r8Gj6rJPxhx8k9Xa4PG2C8/FaK10QAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAcfjcbZMFvnDWx9m5x2PqcNvS+zSxT7sNPxH62YZQwqzhRZO6UCB
|
|
KUAJTux3SDIRuAncQAmJZRLBMSgZ7iIAZRKd2DICUSlAljLCYWMLIFVukNfI2bNbIDTyT7zu8Ijb
|
|
Sz/qcG/2nf4T/wCE/wD2WnxWt4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHL9oL
|
|
+Hw2cm28VvEuPptfgyVj6yIn0no7/FtJfW8NzYMe3PaPd39d3iMug1WktNc2C9dvPbeP1aZ9xF+v
|
|
T471tHu2iflK2HkqWmvaZj5Surqc9Ps5bx+alTHqYHm68S1Vf/NmfnC2vGNTXvyT84Ql6A3cSvHM
|
|
sfaxVn5Ssrxyv3sM/lKB1xza8bwT3pePyWV4tpZ+/MfOEjfGrXiGlt2zV/PotrqcN/s5aT/+wLRj
|
|
FontMSlAlKEgndO6IAZQljDIEgeQljLCzOVdkCu/SGrkbF56NPNeKxMzMRHxENe0+89DwuNtHHzl
|
|
5PJr8NcnLW3Pbf7r1nCZm2gpae8zMrz4i/W6AgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAETETG0xukB4HVaeMHEtRi26RedvkyjBSfX9W77QYvC4xz7dMlYlrU7M929dWJLFc6aPK0q
|
|
7YLxPS0S22FlP6q38Zac0yR92s/KVc3tHfFf8tpbcsLRvB/dR/8ALLVnU0r9uL1+dZI1mnmdvGpv
|
|
6TOy6ym+Oto2tWJ+cJ/tW+KLK5KW+zes/KU7tG+h01p64qx8Y6NXNo6Y+uPJlp8rLf0rfG7MXtHa
|
|
0x8pZxqs9e2a8f8A7Oj7HaTHn0+f6RWM23LETfr6vRW4PoL99NT8ui7F4+vEdXXtnt+fVbXjGsr/
|
|
AOZE/OsPS29nuH27YrV+VpeV9pdPXhOtw49NG9Mld55+vXcTPd42I47qo7xSfyWV9oM8d8VJ/VxM
|
|
d8l46xWF9cV7en6o/qLfxp2I9ob+eCv/AHMo9op89P8A/wBORGmyT5R+qfo2X8P7n9Q/jTsx7RR5
|
|
6ef+4/8AuHftg/8A6cWcOSO9J/WEbWr3pY7Efzp2Lcfv5YK/9zWy8d1E/ZpSv5Oba1/+Hb9lc+LP
|
|
bFt87I7E/wAabWbiurvEx4nL/pjZzc2bJkn372t85ZXx55/BX85lucC0vPxnTxlnnjm32mOiZqUu
|
|
LJ2p4TwnVavNWaYbRTfre0bQ99pcH0bT0xb78vmtiIiNojaErMwAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAHnfarF7umzRHaZrLjYrdIen9ocPi8JyTt1xzF4eUw23rCm3R4r6bMy
|
|
wt6kdTaWLdjswmNoZontsCm0K5XWjopnuDC0dGpqG5bs08/daKV672MjbSaif6oh6Z5f2LtvptRX
|
|
0tEvUN3Jfo8f7cYve0eX4zV7B5z20xc/C8eSPuZIRficfXlcPaG7ino08HWIbePpLF2NuiyOyrHK
|
|
3fZFSwuovHVfaVF4QK5YWTM9UT0EKry6Ps1Tn4zjn8NZn9nOtLseydObiWW34cf918fWfk+PYANn
|
|
KAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAq1WKM+ly4p+/WYeBxTNd6zG0xO0
|
|
vobw3FcP0bi2em20Tbmj5Srr418V9sa2Z7qKyzi07MXUylhaU7yjqhLCeiq3ddaFNxFYW7NLNG8t
|
|
zya+WO6Va9J7FW66mvwidnrXiPY3Ny8RyUn71Jj9Ht3RPjk19HK9pMHj8D1ER3rHN+jqqtTjjNps
|
|
uOe16zAifXzfTz7kNyndpYazS9qT0mszDdoxrsi6m8LazMq6zDOsq1ZEyrt1WWlXaUCqyq0rbKbi
|
|
Fdp6PReyFd8uqv8ACsfy83aXrPZHHto89/xX2/SP/dpj6y8vx6EBq5gAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAB5n2q03LfDqqx39y39npmlxbS/TOG5se29tuavzgWzeV4mtui2
|
|
O3RRSY2hdVhqO2MvI36iu9lUsrSrvDHn6spnmSiq5jooyV6tq1VV69RC32byTh43h8otMx+r6I+Z
|
|
aK/g8TwX7bXh9Mid4iW+fjl8n1ICWb57xLBOm4zqse20Tbmj8+qKdnS9q8PhcTw5tumSm0/OHMxz
|
|
0Za+uzx3sX1t0Zxurr1ZxvspWiZYWZbsbT0QK7KLrZVZJFaqt5vbezNOTg9J/FaZeJns93wCvLwb
|
|
T/GJn92uGHldIBowAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAADuAPA67F9H4l
|
|
qMW20VvO3yRWW97T4fC4rXJHSMtI/WGhVlue3b473K2KzMML4+62tujG9pnozXaOSOVFMnVbmq1t
|
|
trJRW5E7wwvUxTvCyY6CHOt7moxz6Wh9PxTzYaT61h8x1MbZK/OH0zTf+Fxf6I/htj45vL9WgLMn
|
|
mvbPFvocGWO9L7fq85p5maw9d7VYvE4JkmPu2if3eW0+PasdFNOnxfF1Y2hlykRsmY+LJ0MZjZXa
|
|
eq2eyi8oQTO0KLdZWzPRjWu6VaqtHR73g0bcI0sf0Q8Nkq93wqNuFaWP+XDTDDytwBowAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAef9q8HNpcGaI60vtPyl56k9Iew49j8ThGe
|
|
PwxFv0l4zH2U26fDfTYiyJljvsjf4sm6vJ1hrXjq2MkqLdZEVbgbMx0auGdmzNt6iHN1Ub5af6of
|
|
TdPG2nxx6Vj+HzaaTm1+nx/iyVj930ysbViPRrj45vL9SAuyc7j1efguqj+jd4/T33rD3HEcPj8O
|
|
1GP8WOY/Z4TTT7sKadHhbcsZnaCJ3TPZk6VdrKbTutmP0U2nqgrGOsr8deiuI2X09EqKM1dt3uuG
|
|
f/jdN/06/wAPE546S9rwud+Gaaf+XH8NMMPK2wGjAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAABrcRp4nDtRWPPHP8PCYusPoWSvNjtX1iYfPuWaXtX8MzCuvjfw32siu8ptXoxi
|
|
0wy5t4YulReqmazu2skbquURWFInddM7VYRGyL291KFnCcfj8e0le/Lbmn8n0N4b2Ur4nHLWmPsY
|
|
5e5a5+OXyXugBZmiY3iY9Xz7NjnTa3Ph/BeYj5PoTxftFg8Hjk2iOmWkW/Psrr418V5WrWd2faFc
|
|
V2jdnEMXWxntupmN7NiYU27iWML6dVMVnddjgVqMsdHr+CW5uE6f4Rt+7yuSsTDv+zWXn0WTHP3L
|
|
/tK+GHl+O0A1c4AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA8Dn93W56/wDM
|
|
t/L3z59qp24jn+OS38lnpr4r7ZxHQ2TEstt3PXUrt27K57rr1VT0BjKnJPRbMqMs7QlV2fYvHvrd
|
|
VknyrEfu9m8f7FZI8fVU85iJewbT45NfQBKo817W4eulzxHaZrL0rje09ItwqbfhtBVs3leai8RD
|
|
KLw1sduesL606dWFdsZT1jdhNeq6K9DlhCVUU6s4jZnt1YzAhnM71dH2bycmszY/K1d/0c6OzY4R
|
|
fwuK4p8rTstn6z8k7HrwGzkAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHz3
|
|
Vxvr80/8y38voTwGpj/F5/8AqT/JfjTx/WVeyY6FPspc9dZPVXaOq2WEwIUTVRmjo2rNfLHRI3vZ
|
|
DJycXtX8dZh7t879nsnhcbwz23tt+r6I2nxyb+gCVBzuPY/E4PqI9K7ui19fTxNBnp60n+Aj5/pJ
|
|
3jZu1aOnnltMNussdfXbm+l3ZM9URHREdZVXTuT1Nk7boQiOkJw28PU47/htEp5eivJPLMTCZ9Vv
|
|
x7mJ3iJ9UqNHk8XR4b+tIXuhxAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAD
|
|
weqjbWZ4/wCZP8vePCaz/wDIaiP+Zb+UX408f0r9lOxWOifJhXWjfyYWllPRXYQxnrCrJHRd3YZI
|
|
6A1NJecHEsN/S0T+76bE7xE+r5dk93LW3pL6ZpMni6PDf8VIn9m2fjm8s9rgFmQxvHNS0esbMiew
|
|
PnHLyai9fS0w2aNfUTtrs3+uf5bGPqy068fF227KtSsdFlKqNGMV6myyY6sbdIQI8tlOWOi6Jhhk
|
|
j3RD0vA8nicMx9etZmHRcT2Zyb6XNT8N9/2dt0T449T2AJVAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAHhdfG3E9TH9cvdPEcXjk4zqI/q3L8aeP6xr2TsxpLOekMK6mFo6qpXSrm
|
|
OqBixvHSVmzC4OfqK7S9/wAByeLwbTW9K7fo8Fqo6Paeyl+fglI/Da0NcMPK7QC7AAB8313TiOf/
|
|
AKk/y2MHWrX4jG3E9R/1Lfyv0/aFNOrHxuU7LI7MMayGTVlHWUXhNe6Z6wIUsb9d1m20q7dkDpez
|
|
N9tRqKT5xEvRvKez9+Xis1/FSYerb5+OTyf6AFlAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAB43j9eXjN/jWJ/Z7J5L2mry8Upb8VIF8f6aGOey2eynHvOy7bowrrYSxZSwQJ2YXZ
|
|
92N4BoanrEvVexmTm4blr+HJ/aHltRHSXofYm/1Wrp5RaJaYY+X49WA0c4AD51xONuKan/qW/lbp
|
|
+0MOLRtxbU/9SU4J7KadWPjep2WQrr2WRPRk1TvsndXMpiRCb9FNu0rbTuqvKBscCjfi9PhWZeue
|
|
V9n434rafTHL1TfPxy+T/QAszAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAHmv
|
|
avHtfTZfnV6VxPajHzcNrf8ABeJFs/XnMcr4no18c+6vr2YadkY2YM57sEDLyY37Mo7MMnYGlqO0
|
|
vQ+xNfqNVb1tEfs87qZ2rL0/sVX/AHdnt65P7Q0wx8vx6UBo5wAHz/jUbcX1PT78qtO2vaCnJxjP
|
|
8Zif2amnnspp04+OjWejKJ6MKdmcMmyJn4m5ZHzEVPMwtJv0VZLbQDqezcb8RzT6Y/7vUPM+ytZt
|
|
n1OTyiIh6Ztn45N/6AFlAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABocbxeLw
|
|
nUR5xXm/Rvq8+OMuDJjntaswEeBxT0bNZ6NatZpNqz3rO0rqsdO3PxlaWEMpY+aqWXkryT0ZT2V3
|
|
7A0dVPuy9f7G124NM/iyT/Z4zWT7sw957MYfB4Fp4/FE2/WWmGHldcBowAAeM9qKcvFeb8VIly9P
|
|
0nq7ntbTbVYL+tJj93CwT76unR4/jo0nozhhTsy3Y1sWljM9Ce7HyQIm3RRlttVbaWrnt0Sh6n2U
|
|
x8vD8mSfv3/h3XN4Bi8Lg2nj8Uc36y6TeOPXugCUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAPD8RxeBxXUU26Tbmj8+quro+02Lw+I4ssdslNvzhzazvDPbq8d7GW7Dfqz2VzG
|
|
0s2qd+iu/Zn5Ksk9BVztX1mI8930zh2LwOHabH+HHWP2fNYp4+vwYvxXiP3fUqxtWIjyjZtj45/L
|
|
faQFmQADzftfj3w6fJ6WmHmsP23rvaqnNwqLfhvEvIYZ+sV038bo0noy36MK9oZQxrdMyrlnMbMZ
|
|
QKrS1M07zEestq/RRjr4utwY/wAV4j91p9V18fQdJj8LR4ccfdpEfsuREbREJbuMAAAAAAAAAAAA
|
|
BAJAAAAEAJEAJQAJQAJEAJQAJQAJEACUJAQlAJEAJQAJQJAAAEAJEAJBAAAJAABAJEJAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAABwvanDzaPFmjvjv8A
|
|
tLztJ3h7HjGHx+FainnFeaPnHV4vFbeIU038VbHeGF+kso7Mb9mTdhKnLK3dRm7SIrHhGPxeP6Sv
|
|
9cT/AHfSnz72Zx+J7Q45/BWZ/Z9BbZ+OXyfQBZQABzeP4/E4NqI9Ii36S8Ng/wAx9C4jTxOH6ivr
|
|
jn+Hz3B/mQi/GvjdCnWNlsdI2V07LIlg6USrt2ZzZXMoFV+zPhGLxeOaavpbm/RVltEN72Yx+Jxm
|
|
b7dKUmf7L5+s9/HtRA2cqRACRACRACRACUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAACQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQCQQCRACRACRCQBCQBCQB
|
|
ACRACRACRACRACL1i9LVntMbPATTwdRkxT3pea/u+gPE8Xx+DxrPHlaYt+qNfGvjvtXXsi0dOrKk
|
|
dEXjZg6VMtbP2bMtXUdpEV0/Y2nNxbNf8OP+727xvsXH+N1U/wBEfy9k3nxyb+gCVQAGOWvNivX1
|
|
rMPnGGOXNNfOJ2fSZ6w+dZKeHxDPX8N7R+6L8a+L63KdoZ7q6zvEMpnowdKJ6ywmWUyqvIKM0vQ+
|
|
x+D6rU55+9aKx+TzWa36vbezmDwODYenW+95/Nphj5L6dQBo5wAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEgAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAACAEiAAAEoA
|
|
AAAAAAAAAAAAAEAkEAkRuAkQbgkQAkQAkQAkQAl5T2nx8nEMOT8dNv0l6pwfarHvpcGWPu32/WCr
|
|
YvK4mOem6b9mGKd4Z3idmFdka0y1c892zfpMtLPaNpEV6D2Kj/Eauf6YeweQ9ieuTVz8K/3evbT4
|
|
5NfQBKoAA8FxCvJxrUx/XMvevD8Zry8fz/Haf2RfjTx/6RSOnRMyypHu9kXjowrqVSrvPRnZVl6V
|
|
kK0775MsUjvadn0nT4ow6bFijtSsVfPuFYvpPGtNTy54mfy6vorXDm8l9pEC7JIgBIgBIgBIgBIg
|
|
BIgBIhIAgBIhIAgBIgBIIBIAAhIAhIAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJAAAAAAAAAAAAAAA
|
|
AAAAAAAAABAJQkAEAAAAAAAAAAjc3BIjdG4Mkbo5kcwMjdhzHMDPc3V8xzAs3N1fMjmBZubq+Y5g
|
|
Wbm6vmOYFm5ur5jmBZubq+Y5gWbm6vmOYFm5ur5jmBZubq+Y5gWbm6vmTzAz3N2HMnmBlu5ftFTx
|
|
OEZJ/DMW/d0t2rxKni8N1FPWkiZ9eS08e7Cy8dGGn6UhZaJljXZGnmc3UT3dPP2cnUT78xCIV6j2
|
|
H/8A9c/6f7vXPI+w8bU1U+vL/d63du5NfUiDcVSIAS8b7RV5eOb/AIqRL2TyXtNX/e2KfXH/AHlF
|
|
+NPH/pr4+2xcxx0hFpY11K7R16KM32ZWz3UaidqSgrc9kcPicWyZJjfw6T+727y3sXh2xarN+K0V
|
|
h6lvPjj3e0ASqAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAJQAAAAAkQAkQAkAAAAAAAAAAAAAAA
|
|
EgAAAAAAAAAAAAAAAAAAAAAgAAABKDcAN0bgkY8xzAyRux5kcwM9zdXNkTcFm6OZXzMeYFvMibKu
|
|
ZHMC2bo51U2RuC2bom6rc3BZzom6sBZzI52ADPnOdggFnMc6skFnMc6rc3BbznOp3RzAv50c6nml
|
|
HMC/nOf4qOY5wX85zqOc5wbHOc7X5znBsc6edr85zg2ec52vzpi4NjmY5bROG+/bllVzsNTk5dLl
|
|
n0pP8BHmMHWNmzt0aum8obm08vVjfrtnxztR0mXHzTvaZdjVRMTLkZo6yiFen9iZ2pqY/wBP93rN
|
|
3kPY+/LfPX1rE/u9XzN3HfqzdO6vmTuIZ7m7Hc3Bnu8t7TR/vHBP9E/y9Pu837SV31umn+if5Rfi
|
|
/j/01MMb1hjkrtKzBG0bMsmOZY11tOYamr6Und0LUc7XT7u3rJPqL8er9lcPhcFpbzyWm39v7O00
|
|
+FYvA4Zpsc94xxu227jv1IAgAAAAAAAAABKAAAASgASgBIgBIgBIgBIhIAAAAAAAAAAAAAAAAAAC
|
|
UACUJAAAAAAAAAAAABIAAAAAAAAAAAAAAAAAAAAg3AEbomQZbo3YzLGbAz3RNlc3YzcFs2YzdVN2
|
|
M2Bdzom6nmNwW86JurTAMuY3REJ2BB1ZRVMVBhsbSsiqeUFXLucq3lTygp5TlXcpygp5TlXcpygp
|
|
5TlXcqOUFXKjlXcrGYBXysdlswiYBVMdUTCyY6sZBWxlnMMZgGLGZZSwkDdHMiWO4MuY5mEyjcFn
|
|
N1OdVzHMC3nTzqeY5gX85zqOZPMC+Lqdbk20eb/RKOZr8QybaK/XvtH7iZ9aGlp2luzT3fg19NHS
|
|
OjbmPcYX67XH1XSZ9XIzRvMuzrK7zLkZYmYnciunb9lZ5dTk+OP+71cXeP8AZnJ/ip2nf3J/l6iL
|
|
/Fu5L9bMWZczXi6YuIbEWTzKIuyiwLt3nuO25uI4a/hx7/rLuczg8TicvFLbfdpEK6+NPH/phhjo
|
|
stLGkctUWnoxrrU3j1cnWTzZq1jzl1clo5Zcu8c+txR63iP3Tn6pv4+g4o5cVI9IiGe7CJ2iE7t3
|
|
GyN2O6dwSINwSISAlAAlACRAAlAAlACRACRCQAAAAAAAAAASgASISAAAAAAAAAAAAACQAAAAAAAA
|
|
AAAAAASAAAAAAAAAAAAAAAAIAAAQCAJljuljsCJlhMs9mOwMJYys5TkBVsjZdyHICrZPKt5E8oK4
|
|
qmKrOVOwMIqyirPY2Bjyp2ZbAI2NmSARsbMgEbI2ZAMdjZICNkbMkSCNmOzJEgx2YyzljMAwlhKy
|
|
WEwCuWErJhhMArlhLOWEgxljMpljIImWMyTKJA3N0IBO5vux3NwZbnMx3NwZczT4jf3MdPW27a3a
|
|
fJOq1XNP2KdIRfi+J2trSYfcjeF+Wm1OicVeWIiN9kai8xjY12ORqultnI1Ecsujq79XP1FovWYI
|
|
rTgeq+j8QrWZ+3Mx+r2UXeC0WG2Ti2kiN5mL807eUREvbzbaejefHJv62Iv8WUXa0WTFhVtRdlF2
|
|
rz9WUXBtc7jR9dqc2T1ttHyhvZMvJitb0jdq6XHNcNenWVN3028U99WRj6Kb02be3Tq18/SN2Lpc
|
|
3UdN9nOmZrqKX/DaJ/d0svvTLRzV3jomK6+Pd1vvWJj0ZczT0mXxNJht60hfFnQ4qu3N1cWTEgs3
|
|
Tur5k7gz3N2O5uDM3Y7m4MtxBuCQASIASIASAAAAAAACRCQAAAAAAAAEoSAAAAAAAAAAAlAAlCQA
|
|
AAAAAAAAAAASAAAAAAAAAAAAIASgAAAEJAQJQCNkbMgGOyOVnsAw5TlZ7GwMOVPKy2NgY7GzIBGx
|
|
skA2AAAAAAAAAAQkBAEghEskAxYzDPZGwK5hjMLJhjMAqmGEwumrCagomFcw2JqqtUFEsLLrV82F
|
|
o7gqljKyYYTGwMZRKUSCAQAboJnaN5Bjkneu0d5W4ccViIiOzHFWbTzNumP1Zarr8eeRMbxDW1Mx
|
|
NO67NbkhzNVnmInqzaOZrL93JyZeV0M1++7S02jvxDWxhxx033tPpC8Z6rrezWjmZyazJG2/u03h
|
|
2vFibTHoqvamiwVwY+nLGzV0+SZ1Mx8G0/45tOhzJ5lXMc3UVXRdlF1HP+iYsDPLPPy49/tz1+Te
|
|
pSIr0ho6ak5Ms5J8o2q6NImOrHV7XX488ypzTtHXo0s9t6zG7c1G1qz6ubeZiZ3UatXJG3yauSO7
|
|
cvMTEx5tPLb3prPRMVr0HB8vicNxf0+7+kt+LOJwTJyY/Bnz3tH93X36N58cWvq6LSyiyndMSlC7
|
|
mZcymLJiwLosmJVRLKLAtiU7q4lMSCzc3YxJuDMRuAlKAEgAAAlAkAAAAAABKAEgAAAAAJAAAAAA
|
|
AAAAAAAEgAAAAAAAAAAAAAkAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAhIAAACAAAASgAAAAAAEAAAA
|
|
hGzJAImGMwzQDDZjNVuyNgUTVhNGxysZqDVmiu1G5NN2M4waM0+DCaN2cbGcQNGaMZq3JxMJxA1J
|
|
qx2bU4kU09slorWNwa20z02RXHbJbl26QvtFovbHWkxEdJt5y2MOHlr2U1W3jx+1hiw8vSO63lmI
|
|
XRTaEWmtY6snRHO1VpmJ+DjavpSZl2s8b7y4HFcnh0n0gha5ebJN55KRM2mdoiPN6fh+kpwXh0Wy
|
|
RHj5Otp/s5Ps1p62y31+em9aTMYt/OfVfxTiPjZ52naI7fBrI5t66xz5+a1rW7yx0eSL6iZjtEOX
|
|
qNbSletom3lENjh2fbHzbbWt3iVozruc+5ztWubf4M4ybpQ2Oboyrva0Vjza8WdDR4OkXt3n9ldX
|
|
kaePP9VtYqctYhdvt5oivTeCZ2YOxXk6ubqMfV0b9mrljfqlFcq88k7z2U5axeItDa1OPessuC8P
|
|
ya7XRWYnwqdbT/ZMilvIu4dpslNdixXja8Y5tt85djZdbDWnGOesRtXFtuw6T27No5Kx2OrKYQlC
|
|
ExKJgBnEpiyvdlEgsizKLKollFgWxLKJVRLKJBbEp3VxLKJBnuMWQJEbpBIAAAJAAAABIAAAAAAA
|
|
lAJAAAAAAAAAAAAAASAAAAAAAAAAAAAJAAAABAJABAlAAAAAAAAAAAAAAAAAAAAAAAAIAAAAAAAA
|
|
AAABAJQAAAAgAABAAI2EoBGyJhkgGPKxmqxAKpownHC+YRMdN5BrTj67R3bOn01o7p01Iv71u89o
|
|
b9a7LfBTfS1vWI2jf12VfQPSW8KX2mas+NC2iv6xMNfJpMnLtEbuuxtMRCtzF55NR5rPps1N/ctP
|
|
y6uHreE6nXZ4pak48X3rT06fB7fNeI33cbX6mI32R/MWu7XF116aDSRhxbRERs8f499bkyZeeKae
|
|
kzE2mdon81/tfxDLGOunwbzlzbx08oaHBvZHJlx48mrvaa94pu04y617576rNGLRRM0397JEd/lu
|
|
9Dw/S3x4qxffo6mm4NjwUiKY4iI9Ib1dHFY6QIaNabbrYrLfrpJtaK1rMzPZb/s+05IpP59OyLeJ
|
|
k7eNfRaOc1ue32I7fGXYpi5Y77M8OGMeOKxHSFsU3Y29deZMzirl6dlVvhLatCjJHeYQv1rXnps1
|
|
8k9/VsW6qLVmZIi1rzitlvFKRvaZ2h6TSaenC9FFY+3brM+sqeG8Prp4+kZ+lvuxPkr1mqm95nfp
|
|
DXM459676a2q1dsV7XietvNno78+CJn1cjX6mOeIm0bR33dfRU5NJjidt9t5afjG/V6JZ7I2QMNh
|
|
nyo2BhsMuVG3wAhMSbbQRAMolnE+iuGUSCyJZRKuGUSCyJZK4llEgyZMYTuCUsYSCQASISAAAlCQ
|
|
AAAAAAEoASCASAAAAAAAAAAAAlACRACQAAAAAAAAAEgCEoASCAAAAAAAAAAAAAAAAAAAAAAABAAA
|
|
AAAAAAAISAIAAAAAAQAAACASgAAAQJAQAAhIDHZhln3do7z0WS18mWsajHjmes7pg3dNi5aRMNqO
|
|
yvDHTpPRaigHZhN4hHRlaVN59JY3zRENLUavaO+yq0iNVlitJ6vNcR1MVi0zO0era1/Ea0rPvbz5
|
|
PM5MWp45qvo2GZrhmfrsnpHpHzTCseEcM/2vrr8Q1Eb4qzy44nziPN63HpYiIiI7LNHoqabBTFii
|
|
IpSNohuVxrKtWMEejPwY9G1FFmHB4mWJn7MdfnIM9JpIx15to5pbUaas/a6rqViI7MxPxqX0UT1r
|
|
O3wVzpbR2hviP5i03Y5s6a879FNtHljydhExCv8AMTPJXBnRZbz0iG5ptFjwe/l96zctMVamTJtE
|
|
yTMibu1VrdTzRMR0j0ed4lr64MVpm0RERvMz5NvX62uOJ69XhOKX1HH9bHDtFvNYnfJeOy0Z2ojX
|
|
6jjnEq6fRUmccTvN/J9H0eKcOnx45neaxEbubwHgOHg+milI3vP2resu3Wu0JQmITsmISDHZHKz2
|
|
JgFc1RMLJhGwK9iIZ7MZgEdgmAEwyiWCdwWRLKJVxKYsC2JTuriWUSDNlEsIlMAySx3SCRCQSIAS
|
|
AAACRACQAAAAAAASIASAAAAAAAAAAAAAAACRACRACQASIAAAAAAAAAAAAAAAAAAAAAAAAQCUAAAA
|
|
AAAAAAIAAAAAAAAQAAAAAACBICBICAAEJAQJQCJcLjuS2ny6fPG/LWdpd1o8T0X07SXx/e7wCdJx
|
|
Wa0jmneHQpxPDMdZmJfNtZm49weZrh0/j4o7VtSZ2+Uw0/8A7o49k92vBLc/ntFohFW9PqGXimOI
|
|
6Tu1L8T3eCx6r2t1O3JwvHjifO99v7t/Bwf2l1PXU6rS6eJ8qUm8x+so5TsekzcSjbvs4mt4rzW5
|
|
K2mbT0itesy2cHsvbvqtbmyz5xERWP2jd1tJwrTaONsOKtZ8585+cnDrzmn4Rq+IZObUROHD32n7
|
|
Vv8A0ej0uhxaXFGPFSK1j0bkY4jyZRVZVXFGUVWbGwKsk8mObekNrSW3pWf1a2aYjHbm7bNnQ1id
|
|
PW0TvuDdhJEbQABMsLW2R0ZTMQrvfbz2YWzVhpanUxEd0dWkW5c8R5uXxDX1w4pnfr5Q19XxKuOJ
|
|
2neXltVqtVxbV/RdJ715+1bypANfiOu1HENV9C0MTfNeesx2rD1PAeBYuE6aKx72W3W9/WVnBuB4
|
|
eF4dqRzZbdb5J72l160WVK02ZxCYhOwI23TsnY2BGxsnYBjsiYZsZBjMMZZSgGEolMsQDdG6NwZ7
|
|
piVe6YkFsSziVMWZRILolMSriWUSCyJTuwhMSDMRCQSI3SAlACRCQAAEoAEoASAAAAAAAAACUACR
|
|
ACQAAAAAAAAAAAAASAAAAAAAAAAAAAAAAAAACAAAAAAAAAAAAAABAAAAAAAAAAAAACBKAAAAAAAQ
|
|
JQAAAhICEbJAYTWJ7wx8KvpC0BV4ceieWGewDHlNmWwCNjZICNhIDmcZredBecdpiY69FXCOLW+i
|
|
UiZidukulmxxlx2paN4mNng+K4+I8Hy2yaTfl37TXetoCPfRxfp1qi3F48ofKMvtvxak8s6LDv61
|
|
rZji9rPaLUf5PC+bfttS0q8q3p9W/wBrRMdpUZuKdN99nzvFqPbTVz7nD8OKs+do2/mW3h4D7Xaq
|
|
ZnPrtNpqz35aRaYOHY9Zk4pNt9rR+rl6zi+OnS+WN57Rv1lXp/YrNaYtruL6zNPnGO3hxP6O5w/2
|
|
f0HDuun09Yv55Le9afznqcOvO4tBreMTHu30unnva0bWt8on+70nDuE4OHYYx4Kbesz3tPrMuhGO
|
|
IjpDOKrK9YVpsyiGUQnYGOyUgI2SlAIEmwMWMs9kTAMJYzDOYRMArmGErZhhMArlHmzmGMwDE3Ts
|
|
bAbs4swj5pgFkSziVcM4BZEsolXDKAZwyhjCYBkACQhIAAAAAAAJAAAAAAAAAAAAAAAAAAAShIAA
|
|
AAAAAAJAAAAAAAAAAAAAABAJEAAAAAAAAAAAAAAAIEoBKAAAAAAAAAAAAAAABAlAAAAAAAIAAAAA
|
|
BAkBAkBAkBAlACEgMZjdjbFW8bWrEx8YWANb6Fp+bfwab+vLDKMFK9qxH5L0bAr8OPRPKz2AY7J2
|
|
SbAjYZAI2E7AIEgIEgIEgMdkSy2NgY7MdlmyNoBXsxmFuyNgVTVjNV3KjlBRNTlXTVHKCrlIqt5T
|
|
lBhEMohlFerLlBjEMohMVTEARDKCITsAk2AEgAAAkAAAAAAAAAAAAAAAAAAAAAAAASAAAAAAAAD/
|
|
2Q==`;async function H2e(e){let t=(n,s="application/octet-stream")=>fetch(`data:${s};base64,${n}`).then(i=>i.blob()),r,a;switch(e.config.warmup){case"face":r=await t(B0);break;case"body":case"full":r=await t(W0);break;default:r=null}if(r){let n=await createImageBitmap(r);a=await e.detect(n,e.config),n.close()}return a}async function q2e(e){return new Promise(t=>{let r;switch(e.config.warmup){case"face":r="data:image/jpeg;base64,"+B0;break;case"full":case"body":r="data:image/jpeg;base64,"+W0;break;default:r=null}let a;if(typeof Image!="undefined")a=new Image;else if(ce.Image)a=new ce.Image;else return;a.onload=async()=>{let n=Ur(a.naturalWidth,a.naturalHeight);if(!n)se("Warmup: Canvas not found"),t(void 0);else{let s=n.getContext("2d");s&&s.drawImage(a,0,0);let i=await e.image(n),o=await e.detect(i.tensor,e.config);t(o)}},r?a.src=r:t(void 0)})}async function K2e(e){let t=n=>Buffer.from(n,"base64"),r;e.config.warmup==="face"?r=t(B0):r=t(W0);let a;if("node"in We){let n=(void 0).decodeJpeg(r),s=n.expandDims(0);e.tf.dispose(n),a=await e.detect(s,e.config),e.tf.dispose(s)}else e.config.debug&&se("Warmup tfjs-node not loaded");return a}async function t9(e,t){let r=oe();if(e.state="warmup",t&&(e.config=vr(e.config,t)),!e.config.warmup||e.config.warmup.length===0||e.config.warmup==="none")return{face:[],body:[],hand:[],gesture:[],object:[],performance:e.performance,timestamp:oe(),persons:[],error:null};let a;return new Promise(async n=>{typeof createImageBitmap=="function"?a=await H2e(e):typeof Image!="undefined"||ce.Canvas!==void 0?a=await q2e(e):a=await K2e(e);let s=oe();e.config.debug&&se("Warmup",e.config.warmup,Math.round(s-r),"ms"),e.emit("warmup"),n(a)})}var Ld,Kh,Xh,V0,r9=class{constructor(t){fe(this,"version");fe(this,"config");fe(this,"result");fe(this,"state");fe(this,"process");fe(this,"tf");fe(this,"env");fe(this,"draw");fe(this,"models");fe(this,"events");fe(this,"faceTriangulation");fe(this,"faceUVMap");fe(this,"performance");tp(this,Ld,void 0);tp(this,Kh,void 0);tp(this,Xh,void 0);fe(this,"gl");fe(this,"analyze",(...t)=>{if(!ep(this,Kh))return;let r=this.tf.engine().state.numTensors,a=ep(this,Ld);rp(this,Ld,r);let n=r-a;n!==0&&se(...t,n)});tp(this,V0,t=>{if(!ep(this,Xh))return null;if(!t)return"input is not defined";if(this.env.node&&!(t instanceof et))return"input must be a tensor";try{this.tf.getBackend()}catch(r){return"backend not loaded"}return null});fe(this,"similarity",JN);fe(this,"distance",L0);fe(this,"match",QN);fe(this,"emit",t=>{var r;this.events&&this.events.dispatchEvent&&((r=this.events)==null||r.dispatchEvent(new Event(t)))});this.env=ce,xs.wasmPath=Dh["tfjs-core"].includes("-")?"https://vladmandic.github.io/tfjs/dist/":`https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@${Zy}/dist/`,xs.modelBasePath=ce.browser?"../models/":"file://models/",xs.backend=ce.browser?"humangl":"tensorflow",this.version=Jx,Object.defineProperty(this,"version",{value:Jx}),this.config=JSON.parse(JSON.stringify(xs)),Object.seal(this.config),t&&(this.config=vr(this.config,t)),this.config.cacheModels=typeof indexedDB!="undefined",wT(this.config),this.tf=We,this.state="idle",rp(this,Ld,0),rp(this,Kh,!1),rp(this,Xh,!1),this.performance={},this.events=typeof EventTarget!="undefined"?new EventTarget:void 0,this.models=new f5,this.draw={options:ps,canvas:(r,a)=>VN(r,a),face:(r,a,n)=>x5(r,a,n),body:(r,a,n)=>b5(r,a,n),hand:(r,a,n)=>v5(r,a,n),gesture:(r,a,n)=>A5(r,a,n),object:(r,a,n)=>w5(r,a,n),person:(r,a,n)=>WN(r,a,n),all:(r,a,n)=>UN(r,a,n)},this.result={face:[],body:[],hand:[],gesture:[],object:[],performance:{},timestamp:0,persons:[],error:null},this.process={tensor:null,canvas:null},this.faceTriangulation=MC,this.faceUVMap=$C,this.gl=Nt,this.emit("create")}reset(){let t=this.config.backend;this.config=JSON.parse(JSON.stringify(xs)),this.config.backend=t}validate(t){return m1(xs,t||this.config)}now(){return oe()}image(t,r=!0){return kd(t,this.config,r)}async segmentation(t,r){return MN(t,r,this.config)}enhance(t){return zb(t)}compare(t,r){return bT(this.config,t,r)}async init(){await _0(this,!0),await this.tf.ready()}async load(t){this.state="load";let r=oe(),a=Object.values(this.models).filter(i=>i).length;t&&(this.config=vr(this.config,t)),this.env.initial&&(this.config.debug&&se(`version: ${this.version}`),this.config.debug&&se(`tfjs version: ${this.tf.version["tfjs-core"]}`),await _0(this)||se("error: backend check failed"),await Qu(),this.env.browser&&(this.config.debug&&se("configuration:",this.config),this.config.debug&&se("environment:",this.env),this.config.debug&&se("tf flags:",this.tf.ENV.flags))),await PN(this),this.env.initial&&this.config.debug&&se("tf engine state:",this.tf.engine().state.numBytes,"bytes",this.tf.engine().state.numTensors,"tensors"),this.env.initial=!1,Object.values(this.models).filter(i=>i).length!==a&&(await ON(this),this.emit("load"));let s=Math.trunc(oe()-r);s>(this.performance.loadModels||0)&&(this.performance.loadModels=this.env.perfadd?(this.performance.loadModels||0)+s:s)}next(t=this.result){return ZN(t,this.config)}async warmup(t){let r=oe(),a=await t9(this,t),n=oe();return this.performance.warmup=Math.trunc(n-r),a}async profile(t,r){let a=await this.tf.profile(()=>this.detect(t,r)),n={};for(let o of a.kernels)n[o.name]?n[o.name]+=o.kernelTimeMs:n[o.name]=o.kernelTimeMs;let s=[];Object.entries(n).forEach(o=>s.push({name:o[0],ms:o[1]})),s.sort((o,l)=>l.ms-o.ms),s.length=20;let i={};for(let o of s)i[o.name]=o.ms;return i}async detect(t,r){return this.state="detect",new Promise(async a=>{var g,y,A,x,b,v,C,T,E,R,z,M,I,D,O,j,X,_,K,W,ee,Q;this.state="config";let n;this.config=vr(this.config,r),this.state="check";let s=ep(this,V0).call(this,t);s&&(se(s,t),this.emit("error"),a({face:[],body:[],hand:[],gesture:[],object:[],performance:this.performance,timestamp:oe(),persons:[],error:s}));let i=oe();await _0(this),await this.load(),n=oe(),this.state="image";let o=await kd(t,this.config);if(this.process=o,this.performance.inputProcess=this.env.perfadd?(this.performance.inputProcess||0)+Math.trunc(oe()-n):Math.trunc(oe()-n),this.analyze("Get Image:"),!o.tensor){this.config.debug&&se("could not convert input to tensor"),this.emit("error"),a({face:[],body:[],hand:[],gesture:[],object:[],performance:this.performance,timestamp:oe(),persons:[],error:"could not convert input to tensor"});return}this.emit("image"),n=oe(),this.config.skipAllowed=await xT(this.config,o.tensor),this.performance.totalFrames||(this.performance.totalFrames=0),this.performance.cachedFrames||(this.performance.cachedFrames=0),this.performance.totalFrames++,this.config.skipAllowed&&this.performance.cachedFrames++,this.performance.cacheCheck=this.env.perfadd?(this.performance.cacheCheck||0)+Math.trunc(oe()-n):Math.trunc(oe()-n),this.analyze("Check Changed:");let l=[],d=[],u=[],p=[];this.state="detect:face",this.config.async?(l=this.config.face.enabled?I5(this,o.tensor):[],this.performance.face&&delete this.performance.face):(n=oe(),l=this.config.face.enabled?await I5(this,o.tensor):[],this.performance.face=this.env.perfadd?(this.performance.face||0)+Math.trunc(oe()-n):Math.trunc(oe()-n)),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 h=this.config.body.maxDetected===-1?vr(this.config,{body:{maxDetected:this.config.face.enabled?1*l.length:1}}):this.config;this.config.async?(((g=this.config.body.modelPath)==null?void 0:g.includes("posenet"))?d=this.config.body.enabled?p5(o.tensor,h):[]:((y=this.config.body.modelPath)==null?void 0:y.includes("blazepose"))?d=this.config.body.enabled?bb(o.tensor,h):[]:((A=this.config.body.modelPath)==null?void 0:A.includes("efficientpose"))?d=this.config.body.enabled?Cb(o.tensor,h):[]:((x=this.config.body.modelPath)==null?void 0:x.includes("movenet"))&&(d=this.config.body.enabled?a5(o.tensor,h):[]),this.performance.body&&delete this.performance.body):(n=oe(),((b=this.config.body.modelPath)==null?void 0:b.includes("posenet"))?d=this.config.body.enabled?await p5(o.tensor,h):[]:((v=this.config.body.modelPath)==null?void 0:v.includes("blazepose"))?d=this.config.body.enabled?await bb(o.tensor,h):[]:((C=this.config.body.modelPath)==null?void 0:C.includes("efficientpose"))?d=this.config.body.enabled?await Cb(o.tensor,h):[]:((T=this.config.body.modelPath)==null?void 0:T.includes("movenet"))&&(d=this.config.body.enabled?await a5(o.tensor,h):[]),this.performance.body=this.env.perfadd?(this.performance.body||0)+Math.trunc(oe()-n):Math.trunc(oe()-n)),this.analyze("End Body:"),this.analyze("Start Hand:"),this.state="detect:hand";let c=this.config.hand.maxDetected===-1?vr(this.config,{hand:{maxDetected:this.config.face.enabled?2*l.length:1}}):this.config;this.config.async?(((R=(E=this.config.hand.detector)==null?void 0:E.modelPath)==null?void 0:R.includes("handdetect"))?u=this.config.hand.enabled?jb(o.tensor,c):[]:((M=(z=this.config.hand.detector)==null?void 0:z.modelPath)==null?void 0:M.includes("handtrack"))&&(u=this.config.hand.enabled?Xb(o.tensor,c):[]),this.performance.hand&&delete this.performance.hand):(n=oe(),((D=(I=this.config.hand.detector)==null?void 0:I.modelPath)==null?void 0:D.includes("handdetect"))?u=this.config.hand.enabled?await jb(o.tensor,c):[]:((j=(O=this.config.hand.detector)==null?void 0:O.modelPath)==null?void 0:j.includes("handtrack"))&&(u=this.config.hand.enabled?await Xb(o.tensor,c):[]),this.performance.hand=this.env.perfadd?(this.performance.hand||0)+Math.trunc(oe()-n):Math.trunc(oe()-n)),this.analyze("End Hand:"),this.analyze("Start Object:"),this.state="detect:object",this.config.async?(((X=this.config.object.modelPath)==null?void 0:X.includes("nanodet"))?p=this.config.object.enabled?s5(o.tensor,this.config):[]:((_=this.config.object.modelPath)==null?void 0:_.includes("centernet"))&&(p=this.config.object.enabled?kb(o.tensor,this.config):[]),this.performance.object&&delete this.performance.object):(n=oe(),((K=this.config.object.modelPath)==null?void 0:K.includes("nanodet"))?p=this.config.object.enabled?await s5(o.tensor,this.config):[]:((W=this.config.object.modelPath)==null?void 0:W.includes("centernet"))&&(p=this.config.object.enabled?await kb(o.tensor,this.config):[]),this.performance.object=this.env.perfadd?(this.performance.object||0)+Math.trunc(oe()-n):Math.trunc(oe()-n)),this.analyze("End Object:"),this.state="detect:await",this.config.async&&([l,d,u,p]=await Promise.all([l,d,u,p])),this.state="detect:gesture";let f=[];this.config.gesture.enabled&&(n=oe(),f=[...qN(l),...HN(d),...XN(u),...KN(l)],this.config.async?this.performance.gesture&&delete this.performance.gesture:this.performance.gesture=this.env.perfadd?(this.performance.gesture||0)+Math.trunc(oe()-n):Math.trunc(oe()-n)),this.performance.total=this.env.perfadd?(this.performance.total||0)+Math.trunc(oe()-i):Math.trunc(oe()-i);let m=((Q=(ee=this.process)==null?void 0:ee.tensor)==null?void 0:Q.shape)||[];this.result={face:l,body:d,hand:u,gesture:f,object:p,performance:this.performance,canvas:this.process.canvas,timestamp:Date.now(),error:null,get persons(){return e9(l,d,u,f,m)}},re(o.tensor),this.emit("detect"),this.state="idle",a(this.result)})}};Ld=new WeakMap,Kh=new WeakMap,Xh=new WeakMap,V0=new WeakMap;return nE(Z2e);})();
|
|
/**
|
|
* @license
|
|
* Copyright 2017 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2018 Google LLC
|
|
*
|
|
* Use of this source code is governed by an MIT-style
|
|
* license that can be found in the LICENSE file or at
|
|
* https://opensource.org/licenses/MIT.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
*
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC
|
|
*
|
|
* Use of this source code is governed by an MIT-style
|
|
* license that can be found in the LICENSE file or at
|
|
* https://opensource.org/licenses/MIT.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
*
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2019 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2020 Google Inc. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2020 Google LLC
|
|
*
|
|
* Use of this source code is governed by an MIT-style
|
|
* license that can be found in the LICENSE file or at
|
|
* https://opensource.org/licenses/MIT.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use backend file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2020 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the License);
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an AS IS BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2021 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2021 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* https://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2021 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the License);
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an AS IS BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* Human main module
|
|
* @default Human Library
|
|
* @summary <https://github.com/vladmandic/human>
|
|
* @author <https://github.com/vladmandic>
|
|
* @copyright <https://github.com/vladmandic>
|
|
* @license MIT
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2018 Google LLC. All Rights Reserved.
|
|
* Licensed under the Apache License, Version 2.0 (the "License");
|
|
* you may not use this file except in compliance with the License.
|
|
* You may obtain a copy of the License at
|
|
*
|
|
* http://www.apache.org/licenses/LICENSE-2.0
|
|
*
|
|
* Unless required by applicable law or agreed to in writing, software
|
|
* distributed under the License is distributed on an "AS IS" BASIS,
|
|
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
* See the License for the specific language governing permissions and
|
|
* limitations under the License.
|
|
* =============================================================================
|
|
*/
|
|
/** @license See the LICENSE file. */
|