mirror of https://github.com/vladmandic/human
8095 lines
1.6 MiB
8095 lines
1.6 MiB
/*
|
|
Human
|
|
homepage: <https://github.com/vladmandic/human>
|
|
author: <https://github.com/vladmandic>'
|
|
*/
|
|
|
|
var Human=(()=>{var Vc=Object.defineProperty;var DE=Object.getOwnPropertyDescriptor;var LE=Object.getOwnPropertyNames;var BE=Object.prototype.hasOwnProperty;var WE=(e,t,r)=>t in e?Vc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:r}):e[t]=r;var bs=(e,t)=>{for(var r in t)Vc(e,r,{get:t[r],enumerable:!0})},VE=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of LE(t))!BE.call(e,a)&&a!==r&&Vc(e,a,{get:()=>t[a],enumerable:!(n=DE(t,a))||n.enumerable});return e};var UE=e=>VE(Vc({},"__esModule",{value:!0}),e);var fe=(e,t,r)=>(WE(e,typeof t!="symbol"?t+"":t,r),r),E3=(e,t,r)=>{if(!t.has(e))throw TypeError("Cannot "+r)};var pp=(e,t,r)=>(E3(e,t,"read from private field"),r?r.call(e):t.get(e)),hp=(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)},cp=(e,t,r,n)=>(E3(e,t,"write to private field"),n?n.call(e,r):t.set(e,r),r);var YAe={};bs(YAe,{Human:()=>o3,default:()=>o3,defaults:()=>vs,draw:()=>e3,env:()=>he,match:()=>i3,models:()=>pg});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 R3(e,t){let r=e.endsWith("/")?"":"/",a=t.startsWith(".")||t.startsWith("/")||t.startsWith("http:")||t.startsWith("https:")||t.startsWith("file:")?`${t}`:`${e}${r}${t}`;if(!a.toLocaleLowerCase().includes(".json"))throw new Error(`modelpath error: expecting json file: ${a}`);return a}var oe=()=>typeof performance!="undefined"?performance.now():parseInt((Number(process.hrtime.bigint())/1e3/1e3).toString());function q1(e,t,r="config",n=[]){for(let a of Object.keys(t))if(typeof t[a]=="object")q1(e[a],t[a],a,n);else{let s=e&&typeof e[a]!="undefined";s||n.push({reason:"unknown property",where:`${r}.${a} = ${t[a]}`});let i=e&&typeof e[a]==typeof t[a];s&&!i&&n.push({reason:"property type mismatch",where:`${r}.${a} = ${t[a]}`,expected:typeof e[a]})}return t.debug&&r==="config"&&n.length>0&&se("invalid configuration",n),n}function Ut(...e){let t=r=>r&&typeof r=="object";return e.reduce((r,n)=>(Object.keys(n||{}).forEach(a=>{let s=r[a],i=n[a];Array.isArray(s)&&Array.isArray(i)?r[a]=s.concat(...i):t(s)&&t(i)?r[a]=Ut(s,i):r[a]=i}),r),{})}var vs={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"},attention:{enabled:!1,modelPath:"facemesh-attention.json"},iris:{enabled:!0,modelPath:"iris.json"},emotion:{enabled:!0,minConfidence:.1,skipFrames:99,skipTime:1500,modelPath:"emotion.json"},description:{enabled:!0,modelPath:"faceres.json",skipFrames:99,skipTime:3e3,minConfidence:.1},antispoof:{enabled:!1,skipFrames:99,skipTime:4e3,modelPath:"antispoof.json"},liveness:{enabled:!1,skipFrames:99,skipTime:4e3,modelPath:"liveness.json"}},body:{enabled:!0,modelPath:"movenet-lightning.json",maxDetected:-1,minConfidence:.3,skipFrames:1,skipTime:200},hand:{enabled:!0,rotation:!0,skipFrames:99,skipTime:1e3,minConfidence:.5,iouThreshold:.2,maxDetected:-1,landmarks:!0,detector:{modelPath:"handtrack.json"},skeleton:{modelPath:"handlandmark-full.json"}},object:{enabled:!1,modelPath:"mb3-centernet.json",minConfidence:.2,iouThreshold:.4,maxDetected:10,skipFrames:99,skipTime:2e3},segmentation:{enabled:!1,modelPath:"selfie.json",blur:8}};var Ue={};bs(Ue,{Abs:()=>Vo,Acos:()=>_u,Acosh:()=>zu,AdadeltaOptimizer:()=>Wm,AdagradOptimizer:()=>Vm,AdamOptimizer:()=>Um,AdamaxOptimizer:()=>Gm,Add:()=>Ja,AddN:()=>Ks,All:()=>Ou,Any:()=>Du,ArgMax:()=>Xs,ArgMin:()=>Lu,Asin:()=>Bu,Asinh:()=>Wu,Atan:()=>Vu,Atan2:()=>Gu,Atanh:()=>Uu,AvgPool:()=>Zs,AvgPool3D:()=>Kp,AvgPool3DGrad:()=>Xf,AvgPoolGrad:()=>Kf,BackendWasm:()=>lN,BatchMatMul:()=>Ys,BatchToSpaceND:()=>Uo,Bincount:()=>Zf,BroadcastArgs:()=>Yf,BroadcastTo:()=>Mw,Callback:()=>s6,CallbackList:()=>s4,Cast:()=>Js,Ceil:()=>Qs,ClipByValue:()=>Qa,Complex:()=>Xp,ComplexAbs:()=>Zp,Concat:()=>Go,Conv2D:()=>ei,Conv2DBackpropFilter:()=>Jf,Conv2DBackpropInput:()=>ti,Conv3D:()=>Yp,Conv3DBackpropFilterV2:()=>Qf,Conv3DBackpropInputV2:()=>em,Cos:()=>ri,Cosh:()=>ni,CropAndResize:()=>Ho,Cumprod:()=>jo,Cumsum:()=>ai,CustomCallback:()=>o4,DataStorage:()=>qp,DenseBincount:()=>tm,DepthToSpace:()=>qo,DepthwiseConv2dNative:()=>si,DepthwiseConv2dNativeBackpropFilter:()=>rm,DepthwiseConv2dNativeBackpropInput:()=>nm,Diag:()=>am,Dilation2D:()=>Jp,Dilation2DBackpropFilter:()=>gf,Dilation2DBackpropInput:()=>mf,ENV:()=>Aa,EarlyStopping:()=>i6,Einsum:()=>Qp,Elu:()=>oi,EluGrad:()=>sm,Environment:()=>Ew,Equal:()=>Ko,Erf:()=>ju,Exp:()=>li,ExpandDims:()=>Xo,Expm1:()=>Zo,FFT:()=>im,Fill:()=>Hu,FlipLeftRight:()=>Yo,Floor:()=>ui,FloorDiv:()=>di,FromPixels:()=>Pp,FusedBatchNorm:()=>pi,FusedConv2D:()=>$s,FusedDepthwiseConv2D:()=>Ps,GPGPUContext:()=>Au,GatherNd:()=>Qo,GatherV2:()=>Jo,GraphModel:()=>m0,Greater:()=>el,GreaterEqual:()=>hi,History:()=>i4,IFFT:()=>om,Identity:()=>ci,Imag:()=>eh,InputSpec:()=>Kt,IsFinite:()=>qu,IsInf:()=>Ku,IsNan:()=>Xu,KernelBackend:()=>$u,LRN:()=>rh,LRNGrad:()=>um,LayerVariable:()=>Z7,LayersModel:()=>Xa,LeakyRelu:()=>fi,Less:()=>tl,LessEqual:()=>rl,LinSpace:()=>lm,Log:()=>mi,Log1p:()=>Zu,LogSoftmax:()=>Fw,LogicalAnd:()=>nl,LogicalNot:()=>Yu,LogicalOr:()=>th,MathBackendCPU:()=>qx,MathBackendWebGL:()=>Oh,Max:()=>gi,MaxPool:()=>Ai,MaxPool3D:()=>nh,MaxPool3DGrad:()=>pm,MaxPoolGrad:()=>dm,MaxPoolWithArgmax:()=>hm,Maximum:()=>yi,Mean:()=>xi,Min:()=>bi,Minimum:()=>vi,MirrorPad:()=>wi,Mod:()=>Ju,MomentumOptimizer:()=>jm,Multinomial:()=>cm,Multiply:()=>ki,Neg:()=>al,NonMaxSuppressionV3:()=>il,NonMaxSuppressionV4:()=>Qu,NonMaxSuppressionV5:()=>ol,NotEqual:()=>sl,OP_SCOPE_SUFFIX:()=>qw,OneHot:()=>ul,OnesLike:()=>ll,Optimizer:()=>ns,OptimizerConstructors:()=>ks,Pack:()=>dl,PadV2:()=>Ii,Pool:()=>PR,Pow:()=>Si,Prelu:()=>Ti,Prod:()=>Ni,RMSPropOptimizer:()=>Hm,RNN:()=>as,Range:()=>ed,Rank:()=>Ow,Real:()=>ah,RealDiv:()=>ii,Reciprocal:()=>td,Reduction:()=>P7,Relu:()=>Ci,Relu6:()=>Ri,Reshape:()=>pl,ResizeBilinear:()=>Ei,ResizeBilinearGrad:()=>mm,ResizeNearestNeighbor:()=>rd,ResizeNearestNeighborGrad:()=>fm,Reverse:()=>hl,RotateWithOffset:()=>Tl,Round:()=>cl,Rsqrt:()=>Mi,SGDOptimizer:()=>kh,ScatterNd:()=>fl,Select:()=>ml,Selu:()=>nd,Sequential:()=>i0,Sigmoid:()=>$i,Sign:()=>ad,Sin:()=>Fi,Sinh:()=>yl,Slice:()=>gl,Softmax:()=>zi,Softplus:()=>sd,SpaceToBatchND:()=>Al,SparseFillEmptyRows:()=>sh,SparseReshape:()=>id,SparseSegmentMean:()=>ih,SparseSegmentSum:()=>oh,SparseToDense:()=>lh,SplitV:()=>xl,Sqrt:()=>Pi,Square:()=>od,SquaredDifference:()=>Oi,Step:()=>Wi,StridedSlice:()=>bl,StringNGrams:()=>uh,StringSplit:()=>gm,StringToHashBucketFast:()=>ym,Sub:()=>Di,Sum:()=>_i,SymbolicTensor:()=>ua,Tan:()=>vl,Tanh:()=>Li,Tensor:()=>nt,TensorBuffer:()=>sr,Tile:()=>es,TopK:()=>wl,Transform:()=>kl,Transpose:()=>Bi,Unique:()=>Am,Unpack:()=>Il,UnsortedSegmentSum:()=>dh,Variable:()=>Op,ZerosLike:()=>Sl,_FusedMatMul:()=>Fs,abs:()=>rr,acos:()=>Tk,acosh:()=>Nk,add:()=>le,addN:()=>bm,all:()=>$2,any:()=>wf,argMax:()=>Cn,argMin:()=>Ck,asin:()=>Ek,asinh:()=>Rk,atan:()=>Mk,atan2:()=>Fk,atanh:()=>$k,avgPool:()=>vm,avgPool3d:()=>_2,backend:()=>zn,backend_util:()=>N,basicLSTMCell:()=>v$,batchNorm:()=>wu,batchNorm2d:()=>Ok,batchNorm3d:()=>Dk,batchNorm4d:()=>Lk,batchToSpaceND:()=>wm,bincount:()=>z2,booleanMaskAsync:()=>Pz,broadcastArgs:()=>Bk,broadcastTo:()=>Ep,broadcast_util:()=>Nl,browser:()=>_n,buffer:()=>We,callbacks:()=>hj,cast:()=>me,ceil:()=>Wk,clipByValue:()=>cn,clone:()=>Br,complex:()=>_s,concat:()=>kt,concat1d:()=>Vk,concat2d:()=>ud,concat3d:()=>Uk,concat4d:()=>Gk,constraints:()=>t4,conv1d:()=>O2,conv2d:()=>Os,conv2dTranspose:()=>L2,conv3d:()=>B2,conv3dTranspose:()=>Hk,copyRegisteredKernels:()=>DR,cos:()=>km,cosh:()=>W2,cosineWindow:()=>pA,cumprod:()=>If,cumsum:()=>V2,customGrad:()=>Fa,data:()=>M6,denseBincount:()=>qk,deprecationWarn:()=>R2,depthToSpace:()=>Kk,depthwiseConv2d:()=>Ah,deregisterOp:()=>mj,device_util:()=>fh,diag:()=>J$,dilation2d:()=>Xk,disableDeprecationWarnings:()=>OF,dispose:()=>re,disposeVariables:()=>DF,div:()=>pe,divNoNan:()=>Zk,dot:()=>sP,dropout:()=>S7,einsum:()=>Yk,elu:()=>xh,enableDebugMode:()=>zF,enableProdMode:()=>E2,enclosingPowerOfTwo:()=>T7,engine:()=>nr,env:()=>Y,equal:()=>En,erf:()=>Jk,exp:()=>Rn,expandDims:()=>qt,expm1:()=>Qk,eye:()=>U2,fft:()=>Pm,fill:()=>dd,findBackend:()=>F2,findBackendFactory:()=>VF,floor:()=>bh,floorDiv:()=>gh,forceHalfFloat:()=>QS,fused:()=>Bs,gather:()=>ku,gatherND:()=>I7,gather_util:()=>w2,getBackend:()=>Ur,getGradient:()=>uy,getKernel:()=>yf,getKernelsForBackend:()=>Ra,getThreadsCount:()=>y2e,gpgpu_util:()=>RS,grad:()=>RP,grads:()=>MP,greater:()=>fn,greaterEqual:()=>El,ifft:()=>Wp,imag:()=>Im,image:()=>Ie,inTopKAsync:()=>jz,initializers:()=>r4,input:()=>v4,io:()=>Tr,irfft:()=>iA,isFinite:()=>bP,isInf:()=>wP,isNaN:()=>e7,keep:()=>fr,kernel_impls:()=>qn,layers:()=>n4,leakyRelu:()=>Sm,less:()=>G2,lessEqual:()=>Rl,linalg:()=>_7,linspace:()=>t7,loadGraphModel:()=>AH,loadLayersModel:()=>kU,localResponseNormalization:()=>r7,log:()=>Mn,log1p:()=>Tm,logSigmoid:()=>OP,logSoftmax:()=>j2,logSumExp:()=>o7,logicalAnd:()=>fa,logicalNot:()=>Cm,logicalOr:()=>K2,logicalXor:()=>XP,losses:()=>ED,matMul:()=>Je,math:()=>ok,max:()=>gr,maxPool:()=>Em,maxPool3d:()=>X2,maxPoolWithArgmax:()=>l7,maximum:()=>ts,mean:()=>Wt,memory:()=>vf,meshgrid:()=>t_,metrics:()=>r6,min:()=>Ds,minimum:()=>vh,mirrorPad:()=>u7,mod:()=>hd,model:()=>vU,models:()=>n6,moments:()=>Rm,movingAverage:()=>Oz,mul:()=>L,multiRNNCell:()=>u_,multinomial:()=>d7,neg:()=>Ot,nextFrame:()=>fA,norm:()=>uA,notEqual:()=>Iu,oneHot:()=>Lp,ones:()=>hn,onesLike:()=>Fn,op:()=>W,outerProduct:()=>f_,pad:()=>Hn,pad1d:()=>y_,pad2d:()=>x_,pad3d:()=>v_,pad4d:()=>k_,pool:()=>C_,pow:()=>Ls,prelu:()=>Fm,print:()=>nk,prod:()=>Z2,profile:()=>LF,rand:()=>$_,randomGamma:()=>O_,randomNormal:()=>p7,randomUniform:()=>cd,range:()=>Su,ready:()=>ld,real:()=>Bp,reciprocal:()=>h7,registerBackend:()=>Cl,registerCallbackConstructor:()=>IU,registerGradient:()=>$w,registerKernel:()=>jn,registerOp:()=>fj,regularizers:()=>a6,relu:()=>_a,relu6:()=>Q2,removeBackend:()=>WF,reshape:()=>G,reverse:()=>$n,reverse1d:()=>H_,reverse2d:()=>K_,reverse3d:()=>Z_,reverse4d:()=>J_,rfft:()=>_m,round:()=>eA,rsqrt:()=>tA,scalar:()=>Se,scatterND:()=>k7,scatter_util:()=>k2,selu:()=>rA,separableConv2d:()=>c7,sequential:()=>wU,serialization:()=>ue,setBackend:()=>M2,setPlatform:()=>UF,setThreadsCount:()=>g2e,setWasmPath:()=>m2e,setWasmPaths:()=>Eb,setWebGLContext:()=>A0,setdiff1dAsync:()=>f7,shared:()=>g0,sigmoid:()=>Nr,sign:()=>m7,signal:()=>CD,sin:()=>nA,sinh:()=>aA,slice:()=>Pe,slice1d:()=>$m,slice2d:()=>sA,slice3d:()=>Ml,slice4d:()=>$o,slice_util:()=>zt,softmax:()=>fd,softplus:()=>pd,spaceToBatchND:()=>Mm,sparse:()=>bp,sparseToDense:()=>dA,spectral:()=>ND,split:()=>Xt,sqrt:()=>Er,square:()=>At,squaredDifference:()=>oA,squeeze:()=>rt,stack:()=>lr,step:()=>wh,stridedSlice:()=>g7,string:()=>rf,sub:()=>ce,sum:()=>ke,sumOutType:()=>ch,tan:()=>y7,tanh:()=>vu,tensor:()=>ct,tensor1d:()=>St,tensor2d:()=>pa,tensor3d:()=>uk,tensor4d:()=>Iz,tensor5d:()=>Sz,tensor6d:()=>Tz,tensor_util:()=>da,test_util:()=>kk,tidy:()=>K,tile:()=>Vn,time:()=>BF,topk:()=>A7,train:()=>go,transpose:()=>tt,truncatedNormal:()=>zm,unique:()=>wy,unregisterGradient:()=>OR,unregisterKernel:()=>zR,unsortedSegmentSum:()=>x7,unstack:()=>rn,upcastType:()=>Cr,util:()=>w,valueAndGrad:()=>FP,valueAndGrads:()=>$P,variable:()=>b7,variableGrads:()=>n7,version:()=>Hh,version_converter:()=>xH,version_core:()=>C2,version_cpu:()=>sK,version_layers:()=>OA,version_wasm:()=>A2e,version_webgl:()=>Ete,webgl:()=>Rte,webgl_util:()=>eS,webgpu:()=>nT,where:()=>Wr,whereAsync:()=>lA,zeros:()=>Pt,zerosLike:()=>at});var GE=Object.create,Gf=Object.defineProperty,jE=Object.getOwnPropertyDescriptor,yw=Object.getOwnPropertyNames,HE=Object.getPrototypeOf,qE=Object.prototype.hasOwnProperty,KE=e=>Gf(e,"__esModule",{value:!0}),ur=(e,t)=>function(){return t||(0,e[yw(e)[0]])((t={exports:{}}).exports,t),t.exports},Le=(e,t)=>{for(var r in t)Gf(e,r,{get:t[r],enumerable:!0})},XE=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of yw(t))!qE.call(e,a)&&(r||a!=="default")&&Gf(e,a,{get:()=>t[a],enumerable:!(n=jE(t,a))||n.enumerable});return e},Bo=(e,t)=>XE(KE(Gf(e!=null?GE(HE(e)):{},"default",!t&&e&&e.__esModule?{get:()=>e.default,enumerable:!0}:{value:e,enumerable:!0})),e),ZE=ur({"src/node_modules/long/src/long.js"(e,t){t.exports=n;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 n(I,z,O){this.low=I|0,this.high=z|0,this.unsigned=!!O}n.prototype.__isLong__,Object.defineProperty(n.prototype,"__isLong__",{value:!0});function a(I){return(I&&I.__isLong__)===!0}n.isLong=a;var s={},i={};function o(I,z){var O,j,X;return z?(I>>>=0,(X=0<=I&&I<256)&&(j=i[I],j)?j:(O=u(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=u(I,I<0?-1:0,!1),X&&(s[I]=O),O))}n.fromInt=o;function l(I,z){if(isNaN(I))return z?b:x;if(z){if(I<0)return b;if(I>=g)return R}else{if(I<=-y)return _;if(I+1>=y)return E}return I<0?l(-I,z).neg():u(I%m|0,I/m|0,z)}n.fromNumber=l;function u(I,z,O){return new n(I,z,O)}n.fromBits=u;var d=Math.pow;function h(I,z,O){if(I.length===0)throw Error("empty string");if(I==="NaN"||I==="Infinity"||I==="+Infinity"||I==="-Infinity")return x;if(typeof z=="number"?(O=z,z=!1):z=!!z,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 h(I.substring(1),z,O).neg();for(var X=l(d(O,8)),D=x,Q=0;Q<I.length;Q+=8){var V=Math.min(8,I.length-Q),ee=parseInt(I.substring(Q,Q+V),O);if(V<8){var J=l(d(O,V));D=D.mul(J).add(l(ee))}else D=D.mul(X),D=D.add(l(ee))}return D.unsigned=z,D}n.fromString=h;function p(I,z){return typeof I=="number"?l(I,z):typeof I=="string"?h(I,z):u(I.low,I.high,typeof z=="boolean"?z:I.unsigned)}n.fromValue=p;var c=1<<16,f=1<<24,m=c*c,g=m*m,y=g/2,A=o(f),x=o(0);n.ZERO=x;var b=o(0,!0);n.UZERO=b;var v=o(1);n.ONE=v;var S=o(1,!0);n.UONE=S;var T=o(-1);n.NEG_ONE=T;var E=u(-1,2147483647,!1);n.MAX_VALUE=E;var R=u(-1,-1,!0);n.MAX_UNSIGNED_VALUE=R;var _=u(0,-2147483648,!1);n.MIN_VALUE=_;var M=n.prototype;M.toInt=function(){return this.unsigned?this.low>>>0:this.low},M.toNumber=function(){return this.unsigned?(this.high>>>0)*m+(this.low>>>0):this.high*m+(this.low>>>0)},M.toString=function(I){if(I=I||10,I<2||36<I)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(_)){var z=l(I),O=this.div(z),j=O.mul(z).sub(this);return O.toString(I)+j.toInt().toString(I)}else return"-"+this.neg().toString(I);for(var X=l(d(I,6),this.unsigned),D=this,Q="";;){var V=D.div(X),ee=D.sub(V.mul(X)).toInt()>>>0,J=ee.toString(I);if(D=V,D.isZero())return J+Q;for(;J.length<6;)J="0"+J;Q=""+J+Q}},M.getHighBits=function(){return this.high},M.getHighBitsUnsigned=function(){return this.high>>>0},M.getLowBits=function(){return this.low},M.getLowBitsUnsigned=function(){return this.low>>>0},M.getNumBitsAbs=function(){if(this.isNegative())return this.eq(_)?64:this.neg().getNumBitsAbs();for(var I=this.high!=0?this.high:this.low,z=31;z>0&&(I&1<<z)==0;z--);return this.high!=0?z+33:z+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 a(I)||(I=p(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(a(I)||(I=p(I)),this.eq(I))return 0;var z=this.isNegative(),O=I.isNegative();return z&&!O?-1:!z&&O?1:this.unsigned?I.high>>>0>this.high>>>0||I.high===this.high&&I.low>>>0>this.low>>>0?-1:1:this.sub(I).isNegative()?-1:1},M.comp=M.compare,M.negate=function(){return!this.unsigned&&this.eq(_)?_:this.not().add(v)},M.neg=M.negate,M.add=function(I){a(I)||(I=p(I));var z=this.high>>>16,O=this.high&65535,j=this.low>>>16,X=this.low&65535,D=I.high>>>16,Q=I.high&65535,V=I.low>>>16,ee=I.low&65535,J=0,ie=0,Z=0,ae=0;return ae+=X+ee,Z+=ae>>>16,ae&=65535,Z+=j+V,ie+=Z>>>16,Z&=65535,ie+=O+Q,J+=ie>>>16,ie&=65535,J+=z+D,J&=65535,u(Z<<16|ae,J<<16|ie,this.unsigned)},M.subtract=function(I){return a(I)||(I=p(I)),this.add(I.neg())},M.sub=M.subtract,M.multiply=function(I){if(this.isZero())return x;if(a(I)||(I=p(I)),r){var z=r.mul(this.low,this.high,I.low,I.high);return u(z,r.get_high(),this.unsigned)}if(I.isZero())return x;if(this.eq(_))return I.isOdd()?_:x;if(I.eq(_))return this.isOdd()?_: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,D=this.low&65535,Q=I.high>>>16,V=I.high&65535,ee=I.low>>>16,J=I.low&65535,ie=0,Z=0,ae=0,de=0;return de+=D*J,ae+=de>>>16,de&=65535,ae+=X*J,Z+=ae>>>16,ae&=65535,ae+=D*ee,Z+=ae>>>16,ae&=65535,Z+=j*J,ie+=Z>>>16,Z&=65535,Z+=X*ee,ie+=Z>>>16,Z&=65535,Z+=D*V,ie+=Z>>>16,Z&=65535,ie+=O*J+j*ee+X*V+D*Q,ie&=65535,u(ae<<16|de,ie<<16|Z,this.unsigned)},M.mul=M.multiply,M.divide=function(I){if(a(I)||(I=p(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 z=(this.unsigned?r.div_u:r.div_s)(this.low,this.high,I.low,I.high);return u(z,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 S;X=b}else{if(this.eq(_)){if(I.eq(v)||I.eq(T))return _;if(I.eq(_))return v;var D=this.shr(1);return O=D.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(_))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 Q=Math.ceil(Math.log(O)/Math.LN2),V=Q<=48?1:d(2,Q-48),ee=l(O),J=ee.mul(I);J.isNegative()||J.gt(j);)O-=V,ee=l(O,this.unsigned),J=ee.mul(I);ee.isZero()&&(ee=v),X=X.add(ee),j=j.sub(J)}return X},M.div=M.divide,M.modulo=function(I){if(a(I)||(I=p(I)),r){var z=(this.unsigned?r.rem_u:r.rem_s)(this.low,this.high,I.low,I.high);return u(z,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 u(~this.low,~this.high,this.unsigned)},M.and=function(I){return a(I)||(I=p(I)),u(this.low&I.low,this.high&I.high,this.unsigned)},M.or=function(I){return a(I)||(I=p(I)),u(this.low|I.low,this.high|I.high,this.unsigned)},M.xor=function(I){return a(I)||(I=p(I)),u(this.low^I.low,this.high^I.high,this.unsigned)},M.shiftLeft=function(I){return a(I)&&(I=I.toInt()),(I&=63)===0?this:I<32?u(this.low<<I,this.high<<I|this.low>>>32-I,this.unsigned):u(0,this.low<<I-32,this.unsigned)},M.shl=M.shiftLeft,M.shiftRight=function(I){return a(I)&&(I=I.toInt()),(I&=63)===0?this:I<32?u(this.low>>>I|this.high<<32-I,this.high>>I,this.unsigned):u(this.high>>I-32,this.high>=0?0:-1,this.unsigned)},M.shr=M.shiftRight,M.shiftRightUnsigned=function(I){if(a(I)&&(I=I.toInt()),I&=63,I===0)return this;var z=this.high;if(I<32){var O=this.low;return u(O>>>I|z<<32-I,z>>>I,this.unsigned)}else return I===32?u(z,0,this.unsigned):u(z>>>I-32,0,this.unsigned)},M.shru=M.shiftRightUnsigned,M.shr_u=M.shiftRightUnsigned,M.toSigned=function(){return this.unsigned?u(this.low,this.high,!1):this},M.toUnsigned=function(){return this.unsigned?this:u(this.low,this.high,!0)},M.toBytes=function(I){return I?this.toBytesLE():this.toBytesBE()},M.toBytesLE=function(){var I=this.high,z=this.low;return[z&255,z>>>8&255,z>>>16&255,z>>>24,I&255,I>>>8&255,I>>>16&255,I>>>24]},M.toBytesBE=function(){var I=this.high,z=this.low;return[I>>>24,I>>>16&255,I>>>8&255,I&255,z>>>24,z>>>16&255,z>>>8&255,z&255]},n.fromBytes=function(I,z,O){return O?n.fromBytesLE(I,z):n.fromBytesBE(I,z)},n.fromBytesLE=function(I,z){return new n(I[0]|I[1]<<8|I[2]<<16|I[3]<<24,I[4]|I[5]<<8|I[6]<<16|I[7]<<24,z)},n.fromBytesBE=function(I,z){return new n(I[4]<<24|I[5]<<16|I[6]<<8|I[7],I[0]<<24|I[1]<<16|I[2]<<8|I[3],z)}}}),YE=ur({"(disabled):src/node_modules/node-fetch/browser.js"(){}}),JE=ur({"(disabled):util"(){}}),QE=ur({"src/node_modules/seedrandom/lib/alea.js"(e,t){(function(r,n,a){function s(u){var d=this,h=l();d.next=function(){var p=2091639*d.s0+d.c*23283064365386963e-26;return d.s0=d.s1,d.s1=d.s2,d.s2=p-(d.c=p|0)},d.c=1,d.s0=h(" "),d.s1=h(" "),d.s2=h(" "),d.s0-=h(u),d.s0<0&&(d.s0+=1),d.s1-=h(u),d.s1<0&&(d.s1+=1),d.s2-=h(u),d.s2<0&&(d.s2+=1),h=null}function i(u,d){return d.c=u.c,d.s0=u.s0,d.s1=u.s1,d.s2=u.s2,d}function o(u,d){var h=new s(u),p=d&&d.state,c=h.next;return c.int32=function(){return h.next()*4294967296|0},c.double=function(){return c()+(c()*2097152|0)*11102230246251565e-32},c.quick=c,p&&(typeof p=="object"&&i(p,h),c.state=function(){return i(h,{})}),c}function l(){var u=4022871197,d=function(h){h=String(h);for(var p=0;p<h.length;p++){u+=h.charCodeAt(p);var c=.02519603282416938*u;u=c>>>0,c-=u,c*=u,u=c>>>0,c-=u,u+=c*4294967296}return(u>>>0)*23283064365386963e-26};return d}n&&n.exports?n.exports=o:a&&a.amd?a(function(){return o}):this.alea=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),eR=ur({"src/node_modules/seedrandom/lib/xor128.js"(e,t){(function(r,n,a){function s(l){var u=this,d="";u.x=0,u.y=0,u.z=0,u.w=0,u.next=function(){var p=u.x^u.x<<11;return u.x=u.y,u.y=u.z,u.z=u.w,u.w^=u.w>>>19^p^p>>>8},l===(l|0)?u.x=l:d+=l;for(var h=0;h<d.length+64;h++)u.x^=d.charCodeAt(h)|0,u.next()}function i(l,u){return u.x=l.x,u.y=l.y,u.z=l.z,u.w=l.w,u}function o(l,u){var d=new s(l),h=u&&u.state,p=function(){return(d.next()>>>0)/4294967296};return p.double=function(){do var c=d.next()>>>11,f=(d.next()>>>0)/4294967296,m=(c+f)/(1<<21);while(m===0);return m},p.int32=d.next,p.quick=p,h&&(typeof h=="object"&&i(h,d),p.state=function(){return i(d,{})}),p}n&&n.exports?n.exports=o:a&&a.amd?a(function(){return o}):this.xor128=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),tR=ur({"src/node_modules/seedrandom/lib/xorwow.js"(e,t){(function(r,n,a){function s(l){var u=this,d="";u.next=function(){var p=u.x^u.x>>>2;return u.x=u.y,u.y=u.z,u.z=u.w,u.w=u.v,(u.d=u.d+362437|0)+(u.v=u.v^u.v<<4^(p^p<<1))|0},u.x=0,u.y=0,u.z=0,u.w=0,u.v=0,l===(l|0)?u.x=l:d+=l;for(var h=0;h<d.length+64;h++)u.x^=d.charCodeAt(h)|0,h==d.length&&(u.d=u.x<<10^u.x>>>4),u.next()}function i(l,u){return u.x=l.x,u.y=l.y,u.z=l.z,u.w=l.w,u.v=l.v,u.d=l.d,u}function o(l,u){var d=new s(l),h=u&&u.state,p=function(){return(d.next()>>>0)/4294967296};return p.double=function(){do var c=d.next()>>>11,f=(d.next()>>>0)/4294967296,m=(c+f)/(1<<21);while(m===0);return m},p.int32=d.next,p.quick=p,h&&(typeof h=="object"&&i(h,d),p.state=function(){return i(d,{})}),p}n&&n.exports?n.exports=o:a&&a.amd?a(function(){return o}):this.xorwow=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),rR=ur({"src/node_modules/seedrandom/lib/xorshift7.js"(e,t){(function(r,n,a){function s(l){var u=this;u.next=function(){var h=u.x,p=u.i,c,f,m;return c=h[p],c^=c>>>7,f=c^c<<24,c=h[p+1&7],f^=c^c>>>10,c=h[p+3&7],f^=c^c>>>3,c=h[p+4&7],f^=c^c<<7,c=h[p+7&7],c=c^c<<13,f^=c^c<<9,h[p]=f,u.i=p+1&7,f};function d(h,p){var c,f,m=[];if(p===(p|0))f=m[0]=p;else for(p=""+p,c=0;c<p.length;++c)m[c&7]=m[c&7]<<15^p.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],h.x=m,h.i=0,c=256;c>0;--c)h.next()}d(u,l)}function i(l,u){return u.x=l.x.slice(),u.i=l.i,u}function o(l,u){l==null&&(l=+new Date);var d=new s(l),h=u&&u.state,p=function(){return(d.next()>>>0)/4294967296};return p.double=function(){do var c=d.next()>>>11,f=(d.next()>>>0)/4294967296,m=(c+f)/(1<<21);while(m===0);return m},p.int32=d.next,p.quick=p,h&&(h.x&&i(h,d),p.state=function(){return i(d,{})}),p}n&&n.exports?n.exports=o:a&&a.amd?a(function(){return o}):this.xorshift7=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),nR=ur({"src/node_modules/seedrandom/lib/xor4096.js"(e,t){(function(r,n,a){function s(l){var u=this;u.next=function(){var h=u.w,p=u.X,c=u.i,f,m;return u.w=h=h+1640531527|0,m=p[c+34&127],f=p[c=c+1&127],m^=m<<13,f^=f<<17,m^=m>>>15,f^=f>>>12,m=p[c]=m^f,u.i=c,m+(h^h>>>16)|0};function d(h,p){var c,f,m,g,y,A=[],x=128;for(p===(p|0)?(f=p,p=null):(p=p+"\0",f=0,x=Math.max(x,p.length)),m=0,g=-32;g<x;++g)p&&(f^=p.charCodeAt((g+32)%p.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[(p&&p.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;h.w=y,h.X=A,h.i=m}d(u,l)}function i(l,u){return u.i=l.i,u.w=l.w,u.X=l.X.slice(),u}function o(l,u){l==null&&(l=+new Date);var d=new s(l),h=u&&u.state,p=function(){return(d.next()>>>0)/4294967296};return p.double=function(){do var c=d.next()>>>11,f=(d.next()>>>0)/4294967296,m=(c+f)/(1<<21);while(m===0);return m},p.int32=d.next,p.quick=p,h&&(h.X&&i(h,d),p.state=function(){return i(d,{})}),p}n&&n.exports?n.exports=o:a&&a.amd?a(function(){return o}):this.xor4096=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),aR=ur({"src/node_modules/seedrandom/lib/tychei.js"(e,t){(function(r,n,a){function s(l){var u=this,d="";u.next=function(){var p=u.b,c=u.c,f=u.d,m=u.a;return p=p<<25^p>>>7^c,c=c-f|0,f=f<<24^f>>>8^m,m=m-p|0,u.b=p=p<<20^p>>>12^c,u.c=c=c-f|0,u.d=f<<16^c>>>16^m,u.a=m-p|0},u.a=0,u.b=0,u.c=-1640531527,u.d=1367130551,l===Math.floor(l)?(u.a=l/4294967296|0,u.b=l|0):d+=l;for(var h=0;h<d.length+20;h++)u.b^=d.charCodeAt(h)|0,u.next()}function i(l,u){return u.a=l.a,u.b=l.b,u.c=l.c,u.d=l.d,u}function o(l,u){var d=new s(l),h=u&&u.state,p=function(){return(d.next()>>>0)/4294967296};return p.double=function(){do var c=d.next()>>>11,f=(d.next()>>>0)/4294967296,m=(c+f)/(1<<21);while(m===0);return m},p.int32=d.next,p.quick=p,h&&(typeof h=="object"&&i(h,d),p.state=function(){return i(d,{})}),p}n&&n.exports?n.exports=o:a&&a.amd?a(function(){return o}):this.tychei=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),sR=ur({"(disabled):crypto"(){}}),iR=ur({"src/node_modules/seedrandom/seedrandom.js"(e,t){(function(r,n,a){var s=256,i=6,o=52,l="random",u=a.pow(s,i),d=a.pow(2,o),h=d*2,p=s-1,c;function f(v,S,T){var E=[];S=S==!0?{entropy:!0}:S||{};var R=A(y(S.entropy?[v,b(n)]:v==null?x():v,3),E),_=new m(E),M=function(){for(var I=_.g(i),z=u,O=0;I<d;)I=(I+O)*s,z*=s,O=_.g(1);for(;I>=h;)I/=2,z/=2,O>>>=1;return(I+O)/z};return M.int32=function(){return _.g(4)|0},M.quick=function(){return _.g(4)/4294967296},M.double=M,A(b(_.S),n),(S.pass||T||function(I,z,O,j){return j&&(j.S&&g(j,_),I.state=function(){return g(_,{})}),O?(a[l]=I,z):I})(M,R,"global"in S?S.global:this==a,S.state)}function m(v){var S,T=v.length,E=this,R=0,_=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[_=p&_+v[R%T]+(S=M[R])],M[_]=S;(E.g=function(I){for(var z,O=0,j=E.i,X=E.j,D=E.S;I--;)z=D[j=p&j+1],O=O*s+D[p&(D[j]=D[X=p&X+z])+(D[X]=z)];return E.i=j,E.j=X,O})(s)}function g(v,S){return S.i=v.i,S.j=v.j,S.S=v.S.slice(),S}function y(v,S){var T=[],E=typeof v,R;if(S&&E=="object")for(R in v)try{T.push(y(v[R],S-1))}catch(_){}return T.length?T:E=="string"?v:v+"\0"}function A(v,S){for(var T=v+"",E,R=0;R<T.length;)S[p&R]=p&(E^=S[p&R]*19)+T.charCodeAt(R++);return b(S)}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 S=r.navigator,T=S&&S.plugins;return[+new Date,r,T,r.screen,b(n)]}}function b(v){return String.fromCharCode.apply(0,v)}if(A(a.random(),n),typeof t=="object"&&t.exports){t.exports=f;try{c=sR()}catch(v){}}else typeof define=="function"&&define.amd?define(function(){return f}):a["seed"+l]=f})(typeof self!="undefined"?self:e,[],Math)}}),jf=ur({"src/node_modules/seedrandom/index.js"(e,t){var r=QE(),n=eR(),a=tR(),s=rR(),i=nR(),o=aR(),l=iR();l.alea=r,l.xor128=n,l.xorwow=a,l.xorshift7=s,l.xor4096=i,l.tychei=o,t.exports=l}}),Aw=ur({"(disabled):src/node_modules/string_decoder/index.js"(){}}),u2=ur({"(disabled):fs"(){}}),hf=ur({"(disabled):path"(){}}),oR=ur({"(disabled):worker_threads"(){}}),lR=ur({"(disabled):perf_hooks"(){}}),uR=ur({"(disabled):os"(){}}),dR=ur({"src/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm-threaded-simd.js"(e,t){var r=(()=>{var n=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(n=n||__filename),function(a){a=a||{};function s(){return $e.buffer!=Pr&&ea($e.buffer),oc}function i(){return $e.buffer!=Pr&&ea($e.buffer),lc}function o(){return $e.buffer!=Pr&&ea($e.buffer),ep}function l(){return $e.buffer!=Pr&&ea($e.buffer),uc}function u(){return $e.buffer!=Pr&&ea($e.buffer),dc}function d(){return $e.buffer!=Pr&&ea($e.buffer),pc}function h(){return $e.buffer!=Pr&&ea($e.buffer),hc}var p=typeof a!="undefined"?a:{},c,f;p.ready=new Promise(function(C,$){c=C,f=$});var m;typeof process!="undefined"&&process.listeners&&(m={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var g=Object.assign({},p),y=[],A="./this.program",x=(C,$)=>{throw $},b=typeof window=="object",v=typeof importScripts=="function",S=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",T=p.ENVIRONMENT_IS_PTHREAD||!1,E="";function R(C){return p.locateFile?p.locateFile(C,E):E+C}var _,M,I,z;function O(C){C instanceof up||J("exiting due to exception: "+C)}var j,X,D;if(S){v?E=hf().dirname(E)+"/":E=__dirname+"/",D=()=>{X||(j=u2(),X=hf())},_=function($,U){return D(),$=X.normalize($),j.readFileSync($,U?void 0:"utf8")},I=$=>{var U=_($,!0);return U.buffer||(U=new Uint8Array(U)),U},M=($,U,te)=>{D(),$=X.normalize($),j.readFile($,function(ge,xe){ge?te(ge):U(xe.buffer)})},process.argv.length>1&&(A=process.argv[1].replace(/\\/g,"/")),y=process.argv.slice(2),process.on("uncaughtException",function($){if(!($ instanceof up))throw $}),process.on("unhandledRejection",function($){throw $}),x=($,U)=>{if(oo())throw process.exitCode=$,U;O(U),process.exit($)},p.inspect=function(){return"[Emscripten Module object]"};let C;try{C=oR()}catch($){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),$}global.Worker=C.Worker}else(b||v)&&(v?E=self.location.href:typeof document!="undefined"&&document.currentScript&&(E=document.currentScript.src),typeof n!="undefined"&&n&&(E=n),E.indexOf("blob:")!==0?E=E.substr(0,E.replace(/[?#].*/,"").lastIndexOf("/")+1):E="",S||(_=C=>{var $=new XMLHttpRequest;return $.open("GET",C,!1),$.send(null),$.responseText},v&&(I=C=>{var $=new XMLHttpRequest;return $.open("GET",C,!1),$.responseType="arraybuffer",$.send(null),new Uint8Array($.response)}),M=(C,$,U)=>{var te=new XMLHttpRequest;te.open("GET",C,!0),te.responseType="arraybuffer",te.onload=()=>{if(te.status==200||te.status==0&&te.response){$(te.response);return}U()},te.onerror=U,te.send(null)}),z=C=>document.title=C);S&&typeof performance=="undefined"&&(global.performance=lR().performance);var Q=console.log.bind(console),V=console.warn.bind(console);S&&(D(),Q=C=>j.writeSync(1,C+`
|
|
`),V=C=>j.writeSync(2,C+`
|
|
`));var ee=p.print||Q,J=p.printErr||V;Object.assign(p,g),g=null,p.arguments&&(y=p.arguments),p.thisProgram&&(A=p.thisProgram),p.quit&&(x=p.quit);var ie=4;function Z(C){Z.shown||(Z.shown={}),Z.shown[C]||(Z.shown[C]=1,J(C))}function ae(C,$){if(typeof WebAssembly.Function=="function"){for(var U={i:"i32",j:"i64",f:"f32",d:"f64"},te={parameters:[],results:$[0]=="v"?[]:[U[$[0]]]},ge=1;ge<$.length;++ge)te.parameters.push(U[$[ge]]);return new WebAssembly.Function(te,C)}var xe=[1,0,1,96],Ne=$.slice(0,1),_e=$.slice(1),$t={i:127,j:126,f:125,d:124};xe.push(_e.length);for(var ge=0;ge<_e.length;++ge)xe.push($t[_e[ge]]);Ne=="v"?xe.push(0):xe=xe.concat([1,$t[Ne]]),xe[1]=xe.length-2;var aa=new Uint8Array([0,97,115,109,1,0,0,0].concat(xe,[2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0])),sa=new WebAssembly.Module(aa),Wc=new WebAssembly.Instance(sa,{e:{f:C}}),dp=Wc.exports.f;return dp}var de=[],Ae;function be(){if(de.length)return de.pop();try{kn.grow(1)}catch(C){throw C instanceof RangeError?"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.":C}return kn.length-1}function Ee(C,$){for(var U=C;U<C+$;U++){var te=Jl(U);te&&Ae.set(te,U)}}var Me=0,De=C=>{Me=C},Be=Atomics.load,Ze=Atomics.store,ot=Atomics.compareExchange,dt;p.wasmBinary&&(dt=p.wasmBinary);var pt=p.noExitRuntime||!0;typeof WebAssembly!="object"&&Xl("no native wasm support detected");var $e,vt,yt=!1,$r;function pr(C,$){C||Xl($)}function Yr(C){var $=p["_"+C];return $}function er(C,$,U,te,ge){var xe={string:function(In){var su=0;if(In!=null&&In!==0){var C3=(In.length<<2)+1;su=au(C3),so(In,su,C3)}return su},array:function(In){var su=au(In.length);return Ua(In,su),su}};function Ne(In){return $==="string"?wn(In):$==="boolean"?Boolean(In):In}var _e=Yr(C),$t=[],aa=0;if(te)for(var sa=0;sa<te.length;sa++){var Wc=xe[U[sa]];Wc?(aa===0&&(aa=j1()),$t[sa]=Wc(te[sa])):$t[sa]=te[sa]}var dp=_e.apply(null,$t);function OE(In){return aa!==0&&Oc(aa),Ne(In)}return dp=OE(dp),dp}function hr(C,$,U,te){U=U||[];var ge=U.every(function(Ne){return Ne==="number"}),xe=$!=="string";return xe&&ge&&!te?Yr(C):function(){return er(C,$,U,arguments,te)}}var Qn=1;function Jr(C){var $=new TextDecoder(C);this.decode=U=>(U.buffer instanceof SharedArrayBuffer&&(U=new Uint8Array(U)),$.decode.call($,U))}var tr=typeof TextDecoder!="undefined"?new Jr("utf8"):void 0;function vn(C,$,U){for(var te=$+U,ge=$;C[ge]&&!(ge>=te);)++ge;if(ge-$>16&&C.subarray&&tr)return tr.decode(C.subarray($,ge));for(var xe="";$<ge;){var Ne=C[$++];if(!(Ne&128)){xe+=String.fromCharCode(Ne);continue}var _e=C[$++]&63;if((Ne&224)==192){xe+=String.fromCharCode((Ne&31)<<6|_e);continue}var $t=C[$++]&63;if((Ne&240)==224?Ne=(Ne&15)<<12|_e<<6|$t:Ne=(Ne&7)<<18|_e<<12|$t<<6|C[$++]&63,Ne<65536)xe+=String.fromCharCode(Ne);else{var aa=Ne-65536;xe+=String.fromCharCode(55296|aa>>10,56320|aa&1023)}}return xe}function wn(C,$){return C?vn(i(),C,$):""}function ms(C,$,U,te){if(!(te>0))return 0;for(var ge=U,xe=U+te-1,Ne=0;Ne<C.length;++Ne){var _e=C.charCodeAt(Ne);if(_e>=55296&&_e<=57343){var $t=C.charCodeAt(++Ne);_e=65536+((_e&1023)<<10)|$t&1023}if(_e<=127){if(U>=xe)break;$[U++]=_e}else if(_e<=2047){if(U+1>=xe)break;$[U++]=192|_e>>6,$[U++]=128|_e&63}else if(_e<=65535){if(U+2>=xe)break;$[U++]=224|_e>>12,$[U++]=128|_e>>6&63,$[U++]=128|_e&63}else{if(U+3>=xe)break;$[U++]=240|_e>>18,$[U++]=128|_e>>12&63,$[U++]=128|_e>>6&63,$[U++]=128|_e&63}}return $[U]=0,U-ge}function so(C,$,U){return ms(C,i(),$,U)}function ic(C){for(var $=0,U=0;U<C.length;++U){var te=C.charCodeAt(U);te>=55296&&te<=57343&&(te=65536+((te&1023)<<10)|C.charCodeAt(++U)&1023),te<=127?++$:te<=2047?$+=2:te<=65535?$+=3:$+=4}return $}var gs=typeof TextDecoder!="undefined"?new Jr("utf-16le"):void 0;function Ua(C,$){s().set(C,$)}function Qd(C,$,U){for(var te=0;te<C.length;++te)s()[$++>>0]=C.charCodeAt(te);U||(s()[$>>0]=0)}function ql(C,$){return C%$>0&&(C+=$-C%$),C}var Pr,oc,lc,ep,uc,dc,l3,pc,hc;T&&(Pr=p.buffer);function ea(C){Pr=C,p.HEAP8=oc=new Int8Array(C),p.HEAP16=ep=new Int16Array(C),p.HEAP32=dc=new Int32Array(C),p.HEAPU8=lc=new Uint8Array(C),p.HEAPU16=uc=new Uint16Array(C),p.HEAPU32=l3=new Uint32Array(C),p.HEAPF32=pc=new Float32Array(C),p.HEAPF64=hc=new Float64Array(C)}var cc=p.INITIAL_MEMORY||16777216;if(T)$e=p.wasmMemory,Pr=p.buffer;else if(p.wasmMemory)$e=p.wasmMemory;else if($e=new WebAssembly.Memory({initial:cc/65536,maximum:32768,shared:!0}),!($e.buffer instanceof SharedArrayBuffer))throw J("requested a shared WebAssembly.Memory but the returned buffer is not a SharedArrayBuffer, indicating that while the browser has SharedArrayBuffer it does not have WebAssembly threads support - you may need to set a flag"),S&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");$e&&(Pr=$e.buffer),cc=Pr.byteLength,ea(Pr);var kn,Kl=[],ys=[],gg=[],fc=[],io=!1,yg=!1,mc=0;function oo(){return pt||mc>0}function _r(){if(p.preRun)for(typeof p.preRun=="function"&&(p.preRun=[p.preRun]);p.preRun.length;)u3(p.preRun.shift());bc(Kl)}function tp(){io=!0,!T&&bc(ys)}function Ag(){T||(Oe.terminateAllThreads(),yg=!0)}function xg(){if(!T){if(p.postRun)for(typeof p.postRun=="function"&&(p.postRun=[p.postRun]);p.postRun.length;)rp(p.postRun.shift());bc(fc)}}function u3(C){Kl.unshift(C)}function d3(C){ys.unshift(C)}function rp(C){fc.unshift(C)}var As=0,gc=null,ta=null;function np(C){As++,p.monitorRunDependencies&&p.monitorRunDependencies(As)}function p3(C){if(As--,p.monitorRunDependencies&&p.monitorRunDependencies(As),As==0&&(gc!==null&&(clearInterval(gc),gc=null),ta)){var $=ta;ta=null,$()}}p.preloadedImages={},p.preloadedAudios={};function Xl(C){T?postMessage({cmd:"onAbort",arg:C}):p.onAbort&&p.onAbort(C),C="Aborted("+C+")",J(C),yt=!0,$r=1,C+=". Build with -s ASSERTIONS=1 for more info.";var $=new WebAssembly.RuntimeError(C);throw f($),$}var bg="data:application/octet-stream;base64,";function yc(C){return C.startsWith(bg)}function Ac(C){return C.startsWith("file://")}var zr;zr="tfjs-backend-wasm-threaded-simd.wasm",yc(zr)||(zr=R(zr));function xc(C){try{if(C==zr&&dt)return new Uint8Array(dt);if(I)return I(C);throw"both async and sync fetching of the wasm failed"}catch($){Xl($)}}function Zl(){if(!dt&&(b||v)){if(typeof fetch=="function"&&!Ac(zr))return fetch(zr,{credentials:"same-origin"}).then(function(C){if(!C.ok)throw"failed to load wasm binary file at '"+zr+"'";return C.arrayBuffer()}).catch(function(){return xc(zr)});if(M)return new Promise(function(C,$){M(zr,function(U){C(new Uint8Array(U))},$)})}return Promise.resolve().then(function(){return xc(zr)})}function vg(){var C={env:Fc,wasi_snapshot_preview1:Fc};function $(Ne,_e){var $t=Ne.exports;if(p.asm=$t,Cg(p.asm.emscripten_tls_init),kn=p.asm.__indirect_function_table,d3(p.asm.__wasm_call_ctors),vt=_e,!T){var aa=Oe.unusedWorkers.length;Oe.unusedWorkers.forEach(function(sa){Oe.loadWasmModuleToWorker(sa,function(){--aa||p3("wasm-instantiate")})})}}T||np("wasm-instantiate");function U(Ne){$(Ne.instance,Ne.module)}function te(Ne){return Zl().then(function(_e){return WebAssembly.instantiate(_e,C)}).then(function(_e){return _e}).then(Ne,function(_e){J("failed to asynchronously prepare wasm: "+_e),Xl(_e)})}function ge(){return!dt&&typeof WebAssembly.instantiateStreaming=="function"&&!yc(zr)&&!Ac(zr)&&typeof fetch=="function"?fetch(zr,{credentials:"same-origin"}).then(function(Ne){var _e=WebAssembly.instantiateStreaming(Ne,C);return _e.then(U,function($t){return J("wasm streaming compile failed: "+$t),J("falling back to ArrayBuffer instantiation"),te(U)})}):te(U)}if(p.instantiateWasm)try{var xe=p.instantiateWasm(C,$);return xe}catch(Ne){return J("Module.instantiateWasm callback failed with error: "+Ne),!1}return ge().catch(f),{}}var h3,c3,wg={};function bc(C){for(;C.length>0;){var $=C.shift();if(typeof $=="function"){$(p);continue}var U=$.func;typeof U=="number"?$.arg===void 0?Jl(U)():Jl(U)($.arg):U($.arg===void 0?null:$.arg)}}function Yl(C){var $=j1(),U=C();return Oc($),U}function j9(C){return C}function f3(C){var $=/\b_Z[\w\d_]+/g;return C.replace($,function(U){var te=U;return U===te?U:te+" ["+U+"]"})}function kg(C){u()[C>>2]=0;var $=Oe.pthreads[C];delete Oe.pthreads[C],$.worker.terminate(),G1(C),Oe.runningWorkers.splice(Oe.runningWorkers.indexOf($.worker),1),$.worker.pthread=void 0}function Ig(C){var $=Oe.pthreads[C];$.worker.postMessage({cmd:"cancel"})}function vc(C){var $=Oe.pthreads[C];if($){u()[C>>2]=0;var U=$.worker;Oe.returnWorkerToPool(U)}}function wc(C){PE(C)}function Sg(C){if(C instanceof up||C=="unwind")return $r;x(1,C)}var Oe={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],init:function(){T?Oe.initWorker():Oe.initMainThread()},initMainThread:function(){for(var C=8,$=0;$<C;++$)Oe.allocateUnusedWorker()},initWorker:function(){pt=!1},pthreads:{},setExitStatus:function(C){$r=C},terminateAllThreads:function(){for(var C in Oe.pthreads){var $=Oe.pthreads[C];$&&$.worker&&Oe.returnWorkerToPool($.worker)}for(var U=0;U<Oe.unusedWorkers.length;++U){var te=Oe.unusedWorkers[U];te.terminate()}Oe.unusedWorkers=[]},returnWorkerToPool:function(C){Oe.runWithoutMainThreadQueuedCalls(function(){delete Oe.pthreads[C.pthread.threadInfoStruct],Oe.unusedWorkers.push(C),Oe.runningWorkers.splice(Oe.runningWorkers.indexOf(C),1),G1(C.pthread.threadInfoStruct),C.pthread=void 0})},runWithoutMainThreadQueuedCalls:function(C){u()[N3>>2]=0;try{C()}finally{u()[N3>>2]=1}},receiveObjectTransfer:function(C){},threadInit:function(){for(var C in Oe.tlsInitFunctions)Oe.tlsInitFunctions[C]()},loadWasmModuleToWorker:function(C,$){C.onmessage=U=>{var te=U.data,ge=te.cmd;if(C.pthread&&(Oe.currentProxiedOperationCallerThread=C.pthread.threadInfoStruct),te.targetThread&&te.targetThread!=zc()){var xe=Oe.pthreads[te.targetThread];xe?xe.worker.postMessage(te,te.transferList):J('Internal error! Worker sent a message "'+ge+'" to target pthread '+te.targetThread+", but that thread no longer exists!"),Oe.currentProxiedOperationCallerThread=void 0;return}ge==="processQueuedMainThreadWork"?w3():ge==="spawnThread"?Ic(te):ge==="cleanupThread"?vc(te.thread):ge==="killThread"?kg(te.thread):ge==="cancelThread"?Ig(te.thread):ge==="loaded"?(C.loaded=!0,$&&$(C),C.runPthread&&(C.runPthread(),delete C.runPthread)):ge==="print"?ee("Thread "+te.threadId+": "+te.text):ge==="printErr"?J("Thread "+te.threadId+": "+te.text):ge==="alert"?alert("Thread "+te.threadId+": "+te.text):te.target==="setimmediate"?C.postMessage(te):ge==="onAbort"?p.onAbort&&p.onAbort(te.arg):J("worker sent an unknown command "+ge),Oe.currentProxiedOperationCallerThread=void 0},C.onerror=U=>{var te="worker sent an error!";throw J(te+" "+U.filename+":"+U.lineno+": "+U.message),U},S&&(C.on("message",function(U){C.onmessage({data:U})}),C.on("error",function(U){C.onerror(U)}),C.on("detachedExit",function(){})),C.postMessage({cmd:"load",urlOrBlob:p.mainScriptUrlOrBlob||n,wasmMemory:$e,wasmModule:vt})},allocateUnusedWorker:function(){var C=R("tfjs-backend-wasm-threaded-simd.worker.js");Oe.unusedWorkers.push(new Worker(C))},getNewWorker:function(){return Oe.unusedWorkers.length==0&&(Oe.allocateUnusedWorker(),Oe.loadWasmModuleToWorker(Oe.unusedWorkers[0])),Oe.unusedWorkers.pop()}};function Tg(){var C=zc(),$=u()[C+44>>2],U=u()[C+48>>2],te=$-U;T3($,te),Oc($)}p.establishStackSpace=Tg;function kc(C){if(T)return po(1,0,C);try{wc(C)}catch($){Sg($)}}var lo=[];function Jl(C){var $=lo[C];return $||(C>=lo.length&&(lo.length=C+1),lo[C]=$=kn.get(C)),$}function Ng(C,$){return Jl(C)($)}p.invokeEntryPoint=Ng;function m3(){var C=new Error;if(!C.stack){try{throw new Error}catch($){C=$}if(!C.stack)return"(no stack trace available)"}return C.stack.toString()}function Cg(C,$,U){Oe.tlsInitFunctions.push(C)}function g3(C,$){kn.set(C,$),lo[C]=$}var uo;S?uo=()=>{var C=process.hrtime();return C[0]*1e3+C[1]/1e6}:T?uo=()=>performance.now()-p.__performance_now_clock_drift:uo=()=>performance.now();var Eg=!0;function Rg(C){return u()[v3()>>2]=C,C}function Mg(C,$){var U;if(C===0)U=Date.now();else if((C===1||C===4)&&Eg)U=uo();else return Rg(28),-1;return u()[$>>2]=U/1e3|0,u()[$+4>>2]=U%1e3*1e3*1e3|0,0}function Fg(C,$){return Mg(C,$)}function $g(C){k3(C,!v,1,!b),Oe.threadInit()}function Pg(C){T?postMessage({cmd:"cleanupThread",thread:C}):vc(C)}function Ic(C){var $=Oe.getNewWorker();if(!$)return 6;Oe.runningWorkers.push($);var U=Oe.pthreads[C.pthread_ptr]={worker:$,threadInfoStruct:C.pthread_ptr};$.pthread=U;var te={cmd:"run",start_routine:C.startRoutine,arg:C.arg,threadInfoStruct:C.pthread_ptr};return $.runPthread=()=>{te.time=performance.now(),$.postMessage(te,C.transferList)},$.loaded&&($.runPthread(),delete $.runPthread),0}function _g(C,$,U,te){if(typeof SharedArrayBuffer=="undefined")return J("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var ge=[],xe=0;if(T&&(ge.length===0||xe))return I3(687865856,C,$,U,te);if(xe)return xe;var Ne={startRoutine:U,pthread_ptr:C,arg:te,transferList:ge};return T?(Ne.cmd="spawnThread",postMessage(Ne,ge),0):Ic(Ne)}function zg(){return 2097152}function Og(C,$){if(C==$)postMessage({cmd:"processQueuedMainThreadWork"});else if(T)postMessage({targetThread:C,cmd:"processThreadQueue"});else{var U=Oe.pthreads[C],te=U&&U.worker;if(!te)return;te.postMessage({cmd:"processThreadQueue"})}return 1}function Dg(){Xl("")}function Lg(){S||v||Z("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread")}function Sc(){return 2147483648}function Bg(C,$,U){i().copyWithin(C,$,$+U)}function Wg(){return S?uR().cpus().length:navigator.hardwareConcurrency}function po(C,$){var U=arguments.length-2,te=arguments;return Yl(function(){for(var ge=U,xe=au(ge*8),Ne=xe>>3,_e=0;_e<U;_e++){var $t=te[2+_e];h()[Ne+_e]=$t}return S3(C,ge,xe,$)})}var ap=[];function Vg(C,$,U){ap.length=$;for(var te=U>>3,ge=0;ge<$;ge++)ap[ge]=h()[te+ge];var xe=C<0,Ne=xe?wg[-C-1]:o1[C];return Ne.apply(null,ap)}function Ug(C){try{return $e.grow(C-Pr.byteLength+65535>>>16),ea($e.buffer),1}catch($){}}function Gg(C){var $=i().length;if(C=C>>>0,C<=$)return!1;var U=Sc();if(C>U)return!1;for(var te=1;te<=4;te*=2){var ge=$*(1+.2/te);ge=Math.min(ge,C+100663296);var xe=Math.min(U,ql(Math.max(C,ge),65536)),Ne=Ug(xe);if(Ne)return!0}return!1}var Xe={inEventHandler:0,removeAllEventListeners:function(){for(var C=Xe.eventHandlers.length-1;C>=0;--C)Xe._removeHandler(C);Xe.eventHandlers=[],Xe.deferredCalls=[]},registerRemoveEventListeners:function(){Xe.removeEventListenersRegistered||(gg.push(Xe.removeAllEventListeners),Xe.removeEventListenersRegistered=!0)},deferredCalls:[],deferCall:function(C,$,U){function te(Ne,_e){if(Ne.length!=_e.length)return!1;for(var $t in Ne)if(Ne[$t]!=_e[$t])return!1;return!0}for(var ge in Xe.deferredCalls){var xe=Xe.deferredCalls[ge];if(xe.targetFunction==C&&te(xe.argsList,U))return}Xe.deferredCalls.push({targetFunction:C,precedence:$,argsList:U}),Xe.deferredCalls.sort(function(Ne,_e){return Ne.precedence<_e.precedence})},removeDeferredCalls:function(C){for(var $=0;$<Xe.deferredCalls.length;++$)Xe.deferredCalls[$].targetFunction==C&&(Xe.deferredCalls.splice($,1),--$)},canPerformEventHandlerRequests:function(){return Xe.inEventHandler&&Xe.currentEventHandler.allowsDeferredCalls},runDeferredCalls:function(){if(Xe.canPerformEventHandlerRequests())for(var C=0;C<Xe.deferredCalls.length;++C){var $=Xe.deferredCalls[C];Xe.deferredCalls.splice(C,1),--C,$.targetFunction.apply(null,$.argsList)}},eventHandlers:[],removeAllHandlersOnTarget:function(C,$){for(var U=0;U<Xe.eventHandlers.length;++U)Xe.eventHandlers[U].target==C&&(!$||$==Xe.eventHandlers[U].eventTypeString)&&Xe._removeHandler(U--)},_removeHandler:function(C){var $=Xe.eventHandlers[C];$.target.removeEventListener($.eventTypeString,$.eventListenerFunc,$.useCapture),Xe.eventHandlers.splice(C,1)},registerOrRemoveHandler:function(C){var $=function(te){++Xe.inEventHandler,Xe.currentEventHandler=C,Xe.runDeferredCalls(),C.handlerFunc(te),Xe.runDeferredCalls(),--Xe.inEventHandler};if(C.callbackfunc)C.eventListenerFunc=$,C.target.addEventListener(C.eventTypeString,$,C.useCapture),Xe.eventHandlers.push(C),Xe.registerRemoveEventListeners();else for(var U=0;U<Xe.eventHandlers.length;++U)Xe.eventHandlers[U].target==C.target&&Xe.eventHandlers[U].eventTypeString==C.eventTypeString&&Xe._removeHandler(U--)},queueEventHandlerOnThread_iiii:function(C,$,U,te,ge){Yl(function(){var xe=au(12);u()[xe>>2]=U,u()[xe+4>>2]=te,u()[xe+8>>2]=ge,U1(C,637534208,$,te,xe)})},getTargetThreadForEventCallback:function(C){switch(C){case 1:return 0;case 2:return Oe.currentProxiedOperationCallerThread;default:return C}},getNodeNameForTarget:function(C){return C?C==window?"#window":C==screen?"#screen":C&&C.nodeName?C.nodeName:"":""},fullscreenEnabled:function(){return document.fullscreenEnabled||document.webkitFullscreenEnabled}};function jg(C){var $=ic(C)+1,U=V1($);return so(C,U,$),U}function Hg(C,$,U,te){Yl(function(){var ge=au(12),xe=0;$&&(xe=jg($)),u()[ge>>2]=xe,u()[ge+4>>2]=U,u()[ge+8>>2]=te,U1(C,657457152,0,xe,ge)})}function qg(C,$,U,te){$=$?wn($):"",Hg(C,$,U,te)}function Kg(C){return C>2?wn(C):C}var Xg=[0,typeof document!="undefined"?document:0,typeof window!="undefined"?window:0];function Zg(C){C=Kg(C);var $=Xg[C]||(typeof document!="undefined"?document.querySelector(C):void 0);return $}function sp(C){return Zg(C)}function Tc(C,$,U){var te=sp(C);if(!te)return-4;if(te.canvasSharedPtr&&(u()[te.canvasSharedPtr>>2]=$,u()[te.canvasSharedPtr+4>>2]=U),te.offscreenCanvas||!te.controlTransferredOffscreen){te.offscreenCanvas&&(te=te.offscreenCanvas);var ge=!1;if(te.GLctxObject&&te.GLctxObject.GLctx){var xe=te.GLctxObject.GLctx.getParameter(2978);ge=xe[0]===0&&xe[1]===0&&xe[2]===te.width&&xe[3]===te.height}te.width=$,te.height=U,ge&&te.GLctxObject.GLctx.viewport(0,0,$,U)}else if(te.canvasSharedPtr){var Ne=u()[te.canvasSharedPtr+8>>2];return qg(Ne,C,$,U),1}else return-4;return 0}function Nc(C,$,U){return T?po(2,1,C,$,U):Tc(C,$,U)}function Yg(C,$,U){var te=sp(C);return te?Tc(C,$,U):Nc(C,$,U)}function Jg(){throw"unwind"}function Qg(C){var $=C.getExtension("ANGLE_instanced_arrays");if($)return C.vertexAttribDivisor=function(U,te){$.vertexAttribDivisorANGLE(U,te)},C.drawArraysInstanced=function(U,te,ge,xe){$.drawArraysInstancedANGLE(U,te,ge,xe)},C.drawElementsInstanced=function(U,te,ge,xe,Ne){$.drawElementsInstancedANGLE(U,te,ge,xe,Ne)},1}function e1(C){var $=C.getExtension("OES_vertex_array_object");if($)return C.createVertexArray=function(){return $.createVertexArrayOES()},C.deleteVertexArray=function(U){$.deleteVertexArrayOES(U)},C.bindVertexArray=function(U){$.bindVertexArrayOES(U)},C.isVertexArray=function(U){return $.isVertexArrayOES(U)},1}function t1(C){var $=C.getExtension("WEBGL_draw_buffers");if($)return C.drawBuffers=function(U,te){$.drawBuffersWEBGL(U,te)},1}function r1(C){return!!(C.multiDrawWebgl=C.getExtension("WEBGL_multi_draw"))}var Ft={counter:1,buffers:[],programs:[],framebuffers:[],renderbuffers:[],textures:[],shaders:[],vaos:[],contexts:{},offscreenCanvases:{},queries:[],stringCache:{},unpackAlignment:4,recordError:function(C){Ft.lastError||(Ft.lastError=C)},getNewId:function(C){for(var $=Ft.counter++,U=C.length;U<$;U++)C[U]=null;return $},getSource:function(C,$,U,te){for(var ge="",xe=0;xe<$;++xe){var Ne=te?u()[te+xe*4>>2]:-1;ge+=wn(u()[U+xe*4>>2],Ne<0?void 0:Ne)}return ge},createContext:function(C,$){C.getContextSafariWebGL2Fixed||(C.getContextSafariWebGL2Fixed=C.getContext,C.getContext=function(ge,xe){var Ne=C.getContextSafariWebGL2Fixed(ge,xe);return ge=="webgl"==Ne instanceof WebGLRenderingContext?Ne:null});var U=C.getContext("webgl",$);if(!U)return 0;var te=Ft.registerContext(U,$);return te},registerContext:function(C,$){var U=V1(8);u()[U+4>>2]=zc();var te={handle:U,attributes:$,version:$.majorVersion,GLctx:C};return C.canvas&&(C.canvas.GLctxObject=te),Ft.contexts[U]=te,(typeof $.enableExtensionsByDefault=="undefined"||$.enableExtensionsByDefault)&&Ft.initExtensions(te),U},makeContextCurrent:function(C){return Ft.currentContext=Ft.contexts[C],p.ctx=Mc=Ft.currentContext&&Ft.currentContext.GLctx,!(C&&!Mc)},getContext:function(C){return Ft.contexts[C]},deleteContext:function(C){Ft.currentContext===Ft.contexts[C]&&(Ft.currentContext=null),typeof Xe=="object"&&Xe.removeAllHandlersOnTarget(Ft.contexts[C].GLctx.canvas),Ft.contexts[C]&&Ft.contexts[C].GLctx.canvas&&(Ft.contexts[C].GLctx.canvas.GLctxObject=void 0),b3(Ft.contexts[C].handle),Ft.contexts[C]=null},initExtensions:function(C){if(C||(C=Ft.currentContext),!C.initExtensionsDone){C.initExtensionsDone=!0;var $=C.GLctx;Qg($),e1($),t1($),$.disjointTimerQueryExt=$.getExtension("EXT_disjoint_timer_query"),r1($);var U=$.getSupportedExtensions()||[];U.forEach(function(te){!te.includes("lose_context")&&!te.includes("debug")&&$.getExtension(te)})}}},n1=["default","low-power","high-performance"];function a1(C,$){var U=$>>2,te=u()[U+6],ge={alpha:!!u()[U+0],depth:!!u()[U+1],stencil:!!u()[U+2],antialias:!!u()[U+3],premultipliedAlpha:!!u()[U+4],preserveDrawingBuffer:!!u()[U+5],powerPreference:n1[te],failIfMajorPerformanceCaveat:!!u()[U+7],majorVersion:u()[U+8],minorVersion:u()[U+9],enableExtensionsByDefault:u()[U+10],explicitSwapControl:u()[U+11],proxyContextToMainThread:u()[U+12],renderViaOffscreenBackBuffer:u()[U+13]},xe=sp(C);if(!xe||ge.explicitSwapControl)return 0;var Ne=Ft.createContext(xe,ge);return Ne}function s1(C,$){return a1(C,$)}var Ql={mappings:{},buffers:[null,[],[]],printChar:function(C,$){var U=Ql.buffers[C];$===0||$===10?((C===1?ee:J)(vn(U,0)),U.length=0):U.push($)},varargs:void 0,get:function(){Ql.varargs+=4;var C=u()[Ql.varargs-4>>2];return C},getStr:function(C){var $=wn(C);return $},get64:function(C,$){return C}};function Cc(C){return T?po(3,1,C):0}function Ec(C,$,U,te,ge){if(T)return po(4,1,C,$,U,te,ge)}function Rc(C,$,U,te){if(T)return po(5,1,C,$,U,te);for(var ge=0,xe=0;xe<U;xe++){var Ne=u()[$>>2],_e=u()[$+4>>2];$+=8;for(var $t=0;$t<_e;$t++)Ql.printChar(C,i()[Ne+$t]);ge+=_e}return u()[te>>2]=ge,0}function i1(C){De(C)}Oe.init();var Mc,o1=[null,kc,Nc,Cc,Ec,Rc],y3=!1,Fc={__clock_gettime:Fg,__emscripten_init_main_thread_js:$g,__emscripten_thread_cleanup:Pg,__pthread_create_js:_g,_emscripten_default_pthread_stack_size:zg,_emscripten_notify_thread_queue:Og,abort:Dg,emscripten_check_blocking_allowed:Lg,emscripten_get_heap_max:Sc,emscripten_get_now:uo,emscripten_memcpy_big:Bg,emscripten_num_logical_cores:Wg,emscripten_receive_on_main_thread_js:Vg,emscripten_resize_heap:Gg,emscripten_set_canvas_element_size:Yg,emscripten_unwind_to_js_event_loop:Jg,emscripten_webgl_create_context:s1,exit:wc,fd_close:Cc,fd_seek:Ec,fd_write:Rc,memory:$e||p.wasmMemory,setTempRet0:i1},A3=vg(),l1=p.___wasm_call_ctors=function(){return(l1=p.___wasm_call_ctors=p.asm.__wasm_call_ctors).apply(null,arguments)},u1=p._init=function(){return(u1=p._init=p.asm.init).apply(null,arguments)},d1=p._init_with_threads_count=function(){return(d1=p._init_with_threads_count=p.asm.init_with_threads_count).apply(null,arguments)},p1=p._get_threads_count=function(){return(p1=p._get_threads_count=p.asm.get_threads_count).apply(null,arguments)},h1=p._register_tensor=function(){return(h1=p._register_tensor=p.asm.register_tensor).apply(null,arguments)},c1=p._dispose_data=function(){return(c1=p._dispose_data=p.asm.dispose_data).apply(null,arguments)},f1=p._dispose=function(){return(f1=p._dispose=p.asm.dispose).apply(null,arguments)},m1=p._Abs=function(){return(m1=p._Abs=p.asm.Abs).apply(null,arguments)},g1=p._Add=function(){return(g1=p._Add=p.asm.Add).apply(null,arguments)},y1=p._AddN=function(){return(y1=p._AddN=p.asm.AddN).apply(null,arguments)},A1=p._All=function(){return(A1=p._All=p.asm.All).apply(null,arguments)},x1=p._Any=function(){return(x1=p._Any=p.asm.Any).apply(null,arguments)},b1=p._ArgMax=function(){return(b1=p._ArgMax=p.asm.ArgMax).apply(null,arguments)},v1=p._AvgPool=function(){return(v1=p._AvgPool=p.asm.AvgPool).apply(null,arguments)},w1=p._BatchMatMul=function(){return(w1=p._BatchMatMul=p.asm.BatchMatMul).apply(null,arguments)},k1=p._Ceil=function(){return(k1=p._Ceil=p.asm.Ceil).apply(null,arguments)},I1=p._ClipByValue=function(){return(I1=p._ClipByValue=p.asm.ClipByValue).apply(null,arguments)},S1=p._Conv2D=function(){return(S1=p._Conv2D=p.asm.Conv2D).apply(null,arguments)},T1=p._Conv2DBackpropInput=function(){return(T1=p._Conv2DBackpropInput=p.asm.Conv2DBackpropInput).apply(null,arguments)},N1=p._Cos=function(){return(N1=p._Cos=p.asm.Cos).apply(null,arguments)},C1=p._Cosh=function(){return(C1=p._Cosh=p.asm.Cosh).apply(null,arguments)},E1=p._CropAndResize=function(){return(E1=p._CropAndResize=p.asm.CropAndResize).apply(null,arguments)},R1=p._Cumprod=function(){return(R1=p._Cumprod=p.asm.Cumprod).apply(null,arguments)},M1=p._Cumsum=function(){return(M1=p._Cumsum=p.asm.Cumsum).apply(null,arguments)},F1=p._DepthToSpace=function(){return(F1=p._DepthToSpace=p.asm.DepthToSpace).apply(null,arguments)},$1=p._DepthwiseConv2dNative=function(){return($1=p._DepthwiseConv2dNative=p.asm.DepthwiseConv2dNative).apply(null,arguments)},P1=p._Elu=function(){return(P1=p._Elu=p.asm.Elu).apply(null,arguments)},_1=p._Equal=function(){return(_1=p._Equal=p.asm.Equal).apply(null,arguments)},z1=p._Exp=function(){return(z1=p._Exp=p.asm.Exp).apply(null,arguments)},O1=p._FlipLeftRight=function(){return(O1=p._FlipLeftRight=p.asm.FlipLeftRight).apply(null,arguments)},$c=p._Floor=function(){return($c=p._Floor=p.asm.Floor).apply(null,arguments)},Pc=p._FloorDiv=function(){return(Pc=p._FloorDiv=p.asm.FloorDiv).apply(null,arguments)},ip=p._FusedBatchNorm=function(){return(ip=p._FusedBatchNorm=p.asm.FusedBatchNorm).apply(null,arguments)},D1=p._FusedConv2D=function(){return(D1=p._FusedConv2D=p.asm.FusedConv2D).apply(null,arguments)},L1=p._FusedDepthwiseConv2D=function(){return(L1=p._FusedDepthwiseConv2D=p.asm.FusedDepthwiseConv2D).apply(null,arguments)},eu=p._Gather=function(){return(eu=p._Gather=p.asm.Gather).apply(null,arguments)},op=p._GatherNd=function(){return(op=p._GatherNd=p.asm.GatherNd).apply(null,arguments)},lp=p._Greater=function(){return(lp=p._Greater=p.asm.Greater).apply(null,arguments)},x3=p._GreaterEqual=function(){return(x3=p._GreaterEqual=p.asm.GreaterEqual).apply(null,arguments)},tu=p._LeakyRelu=function(){return(tu=p._LeakyRelu=p.asm.LeakyRelu).apply(null,arguments)},ru=p._Less=function(){return(ru=p._Less=p.asm.Less).apply(null,arguments)},B1=p._LessEqual=function(){return(B1=p._LessEqual=p.asm.LessEqual).apply(null,arguments)},H=p._Log=function(){return(H=p._Log=p.asm.Log).apply(null,arguments)},ne=p._LogicalAnd=function(){return(ne=p._LogicalAnd=p.asm.LogicalAnd).apply(null,arguments)},ye=p._Max=function(){return(ye=p._Max=p.asm.Max).apply(null,arguments)},Re=p._MaxPool=function(){return(Re=p._MaxPool=p.asm.MaxPool).apply(null,arguments)},lt=p._Maximum=function(){return(lt=p._Maximum=p.asm.Maximum).apply(null,arguments)},ht=p._Mean=function(){return(ht=p._Mean=p.asm.Mean).apply(null,arguments)},Ye=p._Min=function(){return(Ye=p._Min=p.asm.Min).apply(null,arguments)},He=p._Minimum=function(){return(He=p._Minimum=p.asm.Minimum).apply(null,arguments)},Ht=p._MirrorPad=function(){return(Ht=p._MirrorPad=p.asm.MirrorPad).apply(null,arguments)},ra=p._Multiply=function(){return(ra=p._Multiply=p.asm.Multiply).apply(null,arguments)},na=p._Neg=function(){return(na=p._Neg=p.asm.Neg).apply(null,arguments)},nu=p._NonMaxSuppressionV3=function(){return(nu=p._NonMaxSuppressionV3=p.asm.NonMaxSuppressionV3).apply(null,arguments)},ho=p._NonMaxSuppressionV4=function(){return(ho=p._NonMaxSuppressionV4=p.asm.NonMaxSuppressionV4).apply(null,arguments)},W1=p._NonMaxSuppressionV5=function(){return(W1=p._NonMaxSuppressionV5=p.asm.NonMaxSuppressionV5).apply(null,arguments)},Qr=p._NotEqual=function(){return(Qr=p._NotEqual=p.asm.NotEqual).apply(null,arguments)},xs=p._OneHot=function(){return(xs=p._OneHot=p.asm.OneHot).apply(null,arguments)},_c=p._PadV2=function(){return(_c=p._PadV2=p.asm.PadV2).apply(null,arguments)},H9=p._Pow=function(){return(H9=p._Pow=p.asm.Pow).apply(null,arguments)},q9=p._Prelu=function(){return(q9=p._Prelu=p.asm.Prelu).apply(null,arguments)},K9=p._Prod=function(){return(K9=p._Prod=p.asm.Prod).apply(null,arguments)},X9=p._RealDiv=function(){return(X9=p._RealDiv=p.asm.RealDiv).apply(null,arguments)},Z9=p._Relu=function(){return(Z9=p._Relu=p.asm.Relu).apply(null,arguments)},Y9=p._Relu6=function(){return(Y9=p._Relu6=p.asm.Relu6).apply(null,arguments)},J9=p._ResizeBilinear=function(){return(J9=p._ResizeBilinear=p.asm.ResizeBilinear).apply(null,arguments)},Q9=p._Reverse=function(){return(Q9=p._Reverse=p.asm.Reverse).apply(null,arguments)},eE=p._RotateWithOffset=function(){return(eE=p._RotateWithOffset=p.asm.RotateWithOffset).apply(null,arguments)},tE=p._Round=function(){return(tE=p._Round=p.asm.Round).apply(null,arguments)},rE=p._Rsqrt=function(){return(rE=p._Rsqrt=p.asm.Rsqrt).apply(null,arguments)},nE=p._ScatterNd=function(){return(nE=p._ScatterNd=p.asm.ScatterNd).apply(null,arguments)},aE=p._SelectV2=function(){return(aE=p._SelectV2=p.asm.SelectV2).apply(null,arguments)},sE=p._Sigmoid=function(){return(sE=p._Sigmoid=p.asm.Sigmoid).apply(null,arguments)},iE=p._Sin=function(){return(iE=p._Sin=p.asm.Sin).apply(null,arguments)},oE=p._Softmax=function(){return(oE=p._Softmax=p.asm.Softmax).apply(null,arguments)},lE=p._SparseFillEmptyRows=function(){return(lE=p._SparseFillEmptyRows=p.asm.SparseFillEmptyRows).apply(null,arguments)},uE=p._SparseReshape=function(){return(uE=p._SparseReshape=p.asm.SparseReshape).apply(null,arguments)},dE=p._SparseSegmentReduction=function(){return(dE=p._SparseSegmentReduction=p.asm.SparseSegmentReduction).apply(null,arguments)},pE=p._Sqrt=function(){return(pE=p._Sqrt=p.asm.Sqrt).apply(null,arguments)},hE=p._Square=function(){return(hE=p._Square=p.asm.Square).apply(null,arguments)},cE=p._SquaredDifference=function(){return(cE=p._SquaredDifference=p.asm.SquaredDifference).apply(null,arguments)},fE=p._Step=function(){return(fE=p._Step=p.asm.Step).apply(null,arguments)},mE=p._StridedSlice=function(){return(mE=p._StridedSlice=p.asm.StridedSlice).apply(null,arguments)},gE=p._Sub=function(){return(gE=p._Sub=p.asm.Sub).apply(null,arguments)},yE=p._Sum=function(){return(yE=p._Sum=p.asm.Sum).apply(null,arguments)},AE=p._Tan=function(){return(AE=p._Tan=p.asm.Tan).apply(null,arguments)},xE=p._Tanh=function(){return(xE=p._Tanh=p.asm.Tanh).apply(null,arguments)},bE=p._Tile=function(){return(bE=p._Tile=p.asm.Tile).apply(null,arguments)},vE=p._TopK=function(){return(vE=p._TopK=p.asm.TopK).apply(null,arguments)},wE=p._Transform=function(){return(wE=p._Transform=p.asm.Transform).apply(null,arguments)},kE=p._Transpose=function(){return(kE=p._Transpose=p.asm.Transpose).apply(null,arguments)},IE=p.__FusedMatMul=function(){return(IE=p.__FusedMatMul=p.asm._FusedMatMul).apply(null,arguments)},V1=p._malloc=function(){return(V1=p._malloc=p.asm.malloc).apply(null,arguments)},b3=p._free=function(){return(b3=p._free=p.asm.free).apply(null,arguments)},SE=p._emscripten_tls_init=function(){return(SE=p._emscripten_tls_init=p.asm.emscripten_tls_init).apply(null,arguments)},v3=p.___errno_location=function(){return(v3=p.___errno_location=p.asm.__errno_location).apply(null,arguments)},zc=p._pthread_self=function(){return(zc=p._pthread_self=p.asm.pthread_self).apply(null,arguments)},w3=p._emscripten_main_thread_process_queued_calls=function(){return(w3=p._emscripten_main_thread_process_queued_calls=p.asm.emscripten_main_thread_process_queued_calls).apply(null,arguments)},TE=p.__emscripten_thread_crashed=function(){return(TE=p.__emscripten_thread_crashed=p.asm._emscripten_thread_crashed).apply(null,arguments)},k3=p.__emscripten_thread_init=function(){return(k3=p.__emscripten_thread_init=p.asm._emscripten_thread_init).apply(null,arguments)},NE=p._emscripten_current_thread_process_queued_calls=function(){return(NE=p._emscripten_current_thread_process_queued_calls=p.asm.emscripten_current_thread_process_queued_calls).apply(null,arguments)},CE=p._emscripten_main_browser_thread_id=function(){return(CE=p._emscripten_main_browser_thread_id=p.asm.emscripten_main_browser_thread_id).apply(null,arguments)},EE=p._emscripten_sync_run_in_main_thread_2=function(){return(EE=p._emscripten_sync_run_in_main_thread_2=p.asm.emscripten_sync_run_in_main_thread_2).apply(null,arguments)},I3=p._emscripten_sync_run_in_main_thread_4=function(){return(I3=p._emscripten_sync_run_in_main_thread_4=p.asm.emscripten_sync_run_in_main_thread_4).apply(null,arguments)},S3=p._emscripten_run_in_main_runtime_thread_js=function(){return(S3=p._emscripten_run_in_main_runtime_thread_js=p.asm.emscripten_run_in_main_runtime_thread_js).apply(null,arguments)},U1=p._emscripten_dispatch_to_thread_=function(){return(U1=p._emscripten_dispatch_to_thread_=p.asm.emscripten_dispatch_to_thread_).apply(null,arguments)},G1=p.__emscripten_thread_free_data=function(){return(G1=p.__emscripten_thread_free_data=p.asm._emscripten_thread_free_data).apply(null,arguments)},RE=p.__emscripten_thread_exit=function(){return(RE=p.__emscripten_thread_exit=p.asm._emscripten_thread_exit).apply(null,arguments)},ME=p._memalign=function(){return(ME=p._memalign=p.asm.memalign).apply(null,arguments)},T3=p._emscripten_stack_set_limits=function(){return(T3=p._emscripten_stack_set_limits=p.asm.emscripten_stack_set_limits).apply(null,arguments)},j1=p.stackSave=function(){return(j1=p.stackSave=p.asm.stackSave).apply(null,arguments)},Oc=p.stackRestore=function(){return(Oc=p.stackRestore=p.asm.stackRestore).apply(null,arguments)},au=p.stackAlloc=function(){return(au=p.stackAlloc=p.asm.stackAlloc).apply(null,arguments)},FE=p.dynCall_iijjiiii=function(){return(FE=p.dynCall_iijjiiii=p.asm.dynCall_iijjiiii).apply(null,arguments)},$E=p.dynCall_jiji=function(){return($E=p.dynCall_jiji=p.asm.dynCall_jiji).apply(null,arguments)},N3=p.__emscripten_allow_main_runtime_queued_calls=21456;p.cwrap=hr,p.keepRuntimeAlive=oo,p.PThread=Oe,p.PThread=Oe,p.wasmMemory=$e,p.ExitStatus=up;var Dc;function up(C){this.name="ExitStatus",this.message="Program terminated with exit("+C+")",this.status=C}ta=function C(){Dc||H1(),Dc||(ta=C)};function H1(C){if(C=C||y,As>0)return;if(T){c(p),tp(),postMessage({cmd:"loaded"});return}if(_r(),As>0)return;function $(){Dc||(Dc=!0,p.calledRun=!0,!yt&&(tp(),c(p),p.onRuntimeInitialized&&p.onRuntimeInitialized(),xg()))}p.setStatus?(p.setStatus("Running..."),setTimeout(function(){setTimeout(function(){p.setStatus("")},1),$()},1)):$()}p.run=H1;function PE(C,$){if($r=C,!$&&T)throw kc(C),"unwind";oo()||Ag(),_E(C)}function _E(C){$r=C,oo()||(Oe.terminateAllThreads(),p.onExit&&p.onExit(C),yt=!0),x(C,new up(C))}if(p.preInit)for(typeof p.preInit=="function"&&(p.preInit=[p.preInit]);p.preInit.length>0;)p.preInit.pop()();H1();var Lc;m&&(Lc={uncaughtException:process.listeners("uncaughtException").filter(function(C){return!m.uncaughtException.indexOf(C)>-1}),unhandledRejection:process.listeners("unhandledRejection").filter(function(C){return!m.unhandledRejection.indexOf(C)>-1})});var Bc;if(typeof WasmBackendModule!="undefined")Bc=WasmBackendModule;else if(typeof a!="undefined")Bc=a;else throw new Error("Could not find wasm module in post.js");if(Lc){var zE=Bc._dispose;Bc._dispose=function(){zE(),Lc.uncaughtException.forEach(function(C){process.removeListener("uncaughtException",C)}),Lc.unhandledRejection.forEach(function(C){process.removeListener("unhandledRejection",C)})}}return a.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)}}),pR=ur({"src/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm.js"(e,t){var r=(()=>{var n=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(n=n||__filename),function(a){a=a||{};var s=typeof a!="undefined"?a:{},i,o;s.ready=new Promise(function(H,ne){i=H,o=ne});var l;typeof process!="undefined"&&process.listeners&&(l={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var u=Object.assign({},s),d=[],h="./this.program",p=(H,ne)=>{throw ne},c=typeof window=="object",f=typeof importScripts=="function",m=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g="";function y(H){return s.locateFile?s.locateFile(H,g):g+H}var A,x,b,v;function S(H){H instanceof op||M("exiting due to exception: "+H)}var T,E,R;m?(f?g=hf().dirname(g)+"/":g=__dirname+"/",R=()=>{E||(T=u2(),E=hf())},A=function(H,ne){return R(),H=E.normalize(H),T.readFileSync(H,ne?void 0:"utf8")},b=H=>{var ne=A(H,!0);return ne.buffer||(ne=new Uint8Array(ne)),ne},x=(H,ne,ye)=>{R(),H=E.normalize(H),T.readFile(H,function(Re,lt){Re?ye(Re):ne(lt.buffer)})},process.argv.length>1&&(h=process.argv[1].replace(/\\/g,"/")),d=process.argv.slice(2),process.on("uncaughtException",function(H){if(!(H instanceof op))throw H}),process.on("unhandledRejection",function(H){throw H}),p=(H,ne)=>{if(ep())throw process.exitCode=H,ne;S(ne),process.exit(H)},s.inspect=function(){return"[Emscripten Module object]"}):(c||f)&&(f?g=self.location.href:typeof document!="undefined"&&document.currentScript&&(g=document.currentScript.src),n&&(g=n),g.indexOf("blob:")!==0?g=g.substr(0,g.replace(/[?#].*/,"").lastIndexOf("/")+1):g="",A=H=>{var ne=new XMLHttpRequest;return ne.open("GET",H,!1),ne.send(null),ne.responseText},f&&(b=H=>{var ne=new XMLHttpRequest;return ne.open("GET",H,!1),ne.responseType="arraybuffer",ne.send(null),new Uint8Array(ne.response)}),x=(H,ne,ye)=>{var Re=new XMLHttpRequest;Re.open("GET",H,!0),Re.responseType="arraybuffer",Re.onload=()=>{if(Re.status==200||Re.status==0&&Re.response){ne(Re.response);return}ye()},Re.onerror=ye,Re.send(null)},v=H=>document.title=H);var _=s.print||console.log.bind(console),M=s.printErr||console.warn.bind(console);Object.assign(s,u),u=null,s.arguments&&(d=s.arguments),s.thisProgram&&(h=s.thisProgram),s.quit&&(p=s.quit);var I=4;function z(H){z.shown||(z.shown={}),z.shown[H]||(z.shown[H]=1,M(H))}function O(H,ne){if(typeof WebAssembly.Function=="function"){for(var ye={i:"i32",j:"i64",f:"f32",d:"f64"},Re={parameters:[],results:ne[0]=="v"?[]:[ye[ne[0]]]},lt=1;lt<ne.length;++lt)Re.parameters.push(ye[ne[lt]]);return new WebAssembly.Function(Re,H)}var ht=[1,0,1,96],Ye=ne.slice(0,1),He=ne.slice(1),Ht={i:127,j:126,f:125,d:124};ht.push(He.length);for(var lt=0;lt<He.length;++lt)ht.push(Ht[He[lt]]);Ye=="v"?ht.push(0):ht=ht.concat([1,Ht[Ye]]),ht[1]=ht.length-2;var ra=new Uint8Array([0,97,115,109,1,0,0,0].concat(ht,[2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0])),na=new WebAssembly.Module(ra),nu=new WebAssembly.Instance(na,{e:{f:H}}),ho=nu.exports.f;return ho}var j=[],X;function D(){if(j.length)return j.pop();try{gs.grow(1)}catch(H){throw H instanceof RangeError?"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.":H}return gs.length-1}function Q(H,ne){for(var ye=H;ye<H+ne;ye++){var Re=np(ye);Re&&X.set(Re,ye)}}var V=0,ee=H=>{V=H},J;s.wasmBinary&&(J=s.wasmBinary);var ie=s.noExitRuntime||!0;typeof WebAssembly!="object"&&io("no native wasm support detected");var Z,ae=!1,de;function Ae(H,ne){H||io(ne)}function be(H){var ne=s["_"+H];return ne}function Ee(H,ne,ye,Re,lt){var ht={string:function(Qr){var xs=0;if(Qr!=null&&Qr!==0){var _c=(Qr.length<<2)+1;xs=ip(_c),pt(Qr,xs,_c)}return xs},array:function(Qr){var xs=ip(Qr.length);return yt(Qr,xs),xs}};function Ye(Qr){return ne==="string"?ot(Qr):ne==="boolean"?Boolean(Qr):Qr}var He=be(H),Ht=[],ra=0;if(Re)for(var na=0;na<Re.length;na++){var nu=ht[ye[na]];nu?(ra===0&&(ra=$c()),Ht[na]=nu(Re[na])):Ht[na]=Re[na]}var ho=He.apply(null,Ht);function W1(Qr){return ra!==0&&Pc(ra),Ye(Qr)}return ho=W1(ho),ho}function Me(H,ne,ye,Re){ye=ye||[];var lt=ye.every(function(Ye){return Ye==="number"}),ht=ne!=="string";return ht&<&&!Re?be(H):function(){return Ee(H,ne,ye,arguments,Re)}}var De=1,Be=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function Ze(H,ne,ye){for(var Re=ne+ye,lt=ne;H[lt]&&!(lt>=Re);)++lt;if(lt-ne>16&&H.subarray&&Be)return Be.decode(H.subarray(ne,lt));for(var ht="";ne<lt;){var Ye=H[ne++];if(!(Ye&128)){ht+=String.fromCharCode(Ye);continue}var He=H[ne++]&63;if((Ye&224)==192){ht+=String.fromCharCode((Ye&31)<<6|He);continue}var Ht=H[ne++]&63;if((Ye&240)==224?Ye=(Ye&15)<<12|He<<6|Ht:Ye=(Ye&7)<<18|He<<12|Ht<<6|H[ne++]&63,Ye<65536)ht+=String.fromCharCode(Ye);else{var ra=Ye-65536;ht+=String.fromCharCode(55296|ra>>10,56320|ra&1023)}}return ht}function ot(H,ne){return H?Ze(hr,H,ne):""}function dt(H,ne,ye,Re){if(!(Re>0))return 0;for(var lt=ye,ht=ye+Re-1,Ye=0;Ye<H.length;++Ye){var He=H.charCodeAt(Ye);if(He>=55296&&He<=57343){var Ht=H.charCodeAt(++Ye);He=65536+((He&1023)<<10)|Ht&1023}if(He<=127){if(ye>=ht)break;ne[ye++]=He}else if(He<=2047){if(ye+1>=ht)break;ne[ye++]=192|He>>6,ne[ye++]=128|He&63}else if(He<=65535){if(ye+2>=ht)break;ne[ye++]=224|He>>12,ne[ye++]=128|He>>6&63,ne[ye++]=128|He&63}else{if(ye+3>=ht)break;ne[ye++]=240|He>>18,ne[ye++]=128|He>>12&63,ne[ye++]=128|He>>6&63,ne[ye++]=128|He&63}}return ne[ye]=0,ye-lt}function pt(H,ne,ye){return dt(H,hr,ne,ye)}function $e(H){for(var ne=0,ye=0;ye<H.length;++ye){var Re=H.charCodeAt(ye);Re>=55296&&Re<=57343&&(Re=65536+((Re&1023)<<10)|H.charCodeAt(++ye)&1023),Re<=127?++ne:Re<=2047?ne+=2:Re<=65535?ne+=3:ne+=4}return ne}var vt=typeof TextDecoder!="undefined"?new TextDecoder("utf-16le"):void 0;function yt(H,ne){er.set(H,ne)}function $r(H,ne,ye){for(var Re=0;Re<H.length;++Re)er[ne++>>0]=H.charCodeAt(Re);ye||(er[ne>>0]=0)}function pr(H,ne){return H%ne>0&&(H+=ne-H%ne),H}var Yr,er,hr,Qn,Jr,tr,vn,wn,ms;function so(H){Yr=H,s.HEAP8=er=new Int8Array(H),s.HEAP16=Qn=new Int16Array(H),s.HEAP32=tr=new Int32Array(H),s.HEAPU8=hr=new Uint8Array(H),s.HEAPU16=Jr=new Uint16Array(H),s.HEAPU32=vn=new Uint32Array(H),s.HEAPF32=wn=new Float32Array(H),s.HEAPF64=ms=new Float64Array(H)}var ic=s.INITIAL_MEMORY||16777216,gs,Ua=[],Qd=[],ql=[],Pr=!1,oc=!1,lc=0;function ep(){return ie||lc>0}function uc(){if(s.preRun)for(typeof s.preRun=="function"&&(s.preRun=[s.preRun]);s.preRun.length;)hc(s.preRun.shift());rp(Ua)}function dc(){Pr=!0,rp(Qd)}function l3(){oc=!0}function pc(){if(s.postRun)for(typeof s.postRun=="function"&&(s.postRun=[s.postRun]);s.postRun.length;)cc(s.postRun.shift());rp(ql)}function hc(H){Ua.unshift(H)}function ea(H){Qd.unshift(H)}function cc(H){ql.unshift(H)}var kn=0,Kl=null,ys=null;function gg(H){kn++,s.monitorRunDependencies&&s.monitorRunDependencies(kn)}function fc(H){if(kn--,s.monitorRunDependencies&&s.monitorRunDependencies(kn),kn==0&&(Kl!==null&&(clearInterval(Kl),Kl=null),ys)){var ne=ys;ys=null,ne()}}s.preloadedImages={},s.preloadedAudios={};function io(H){s.onAbort&&s.onAbort(H),H="Aborted("+H+")",M(H),ae=!0,de=1,H+=". Build with -s ASSERTIONS=1 for more info.";var ne=new WebAssembly.RuntimeError(H);throw o(ne),ne}var yg="data:application/octet-stream;base64,";function mc(H){return H.startsWith(yg)}function oo(H){return H.startsWith("file://")}var _r;_r="tfjs-backend-wasm.wasm",mc(_r)||(_r=y(_r));function tp(H){try{if(H==_r&&J)return new Uint8Array(J);if(b)return b(H);throw"both async and sync fetching of the wasm failed"}catch(ne){io(ne)}}function Ag(){if(!J&&(c||f)){if(typeof fetch=="function"&&!oo(_r))return fetch(_r,{credentials:"same-origin"}).then(function(H){if(!H.ok)throw"failed to load wasm binary file at '"+_r+"'";return H.arrayBuffer()}).catch(function(){return tp(_r)});if(x)return new Promise(function(H,ne){x(_r,function(ye){H(new Uint8Array(ye))},ne)})}return Promise.resolve().then(function(){return tp(_r)})}function xg(){var H={env:Yl,wasi_snapshot_preview1:Yl};function ne(Ye,He){var Ht=Ye.exports;s.asm=Ht,Z=s.asm.memory,so(Z.buffer),gs=s.asm.__indirect_function_table,ea(s.asm.__wasm_call_ctors),fc("wasm-instantiate")}gg("wasm-instantiate");function ye(Ye){ne(Ye.instance)}function Re(Ye){return Ag().then(function(He){return WebAssembly.instantiate(He,H)}).then(function(He){return He}).then(Ye,function(He){M("failed to asynchronously prepare wasm: "+He),io(He)})}function lt(){return!J&&typeof WebAssembly.instantiateStreaming=="function"&&!mc(_r)&&!oo(_r)&&typeof fetch=="function"?fetch(_r,{credentials:"same-origin"}).then(function(Ye){var He=WebAssembly.instantiateStreaming(Ye,H);return He.then(ye,function(Ht){return M("wasm streaming compile failed: "+Ht),M("falling back to ArrayBuffer instantiation"),Re(ye)})}):Re(ye)}if(s.instantiateWasm)try{var ht=s.instantiateWasm(H,ne);return ht}catch(Ye){return M("Module.instantiateWasm callback failed with error: "+Ye),!1}return lt().catch(o),{}}var u3,d3;function rp(H){for(;H.length>0;){var ne=H.shift();if(typeof ne=="function"){ne(s);continue}var ye=ne.func;typeof ye=="number"?ne.arg===void 0?np(ye)():np(ye)(ne.arg):ye(ne.arg===void 0?null:ne.arg)}}function As(H){return H}function gc(H){var ne=/\b_Z[\w\d_]+/g;return H.replace(ne,function(ye){var Re=ye;return ye===Re?ye:Re+" ["+ye+"]"})}var ta=[];function np(H){var ne=ta[H];return ne||(H>=ta.length&&(ta.length=H+1),ta[H]=ne=gs.get(H)),ne}function p3(){var H=new Error;if(!H.stack){try{throw new Error}catch(ne){H=ne}if(!H.stack)return"(no stack trace available)"}return H.stack.toString()}function Xl(H,ne){gs.set(H,ne),ta[H]=ne}function bg(){io("")}function yc(H,ne,ye){hr.copyWithin(H,ne,ne+ye)}function Ac(){return 2147483648}function zr(H){try{return Z.grow(H-Yr.byteLength+65535>>>16),so(Z.buffer),1}catch(ne){}}function xc(H){var ne=hr.length;H=H>>>0;var ye=Ac();if(H>ye)return!1;for(var Re=1;Re<=4;Re*=2){var lt=ne*(1+.2/Re);lt=Math.min(lt,H+100663296);var ht=Math.min(ye,pr(Math.max(H,lt),65536)),Ye=zr(ht);if(Ye)return!0}return!1}var Zl={mappings:{},buffers:[null,[],[]],printChar:function(H,ne){var ye=Zl.buffers[H];ne===0||ne===10?((H===1?_:M)(Ze(ye,0)),ye.length=0):ye.push(ne)},varargs:void 0,get:function(){Zl.varargs+=4;var H=tr[Zl.varargs-4>>2];return H},getStr:function(H){var ne=ot(H);return ne},get64:function(H,ne){return H}};function vg(H){return 0}function h3(H,ne,ye,Re,lt){}function c3(H,ne,ye,Re){for(var lt=0,ht=0;ht<ye;ht++){var Ye=tr[ne>>2],He=tr[ne+4>>2];ne+=8;for(var Ht=0;Ht<He;Ht++)Zl.printChar(H,hr[Ye+Ht]);lt+=He}return tr[Re>>2]=lt,0}function wg(H){ee(H)}var bc=!1,Yl={abort:bg,emscripten_memcpy_big:yc,emscripten_resize_heap:xc,fd_close:vg,fd_seek:h3,fd_write:c3,setTempRet0:wg},j9=xg(),f3=s.___wasm_call_ctors=function(){return(f3=s.___wasm_call_ctors=s.asm.__wasm_call_ctors).apply(null,arguments)},kg=s._init=function(){return(kg=s._init=s.asm.init).apply(null,arguments)},Ig=s._init_with_threads_count=function(){return(Ig=s._init_with_threads_count=s.asm.init_with_threads_count).apply(null,arguments)},vc=s._get_threads_count=function(){return(vc=s._get_threads_count=s.asm.get_threads_count).apply(null,arguments)},wc=s._register_tensor=function(){return(wc=s._register_tensor=s.asm.register_tensor).apply(null,arguments)},Sg=s._dispose_data=function(){return(Sg=s._dispose_data=s.asm.dispose_data).apply(null,arguments)},Oe=s._dispose=function(){return(Oe=s._dispose=s.asm.dispose).apply(null,arguments)},Tg=s._Abs=function(){return(Tg=s._Abs=s.asm.Abs).apply(null,arguments)},kc=s._Add=function(){return(kc=s._Add=s.asm.Add).apply(null,arguments)},lo=s._AddN=function(){return(lo=s._AddN=s.asm.AddN).apply(null,arguments)},Jl=s._All=function(){return(Jl=s._All=s.asm.All).apply(null,arguments)},Ng=s._Any=function(){return(Ng=s._Any=s.asm.Any).apply(null,arguments)},m3=s._ArgMax=function(){return(m3=s._ArgMax=s.asm.ArgMax).apply(null,arguments)},Cg=s._AvgPool=function(){return(Cg=s._AvgPool=s.asm.AvgPool).apply(null,arguments)},g3=s._BatchMatMul=function(){return(g3=s._BatchMatMul=s.asm.BatchMatMul).apply(null,arguments)},uo=s._Ceil=function(){return(uo=s._Ceil=s.asm.Ceil).apply(null,arguments)},Eg=s._ClipByValue=function(){return(Eg=s._ClipByValue=s.asm.ClipByValue).apply(null,arguments)},Rg=s._Conv2D=function(){return(Rg=s._Conv2D=s.asm.Conv2D).apply(null,arguments)},Mg=s._Conv2DBackpropInput=function(){return(Mg=s._Conv2DBackpropInput=s.asm.Conv2DBackpropInput).apply(null,arguments)},Fg=s._Cos=function(){return(Fg=s._Cos=s.asm.Cos).apply(null,arguments)},$g=s._Cosh=function(){return($g=s._Cosh=s.asm.Cosh).apply(null,arguments)},Pg=s._CropAndResize=function(){return(Pg=s._CropAndResize=s.asm.CropAndResize).apply(null,arguments)},Ic=s._Cumprod=function(){return(Ic=s._Cumprod=s.asm.Cumprod).apply(null,arguments)},_g=s._Cumsum=function(){return(_g=s._Cumsum=s.asm.Cumsum).apply(null,arguments)},zg=s._DepthToSpace=function(){return(zg=s._DepthToSpace=s.asm.DepthToSpace).apply(null,arguments)},Og=s._DepthwiseConv2dNative=function(){return(Og=s._DepthwiseConv2dNative=s.asm.DepthwiseConv2dNative).apply(null,arguments)},Dg=s._Elu=function(){return(Dg=s._Elu=s.asm.Elu).apply(null,arguments)},Lg=s._Equal=function(){return(Lg=s._Equal=s.asm.Equal).apply(null,arguments)},Sc=s._Exp=function(){return(Sc=s._Exp=s.asm.Exp).apply(null,arguments)},Bg=s._FlipLeftRight=function(){return(Bg=s._FlipLeftRight=s.asm.FlipLeftRight).apply(null,arguments)},Wg=s._Floor=function(){return(Wg=s._Floor=s.asm.Floor).apply(null,arguments)},po=s._FloorDiv=function(){return(po=s._FloorDiv=s.asm.FloorDiv).apply(null,arguments)},ap=s._FusedBatchNorm=function(){return(ap=s._FusedBatchNorm=s.asm.FusedBatchNorm).apply(null,arguments)},Vg=s._FusedConv2D=function(){return(Vg=s._FusedConv2D=s.asm.FusedConv2D).apply(null,arguments)},Ug=s._FusedDepthwiseConv2D=function(){return(Ug=s._FusedDepthwiseConv2D=s.asm.FusedDepthwiseConv2D).apply(null,arguments)},Gg=s._Gather=function(){return(Gg=s._Gather=s.asm.Gather).apply(null,arguments)},Xe=s._GatherNd=function(){return(Xe=s._GatherNd=s.asm.GatherNd).apply(null,arguments)},jg=s._Greater=function(){return(jg=s._Greater=s.asm.Greater).apply(null,arguments)},Hg=s._GreaterEqual=function(){return(Hg=s._GreaterEqual=s.asm.GreaterEqual).apply(null,arguments)},qg=s._LeakyRelu=function(){return(qg=s._LeakyRelu=s.asm.LeakyRelu).apply(null,arguments)},Kg=s._Less=function(){return(Kg=s._Less=s.asm.Less).apply(null,arguments)},Xg=s._LessEqual=function(){return(Xg=s._LessEqual=s.asm.LessEqual).apply(null,arguments)},Zg=s._Log=function(){return(Zg=s._Log=s.asm.Log).apply(null,arguments)},sp=s._LogicalAnd=function(){return(sp=s._LogicalAnd=s.asm.LogicalAnd).apply(null,arguments)},Tc=s._Max=function(){return(Tc=s._Max=s.asm.Max).apply(null,arguments)},Nc=s._MaxPool=function(){return(Nc=s._MaxPool=s.asm.MaxPool).apply(null,arguments)},Yg=s._Maximum=function(){return(Yg=s._Maximum=s.asm.Maximum).apply(null,arguments)},Jg=s._Mean=function(){return(Jg=s._Mean=s.asm.Mean).apply(null,arguments)},Qg=s._Min=function(){return(Qg=s._Min=s.asm.Min).apply(null,arguments)},e1=s._Minimum=function(){return(e1=s._Minimum=s.asm.Minimum).apply(null,arguments)},t1=s._MirrorPad=function(){return(t1=s._MirrorPad=s.asm.MirrorPad).apply(null,arguments)},r1=s._Multiply=function(){return(r1=s._Multiply=s.asm.Multiply).apply(null,arguments)},Ft=s._Neg=function(){return(Ft=s._Neg=s.asm.Neg).apply(null,arguments)},n1=s._NonMaxSuppressionV3=function(){return(n1=s._NonMaxSuppressionV3=s.asm.NonMaxSuppressionV3).apply(null,arguments)},a1=s._NonMaxSuppressionV4=function(){return(a1=s._NonMaxSuppressionV4=s.asm.NonMaxSuppressionV4).apply(null,arguments)},s1=s._NonMaxSuppressionV5=function(){return(s1=s._NonMaxSuppressionV5=s.asm.NonMaxSuppressionV5).apply(null,arguments)},Ql=s._NotEqual=function(){return(Ql=s._NotEqual=s.asm.NotEqual).apply(null,arguments)},Cc=s._OneHot=function(){return(Cc=s._OneHot=s.asm.OneHot).apply(null,arguments)},Ec=s._PadV2=function(){return(Ec=s._PadV2=s.asm.PadV2).apply(null,arguments)},Rc=s._Pow=function(){return(Rc=s._Pow=s.asm.Pow).apply(null,arguments)},i1=s._Prelu=function(){return(i1=s._Prelu=s.asm.Prelu).apply(null,arguments)},Mc=s._Prod=function(){return(Mc=s._Prod=s.asm.Prod).apply(null,arguments)},o1=s._RealDiv=function(){return(o1=s._RealDiv=s.asm.RealDiv).apply(null,arguments)},y3=s._Relu=function(){return(y3=s._Relu=s.asm.Relu).apply(null,arguments)},Fc=s._Relu6=function(){return(Fc=s._Relu6=s.asm.Relu6).apply(null,arguments)},A3=s._ResizeBilinear=function(){return(A3=s._ResizeBilinear=s.asm.ResizeBilinear).apply(null,arguments)},l1=s._Reverse=function(){return(l1=s._Reverse=s.asm.Reverse).apply(null,arguments)},u1=s._RotateWithOffset=function(){return(u1=s._RotateWithOffset=s.asm.RotateWithOffset).apply(null,arguments)},d1=s._Round=function(){return(d1=s._Round=s.asm.Round).apply(null,arguments)},p1=s._Rsqrt=function(){return(p1=s._Rsqrt=s.asm.Rsqrt).apply(null,arguments)},h1=s._ScatterNd=function(){return(h1=s._ScatterNd=s.asm.ScatterNd).apply(null,arguments)},c1=s._SelectV2=function(){return(c1=s._SelectV2=s.asm.SelectV2).apply(null,arguments)},f1=s._Sigmoid=function(){return(f1=s._Sigmoid=s.asm.Sigmoid).apply(null,arguments)},m1=s._Sin=function(){return(m1=s._Sin=s.asm.Sin).apply(null,arguments)},g1=s._Softmax=function(){return(g1=s._Softmax=s.asm.Softmax).apply(null,arguments)},y1=s._SparseFillEmptyRows=function(){return(y1=s._SparseFillEmptyRows=s.asm.SparseFillEmptyRows).apply(null,arguments)},A1=s._SparseReshape=function(){return(A1=s._SparseReshape=s.asm.SparseReshape).apply(null,arguments)},x1=s._SparseSegmentReduction=function(){return(x1=s._SparseSegmentReduction=s.asm.SparseSegmentReduction).apply(null,arguments)},b1=s._Sqrt=function(){return(b1=s._Sqrt=s.asm.Sqrt).apply(null,arguments)},v1=s._Square=function(){return(v1=s._Square=s.asm.Square).apply(null,arguments)},w1=s._SquaredDifference=function(){return(w1=s._SquaredDifference=s.asm.SquaredDifference).apply(null,arguments)},k1=s._Step=function(){return(k1=s._Step=s.asm.Step).apply(null,arguments)},I1=s._StridedSlice=function(){return(I1=s._StridedSlice=s.asm.StridedSlice).apply(null,arguments)},S1=s._Sub=function(){return(S1=s._Sub=s.asm.Sub).apply(null,arguments)},T1=s._Sum=function(){return(T1=s._Sum=s.asm.Sum).apply(null,arguments)},N1=s._Tan=function(){return(N1=s._Tan=s.asm.Tan).apply(null,arguments)},C1=s._Tanh=function(){return(C1=s._Tanh=s.asm.Tanh).apply(null,arguments)},E1=s._Tile=function(){return(E1=s._Tile=s.asm.Tile).apply(null,arguments)},R1=s._TopK=function(){return(R1=s._TopK=s.asm.TopK).apply(null,arguments)},M1=s._Transform=function(){return(M1=s._Transform=s.asm.Transform).apply(null,arguments)},F1=s._Transpose=function(){return(F1=s._Transpose=s.asm.Transpose).apply(null,arguments)},$1=s.__FusedMatMul=function(){return($1=s.__FusedMatMul=s.asm._FusedMatMul).apply(null,arguments)},P1=s._malloc=function(){return(P1=s._malloc=s.asm.malloc).apply(null,arguments)},_1=s._free=function(){return(_1=s._free=s.asm.free).apply(null,arguments)},z1=s.___errno_location=function(){return(z1=s.___errno_location=s.asm.__errno_location).apply(null,arguments)},O1=s._emscripten_main_thread_process_queued_calls=function(){return(O1=s._emscripten_main_thread_process_queued_calls=s.asm.emscripten_main_thread_process_queued_calls).apply(null,arguments)},$c=s.stackSave=function(){return($c=s.stackSave=s.asm.stackSave).apply(null,arguments)},Pc=s.stackRestore=function(){return(Pc=s.stackRestore=s.asm.stackRestore).apply(null,arguments)},ip=s.stackAlloc=function(){return(ip=s.stackAlloc=s.asm.stackAlloc).apply(null,arguments)},D1=s.dynCall_iijjiiii=function(){return(D1=s.dynCall_iijjiiii=s.asm.dynCall_iijjiiii).apply(null,arguments)},L1=s.dynCall_jiji=function(){return(L1=s.dynCall_jiji=s.asm.dynCall_jiji).apply(null,arguments)};s.cwrap=Me;var eu;function op(H){this.name="ExitStatus",this.message="Program terminated with exit("+H+")",this.status=H}ys=function H(){eu||lp(),eu||(ys=H)};function lp(H){if(H=H||d,kn>0||(uc(),kn>0))return;function ne(){eu||(eu=!0,s.calledRun=!0,!ae&&(dc(),i(s),s.onRuntimeInitialized&&s.onRuntimeInitialized(),pc()))}s.setStatus?(s.setStatus("Running..."),setTimeout(function(){setTimeout(function(){s.setStatus("")},1),ne()},1)):ne()}s.run=lp;function x3(H){de=H,ep()||(s.onExit&&s.onExit(H),ae=!0),p(H,new op(H))}if(s.preInit)for(typeof s.preInit=="function"&&(s.preInit=[s.preInit]);s.preInit.length>0;)s.preInit.pop()();lp();var tu;l&&(tu={uncaughtException:process.listeners("uncaughtException").filter(function(H){return!l.uncaughtException.indexOf(H)>-1}),unhandledRejection:process.listeners("unhandledRejection").filter(function(H){return!l.unhandledRejection.indexOf(H)>-1})});var ru;if(typeof a!="undefined")ru=a;else if(typeof WasmBackendModuleThreadedSimd!="undefined")ru=WasmBackendModuleThreadedSimd;else throw new Error("Could not find wasm module in post.js");if(tu){var B1=ru._dispose;ru._dispose=function(){B1(),tu.uncaughtException.forEach(function(H){process.removeListener("uncaughtException",H)}),tu.unhandledRejection.forEach(function(H){process.removeListener("unhandledRejection",H)})}}return a.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)}}),hR=1e-7,cR=1e-4,qp=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}},$u=class{refCount(e){return Sn("refCount")}incRef(e){return Sn("incRef")}timerAvailable(){return!0}time(e){return Sn("time")}read(e){return Sn("read")}readSync(e){return Sn("readSync")}readToGPU(e,t){return Sn("readToGPU")}numDataIds(){return Sn("numDataIds")}disposeData(e,t){return Sn("disposeData")}write(e,t,r){return Sn("write")}move(e,t,r,n,a){return Sn("move")}memory(){return Sn("memory")}floatPrecision(){return Sn("floatPrecision")}epsilon(){return this.floatPrecision()===32?hR:cR}dispose(){return Sn("dispose")}};function Sn(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 xw(e){let t=e.length,r=0;for(;t>0;)r=Math.random()*t|0,t--,cf(e,t,r)}function fR(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,n=0;for(;r>0;)n=Math.random()*r|0,r--,cf(e,r,n),cf(t,r,n)}function $p(e,t,r){return Math.max(e,Math.min(t,r))}function mR(e){return e%2===0?e:e+1}function cf(e,t,r){let n=e[t];e[t]=e[r],e[r]=n}function gR(e){let t=0;for(let r=0;r<e.length;r++)t+=e[r];return t}function yR(e,t){let r=Math.random();return t*r+(1-r)*e}function AR(e,t){let r=0;for(let n=0;n<e.length;n++){let a=Number(e[n])-Number(t[n]);r+=a*a}return r}function P(e,t){if(!e)throw new Error(typeof t=="string"?t:t())}function Vr(e,t,r=""){P(qs(e,t),()=>r+` Shapes ${e} and ${t} must match`)}function Wo(e){P(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function Eo(e,t=[],r=!1){if(t==null&&(t=[]),Array.isArray(e)||Sr(e)&&!r)for(let n=0;n<e.length;++n)Eo(e[n],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 xR(e){return e.length===0}function qs(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 xu(e){return e%1===0}function bR(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 vR(e){let t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function wR(e){let t=new Uint32Array(e);for(let r=0;r<e;++r)t[r]=r;return xw(t),t}function Cp(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function kR(e,t=n=>0,r){return new Promise((n,a)=>{let s=0,i=()=>{if(e()){n();return}s++;let o=t(s);if(r!=null&&s>=r){a();return}setTimeout(i,o)};i()})}function IR(e,t){let r=1,n=-1;for(let s=0;s<e.length;++s)if(e[s]>=0)r*=e[s];else if(e[s]===-1){if(n!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${n} and dim ${s}`);n=s}else if(e[s]<0)throw Error(`Shapes can not be < 0. Found ${e[s]} at dim ${s}`);if(n===-1){if(t>0&&t!==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 a=e.slice();return a[n]=t/r,a}function Gn(e,t){let r=t.length;return e=e==null?t.map((n,a)=>a):[].concat(e),P(e.every(n=>n>=-r&&n<r),()=>`All values in axis param must be in range [-${r}, ${r}) but got axis ${e}`),P(e.every(n=>xu(n)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(n=>n<0?r+n:n)}function bw(e,t){let r=[],n=[],a=t!=null&&Array.isArray(t)&&t.length===0,s=t==null||a?null:Gn(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]),n.push(o)),s[i]<=o&&i++}e[o]!==1&&(r.push(e[o]),n.push(o))}return{newShape:r,keptDims:n}}function vw(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 ww(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 kw(e,t){for(let r=0;r<e.length;r++){let n=e[r];if(isNaN(n)||!isFinite(n))throw Error(`A tensor of type ${t} being uploaded contains ${n}.`)}}function Iw(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function SR(e,t){return!(t==="complex64"||t==="float32"&&e!=="complex64"||t==="int32"&&e!=="float32"&&e!=="complex64"||t==="bool"&&e==="bool")}function Sr(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}function ly(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 Sw(e){if(e==null)return 0;let t=0;return e.forEach(r=>t+=r.length),t}function Ts(e){return typeof e=="string"||e instanceof String}function Tw(e){return typeof e=="boolean"}function Nw(e){return typeof e=="number"}function Hf(e){return Array.isArray(e)?Hf(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":Nw(e)?"float32":Ts(e)?"string":Tw(e)?"bool":"float32"}function Ms(e){return!!(e&&e.constructor&&e.call&&e.apply)}function ff(e,t){for(let r=t;r<e;++r)if(e%r===0)return r;return e}function Pu(e){let t=e.length;if(t<2)return[];let r=new Array(t-1);r[t-2]=e[t-1];for(let n=t-3;n>=0;--n)r[n]=r[n+1]*e[n+1];return r}function Cw(e,t,r,n=!1){let a=new Array;if(t.length===1){let s=t[0]*(n?2:1);for(let i=0;i<s;i++)a[i]=r[e+i]}else{let s=t[0],i=t.slice(1),o=i.reduce((l,u)=>l*u)*(n?2:1);for(let l=0;l<s;l++)a[l]=Cw(e+l*o,i,r,n)}return a}function fu(e,t,r=!1){if(e.length===0)return t[0];let n=e.reduce((a,s)=>a*s)*(r?2:1);if(n===0)return[];if(n!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${r?" for a complex tensor":""}.`);return Cw(0,e,t,r)}function d2(e,t){let r=qf(e,t);for(let n=0;n<r.length;n++)r[n]=1;return r}function qf(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 TR(e,t){let r=e.reduce((n,a)=>n*a,1);if(t==null||t==="float32")return fu(e,new Float32Array(r));if(t==="int32")return fu(e,new Int32Array(r));if(t==="bool")return fu(e,new Uint8Array(r));throw new Error(`Unknown data type ${t}`)}function p2(e){e.forEach(t=>{P(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function NR(e,t,r){if(t===0)return 0;if(t===1)return e[0];let n=e[e.length-1];for(let a=0;a<e.length-1;++a)n+=r[a]*e[a];return n}function CR(e,t,r){if(t===0)return[];if(t===1)return[e];let n=new Array(t);for(let a=0;a<n.length-1;++a)n[a]=Math.floor(e/r[a]),e-=n[a]*r[a];return n[n.length-1]=e,n}function h2(e){return e&&e.then&&typeof e.then=="function"}var M3="tfjsflags",Ew=class{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=ER,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 n=this.urlFlags[e];Y().getBool("IS_TEST")||Y().getBool("PROD")||console.warn(`Setting feature override from URL ${e}: ${n}.`),this.set(e,n)}}async getAsync(e){return e in this.flags?this.flags[e]:(this.flags[e]=await this.evaluateFlag(e),this.flags[e])}get(e){if(e in this.flags)return this.flags[e];let t=this.evaluateFlag(e);if(h2(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);M3 in e&&e[M3].split(",").forEach(t=>{let[r,n]=t.split(":");this.urlFlags[r]=MR(r,n)})}};function ER(e){let t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(r,...n)=>(RR(t,n[0],n[1]),n.join("="))),t}function RR(e,t,r){e[decodeURIComponent(t)]=decodeURIComponent(r||"")}function MR(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 Aa}var Aa=null;function FR(e){Aa=e}var K1;function Rw(){if(K1==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");K1=e}return K1}function $R(){let e=Rw();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function c2(e,t){let r=$R();if(r.has(e))return r.get(e);{let n=t();return r.set(e,n),r.get(e)}}var Vo="Abs",_u="Acos",zu="Acosh",Ja="Add",Ks="AddN",Ou="All",Du="Any",Xs="ArgMax",Lu="ArgMin",Bu="Asin",Wu="Asinh",Vu="Atan",Uu="Atanh",Gu="Atan2",Zs="AvgPool",Kf="AvgPoolGrad",Kp="AvgPool3D",Xf="AvgPool3DGrad",Ys="BatchMatMul",Uo="BatchToSpaceND",Zf="Bincount",Mw="BroadcastTo",Yf="BroadcastArgs",Js="Cast",Qs="Ceil",Qa="ClipByValue",Xp="Complex",Zp="ComplexAbs",Go="Concat",ei="Conv2D",Jf="Conv2DBackpropFilter",ti="Conv2DBackpropInput",Yp="Conv3D",Qf="Conv3DBackpropFilterV2",em="Conv3DBackpropInputV2",ri="Cos",ni="Cosh",jo="Cumprod",ai="Cumsum",Ho="CropAndResize",tm="DenseBincount",qo="DepthToSpace",si="DepthwiseConv2dNative",rm="DepthwiseConv2dNativeBackpropFilter",nm="DepthwiseConv2dNativeBackpropInput",am="Diag",Jp="Dilation2D",mf="Dilation2DBackpropInput",gf="Dilation2DBackpropFilter",ii="RealDiv",Qp="Einsum",oi="Elu",sm="EluGrad",ju="Erf",Ko="Equal",li="Exp",Xo="ExpandDims",Zo="Expm1",im="FFT",Hu="Fill",Yo="FlipLeftRight",ui="Floor",di="FloorDiv",pi="FusedBatchNorm",Jo="GatherV2",Qo="GatherNd",el="Greater",hi="GreaterEqual",ci="Identity",om="IFFT",eh="Imag",qu="IsFinite",Ku="IsInf",Xu="IsNan",fi="LeakyRelu",tl="Less",rl="LessEqual",lm="LinSpace",mi="Log",Zu="Log1p",nl="LogicalAnd",Yu="LogicalNot",th="LogicalOr",Fw="LogSoftmax",rh="LRN",um="LRNGrad",gi="Max",yi="Maximum",Ai="MaxPool",dm="MaxPoolGrad",nh="MaxPool3D",pm="MaxPool3DGrad",hm="MaxPoolWithArgmax",xi="Mean",bi="Min",vi="Minimum",wi="MirrorPad",Ju="Mod",cm="Multinomial",ki="Multiply",al="Neg",sl="NotEqual",il="NonMaxSuppressionV3",Qu="NonMaxSuppressionV4",ol="NonMaxSuppressionV5",ll="OnesLike",ul="OneHot",dl="Pack",Ii="PadV2",PR="Pool",Si="Pow",Ti="Prelu",Ni="Prod",ed="Range",ah="Real",td="Reciprocal",Ci="Relu",pl="Reshape",rd="ResizeNearestNeighbor",fm="ResizeNearestNeighborGrad",Ei="ResizeBilinear",mm="ResizeBilinearGrad",Ri="Relu6",hl="Reverse",cl="Round",Mi="Rsqrt",fl="ScatterNd",ml="Select",nd="Selu",gl="Slice",Fi="Sin",yl="Sinh",ad="Sign",$i="Sigmoid",sd="Softplus",Pi="Sqrt",_i="Sum",Al="SpaceToBatchND",xl="SplitV",zi="Softmax",sh="SparseFillEmptyRows",id="SparseReshape",ih="SparseSegmentMean",oh="SparseSegmentSum",lh="SparseToDense",Oi="SquaredDifference",od="Square",bl="StridedSlice",uh="StringNGrams",gm="StringSplit",ym="StringToHashBucketFast",Di="Sub",vl="Tan",Li="Tanh",es="Tile",wl="TopK",kl="Transform",Bi="Transpose",Am="Unique",Il="Unpack",dh="UnsortedSegmentSum",Sl="ZerosLike",Wi="Step",Pp="FromPixels",Tl="RotateWithOffset",Fs="_FusedMatMul",$s="FusedConv2D",Ps="FusedDepthwiseConv2D";function Ss(...e){Y().getBool("IS_TEST")||Y().getBool("PROD")||console.warn(...e)}function _R(...e){Y().getBool("IS_TEST")||Y().getBool("PROD")||console.log(...e)}var bu=c2("kernelRegistry",()=>new Map),_p=c2("gradRegistry",()=>new Map);function yf(e,t){let r=f2(e,t);return bu.get(r)}function uy(e){return _p.get(e)}function Ra(e){let t=bu.entries(),r=[];for(;;){let{done:n,value:a}=t.next();if(n)break;let[s,i]=a,[o]=s.split("_");o===e&&r.push(i)}return r}function jn(e){let{kernelName:t,backendName:r}=e,n=f2(t,r);bu.has(n)&&Ss(`The kernel '${t}' for backend '${r}' is already registered`),bu.set(n,e)}function $w(e){let{kernelName:t}=e;_p.has(t)&&Y().getBool("DEBUG")&&Ss(`Overriding the gradient for '${t}'`),_p.set(t,e)}function zR(e,t){let r=f2(e,t);if(!bu.has(r))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);bu.delete(r)}function OR(e){if(!_p.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);_p.delete(e)}function DR(e,t){Ra(e).forEach(r=>{let n=Object.assign({},r,{backendName:t});jn(n)})}function f2(e,t){return`${t}_${e}`}var w={};Le(w,{arraysEqual:()=>qs,assert:()=>P,assertNonNegativeIntegerDimensions:()=>p2,assertNonNull:()=>Wo,assertShapesMatch:()=>Vr,bytesFromStringArray:()=>Sw,bytesPerElement:()=>ly,checkConversionForErrors:()=>kw,clamp:()=>$p,computeStrides:()=>Pu,createScalarValue:()=>GR,createShuffledIndices:()=>wR,decodeString:()=>Af,distSquared:()=>AR,encodeString:()=>hh,fetch:()=>HR,fingerPrint64:()=>UR,flatten:()=>Eo,getArrayFromDType:()=>ww,getTypedArrayFromDType:()=>vw,hasEncodingLoss:()=>SR,hexToLong:()=>ph,indexToLoc:()=>CR,inferDtype:()=>Hf,inferFromImplicitShape:()=>IR,isBoolean:()=>Tw,isFunction:()=>Ms,isInt:()=>xu,isNumber:()=>Nw,isPromise:()=>h2,isScalarShape:()=>xR,isString:()=>Ts,isTypedArray:()=>Sr,isValidDtype:()=>Iw,locToIndex:()=>NR,makeOnesTypedArray:()=>d2,makeZerosNestedTypedArray:()=>TR,makeZerosTypedArray:()=>qf,nearestDivisor:()=>ff,nearestLargerEven:()=>mR,now:()=>zp,parseAxisParam:()=>Gn,randUniform:()=>yR,repeatedTry:()=>kR,rightPad:()=>Cp,shuffle:()=>xw,shuffleCombo:()=>fR,sizeFromShape:()=>Tt,sizeToSquarishShape:()=>vR,squeezeShape:()=>bw,sum:()=>gR,swap:()=>cf,tanh:()=>bR,toNestedArray:()=>fu,toTypedArray:()=>xm});var F3=Bo(ZE()),Ao=F3.default||F3;function ph(e){return Ao.fromString(e,!0,16)}var Pw=ph("c3a5c85c97cb3127"),mo=ph("b492b66fbe98f273"),Or=ph("9ae16a3b2f90404f");function dy(e){return e.xor(e.shru(47))}function _w(e,t,r){let n=e.slice(t,t+r);return Ao.fromBytes(Array.from(n),!0,!0)}function wt(e,t){return _w(e,t,8)}function $3(e,t){return _w(e,t,4)}function cr(e,t){return t===0?e:e.shru(t).or(e.shl(64-t))}function Cs(e,t,r=ph("9ddfea08eb382d69")){let n=e.xor(t).mul(r);n=n.xor(n.shru(47));let a=t.xor(n).mul(r);return a=a.xor(a.shru(47)),a=a.mul(r),a}function LR(e,t,r,n,a,s){a=a.add(e),s=cr(s.add(a).add(n),21);let i=a;return a=a.add(t),a=a.add(r),s=s.add(cr(a,44)),[a.add(n),s.add(i)]}function Uc(e,t,r,n){return LR(wt(e,t),wt(e,t+8),wt(e,t+16),wt(e,t+24),r,n)}function BR(e,t=e.length){if(t>=8){let r=Or.add(t*2),n=wt(e,0).add(Or),a=wt(e,t-8),s=cr(a,37).mul(r).add(n),i=cr(n,25).add(a).mul(r);return Cs(s,i,r)}if(t>=4){let r=Or.add(t*2),n=$3(e,0);return Cs(n.shl(3).add(t),$3(e,t-4),r)}if(t>0){let r=e[0],n=e[t>>1],a=e[t-1],s=r+(n<<8),i=t+(a<<2);return dy(Or.mul(s).xor(Pw.mul(i))).mul(Or)}return Or}function WR(e,t=e.length){let r=Or.add(t*2),n=wt(e,0).mul(mo),a=wt(e,8),s=wt(e,t-8).mul(r),i=wt(e,t-16).mul(Or);return Cs(cr(n.add(a),43).add(cr(s,30)).add(i),n.add(cr(a.add(Or),18)).add(s),r)}function VR(e,t=e.length){let r=Or.add(t*2),n=wt(e,0).mul(Or),a=wt(e,8),s=wt(e,t-8).mul(r),i=wt(e,t-16).mul(Or),o=cr(n.add(a),43).add(cr(s,30)).add(i),l=Cs(o,n.add(cr(a.add(Or),18)).add(s),r),u=wt(e,16).mul(r),d=wt(e,24),h=o.add(wt(e,t-32)).mul(r),p=l.add(wt(e,t-24)).mul(r);return Cs(cr(u.add(d),43).add(cr(h,30)).add(p),u.add(cr(d.add(n),18)).add(h),r)}function UR(e,t=e.length){let r=Ao.fromNumber(81,!0);if(t<=32)return t<=16?BR(e,t):WR(e,t);if(t<=64)return VR(e,t);let n=r,a=r.mul(mo).add(113),s=dy(a.mul(Or).add(113)).mul(Or),i=[Ao.UZERO,Ao.UZERO],o=[Ao.UZERO,Ao.UZERO];n=n.mul(Or).add(wt(e,0));let l=0,u=(t-1>>6)*64,d=u+(t-1&63)-63;do n=cr(n.add(a).add(i[0]).add(wt(e,l+8)),37).mul(mo),a=cr(a.add(i[1]).add(wt(e,l+48)),42).mul(mo),n=n.xor(o[1]),a=a.add(i[0]).add(wt(e,l+40)),s=cr(s.add(o[0]),33).mul(mo),i=Uc(e,l,i[1].mul(mo),n.add(o[0])),o=Uc(e,l+32,s.add(o[1]),a.add(wt(e,l+16))),[s,n]=[n,s],l+=64;while(l!==u);let h=mo.add(s.and(255).shl(1));return l=d,o[0]=o[0].add(t-1&63),i[0]=i[0].add(o[0]),o[0]=o[0].add(i[0]),n=cr(n.add(a).add(i[0]).add(wt(e,l+8)),37).mul(h),a=cr(a.add(i[1]).add(wt(e,l+48)),42).mul(h),n=n.xor(o[1].mul(9)),a=a.add(i[0].mul(9).add(wt(e,l+40))),s=cr(s.add(o[0]),33).mul(h),i=Uc(e,l,i[1].mul(h),n.add(o[0])),o=Uc(e,l+32,s.add(o[1]),a.add(wt(e,l+16))),[s,n]=[n,s],Cs(Cs(i[0],o[0],h).add(dy(a).mul(Pw)).add(s),Cs(i[1],o[1],h).add(n),h)}function GR(e,t){return t==="string"?hh(e):xm([e],t)}function jR(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function xm(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=Eo(e)),Y().getBool("DEBUG")&&kw(e,t),jR(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 n=0;n<r.length;++n)Math.round(e[n])!==0&&(r[n]=1);return r}else throw new Error(`Unknown data type ${t}`)}function zp(){return Y().platform.now()}function HR(e,t){return Y().platform.fetch(e,t)}function hh(e,t="utf-8"){return t=t||"utf-8",Y().platform.encode(e,t)}function Af(e,t="utf-8"){return t=t||"utf-8",Y().platform.decode(e,t)}var qR=class{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new XR)}profileKernel(e,t,r){let n,a=()=>{n=r()},s,i=zp();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(a);else{a();for(let o of n)o.dataSync();s=Promise.resolve({kernelMs:zp()-i})}if(Y().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let o=0;o<n.length;o++){let l=n[o];l.data().then(u=>{KR(u,l.dtype,e)})}return{kernelName:e,outputs:n,inputs:t,timeMs:s.then(o=>o.kernelMs),extraInfo:s.then(o=>o.getExtraProfileInfo!=null?o.getExtraProfileInfo():"")}}logKernelProfile(e){let{kernelName:t,outputs:r,timeMs:n,inputs:a,extraInfo:s}=e;r.forEach(i=>{Promise.all([i.data(),n,s]).then(o=>{this.logger.logKernelProfile(t,i,o[0],o[1],a,o[2])})})}};function KR(e,t,r){if(t!=="float32")return!1;for(let n=0;n<e.length;n++){let a=e[n];if(isNaN(a)||!isFinite(a))return console.warn(`Found ${a} in the result of '${r}'`),!0}return!1}var XR=class{logKernelProfile(e,t,r,n,a,s){let i=typeof n=="number"?Cp(`${n}ms`,9):n.error,o=Cp(e,25),l=t.rank,u=t.size,d=Cp(t.shape.toString(),14),h="";for(let p in a){let c=a[p];if(c!=null){let f=c.shape||t.shape,m=f.length;h+=`${p}: ${m}D ${m>0?f:""} `}}console.log(`%c${o} %c${i} %c${l}D ${d} %c${u} %c${h} %c${s}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function ZR(e,t,r){let n={},a={};for(let l=0;l<t.length;l++)n[t[l].id]=!0;for(let l=0;l<e.length;l++){let u=e[l],d=u.inputs;for(let h in d){let p=d[h],c=!1;for(let f=0;f<t.length;f++)if(n[p.id]){u.outputs.forEach(m=>n[m.id]=!0),c=!0,a[u.id]=!0;break}if(c)break}}let s={};s[r.id]=!0;let i={};for(let l=e.length-1;l>=0;l--){let u=e[l],d=u.inputs;for(let h=0;h<u.outputs.length;h++)if(s[u.outputs[h].id]){for(let p in d)s[d[p].id]=!0,i[u.id]=!0;break}}let o=[];for(let l=0;l<e.length;l++){let u=e[l];if(a[u.id]&&i[u.id]){let d={};for(let p in u.inputs){let c=u.inputs[p];n[c.id]&&(d[p]=c)}let h=Object.assign({},u);h.inputs=d,h.outputs=u.outputs,o.push(h)}}return o}function YR(e,t,r,n){for(let a=t.length-1;a>=0;a--){let s=t[a],i=[];if(s.outputs.forEach(l=>{let u=e[l.id];u!=null?i.push(u):i.push(null)}),s.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`);let o=s.gradient(i);for(let l in s.inputs){if(!(l in o))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(o)}.`);let u=r(()=>o[l]());if(u.dtype!=="float32")throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${u.dtype}'`);let d=s.inputs[l];if(!qs(u.shape,d.shape))throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${l}' has shape '${u.shape}', which does not match the shape of the input '${d.shape}'`);if(e[d.id]==null)e[d.id]=u;else{let h=e[d.id];e[d.id]=n(h,u),h.dispose()}}}}var P3=20,fp=3,X1=7;function JR(e,t,r,n){let a=Pu(t),s=QR(e,t,r,a),i=t.length,o=ef(e,t,r,a,s),l=["Tensor"];return n&&(l.push(` dtype: ${r}`),l.push(` rank: ${i}`),l.push(` shape: [${t}]`),l.push(" values:")),l.push(o.map(u=>" "+u).join(`
|
|
`)),l.join(`
|
|
`)}function QR(e,t,r,n){let a=Tt(t),s=n[n.length-1],i=new Array(s).fill(0),o=t.length,l=r==="complex64"?xp(e):e;if(o>1)for(let u=0;u<a/s;u++){let d=u*s;for(let h=0;h<s;h++)i[h]=Math.max(i[h],Ap(l[d+h],0,r).length)}return i}function Ap(e,t,r){let n;return Array.isArray(e)?n=`${parseFloat(e[0].toFixed(X1))} + ${parseFloat(e[1].toFixed(X1))}j`:Ts(e)?n=`'${e}'`:r==="bool"?n=zw(e):n=parseFloat(e.toFixed(X1)).toString(),Cp(n,t)}function zw(e){return e===0?"false":"true"}function ef(e,t,r,n,a,s=!0){let i=r==="complex64"?2:1,o=t[0],l=t.length;if(l===0){if(r==="complex64"){let m=xp(e);return[Ap(m[0],0,r)]}return r==="bool"?[zw(e[0])]:[e[0].toString()]}if(l===1){if(o>P3){let g=fp*i,y=Array.from(e.slice(0,g)),A=Array.from(e.slice((o-fp)*i,o*i));return r==="complex64"&&(y=xp(y),A=xp(A)),["["+y.map((x,b)=>Ap(x,a[b],r)).join(", ")+", ..., "+A.map((x,b)=>Ap(x,a[o-fp+b],r)).join(", ")+"]"]}let m=r==="complex64"?xp(e):Array.from(e);return["["+m.map((g,y)=>Ap(g,a[y],r)).join(", ")+"]"]}let u=t.slice(1),d=n.slice(1),h=n[0]*i,p=[];if(o>P3){for(let m=0;m<fp;m++){let g=m*h,y=g+h;p.push(...ef(e.slice(g,y),u,r,d,a,!1))}p.push("...");for(let m=o-fp;m<o;m++){let g=m*h,y=g+h;p.push(...ef(e.slice(g,y),u,r,d,a,m===o-1))}}else for(let m=0;m<o;m++){let g=m*h,y=g+h;p.push(...ef(e.slice(g,y),u,r,d,a,m===o-1))}let c=l===2?",":"";p[0]="["+p[0]+c;for(let m=1;m<p.length-1;m++)p[m]=" "+p[m]+c;let f=`,
|
|
`;for(let m=2;m<l;m++)f+=`
|
|
`;return p[p.length-1]=" "+p[p.length-1]+"]"+(s?"":f),p}function xp(e){let t=[];for(let r=0;r<e.length;r+=2)t.push([e[r],e[r+1]]);return t}var sr=class{constructor(e,t,r){if(this.dtype=t,this.shape=e.slice(),this.size=Tt(e),r!=null){let n=r.length;P(n===this.size,()=>`Length of values '${n}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=r||ww(t,this.size),this.strides=Pu(e)}set(e,...t){t.length===0&&(t=[0]),P(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);let r=this.locToIndex(t);this.values[r]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let n of e){if(n<0||n>=this.shape[t]){let a=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(a)}t++}let r=e[e.length-1];for(let n=0;n<e.length-1;++n)r+=this.strides[n]*e[n];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 ia().makeTensor(this.values,this.shape,this.dtype)}},ia=null,pu=null,eM=null;function tM(e){ia=e}function rM(e){pu=e}function nM(e){eM=e}var nt=class{constructor(e,t,r,n){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=Tt(e),this.strides=Pu(e),this.dataId=r,this.id=n,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){let e=await this.data();return pu.buffer(this.shape,this.dtype,e)}bufferSync(){return pu.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return fu(this.shape,e,this.dtype==="complex64")}arraySync(){return fu(this.shape,this.dataSync(),this.dtype==="complex64")}async data(){this.throwIfDisposed();let e=ia().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(r=>Af(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(),ia().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();let e=ia().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>Af(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 ia().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(ia().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return pu.print(this,e)}clone(){return this.throwIfDisposed(),pu.clone(this)}toString(e=!1){let t=this.dataSync();return JR(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),pu.cast(this,e)}variable(e=!0,t,r){return this.throwIfDisposed(),ia().makeVariable(this,e,t,r)}};Object.defineProperty(nt,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function aM(){return c2("Tensor",()=>nt)}aM();var Op=class extends nt{constructor(e,t,r,n){super(e.shape,e.dtype,e.dataId,n),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(!qs(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);ia().disposeTensor(this),this.dataId=e.dataId,ia().incRef(this,null)}dispose(){ia().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(Op,Symbol.hasInstance,{value:e=>e instanceof nt&&e.assign!=null&&e.assign instanceof Function});var da={};Le(da,{assertTypesMatch:()=>Vw,getTensorsInContainer:()=>m2,isTensorInList:()=>iM,makeTypesMatch:()=>Dt});var Ow=(e=>(e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6",e))(Ow||{}),Dw=(e=>(e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64",e))(Dw||{}),Lw=(e=>(e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64",e))(Lw||{}),Bw=(e=>(e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64",e))(Bw||{}),Ww=(e=>(e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64",e))(Ww||{}),sM={float32:Bw,int32:Dw,bool:Lw,complex64:Ww};function Cr(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return sM[e][t]}function ch(e){return Cr(e,"int32")}function Dt(e,t){if(e.dtype===t.dtype)return[e,t];let r=Cr(e.dtype,t.dtype);return[e.cast(r),t.cast(r)]}function Vw(e,t){P(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function iM(e,t){return t.some(r=>r.id===e.id)}function m2(e){let t=[];return Uw(e,t,new Set),t}function Uw(e,t,r){if(e==null)return;if(e instanceof nt){t.push(e);return}if(!oM(e))return;let n=e;for(let a in n){let s=n[a];r.has(s)||(r.add(s),Uw(s,t,r))}}function oM(e){return Array.isArray(e)||typeof e=="object"}function Z1(e){return e.kernelName!=null}var _3=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()}},py=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new _3}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?(Ss(`${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 qR(this.backendInstance),!0}setupRegisteredKernels(){Ra(this.backendName).forEach(e=>{e.setupFunc!=null&&e.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){Ra(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 $u)&&typeof r.then=="function"){let n=++this.pendingBackendInitId,a=r.then(s=>n<this.pendingBackendInitId?!1:(this.registry[e]=s,this.pendingBackendInit=null,!0)).catch(s=>(n<this.pendingBackendInitId||(this.pendingBackendInit=null,Ss(`Initialization of backend ${e} failed`),Ss(s.stack||s.message)),!1));return this.pendingBackendInit=a,{success:a,asyncInit:!0}}else return this.registry[e]=r,{success:!0,asyncInit:!1}}catch(r){return Ss(`Initialization of backend ${e} failed`),Ss(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:n,asyncInit:a}=this.initializeBackend(r);if(a||n)return{name:r,asyncInit:a}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){let r=this.state.tensorInfo.get(t),n=r.backend,a=this.readSync(t),s=n.refCount(t);n.disposeData(t,!0),r.backend=e,e.move(t,a,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 n;return this.scopedRun(()=>this.startScope(r),()=>this.endScope(n),()=>(n=t(),n instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),n))}scopedRun(e,t,r){e();try{let n=r();return t(),n}catch(n){throw t(),n}}nextTensorId(){return py.nextTensorId++}nextVariableId(){return py.nextVariableId++}clone(e){let t=B.runKernel(ci,{x:e}),r={x:e},n=s=>({x:()=>{let i="float32",o={x:s},l={dtype:i};return B.runKernel(Js,o,l)}}),a=[];return this.addTapeNode(this.state.activeScope.name,r,[t],n,a,{}),t}runKernel(e,t,r){if(this.backendName==null&&this.backend,yf(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 n=this.backend.numDataIds(),a=0;r.forEach(o=>{a+=o.dtype==="complex64"?3:1});let s=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=n-t-a-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=[],n=this.isTapeOn(),a=this.state.numBytes,s=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let i;this.backendName==null&&this.backend;let o,l=Z1(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(Z1(e)){let{kernelName:c,inputs:f,attrs:m}=e;this.backendName==null&&this.backend;let g=yf(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:S,dtype:T}=b;return this.makeTensorFromDataId(v,S,T)});if(n){let b=this.getTensorsForGradient(c,f,x);r=this.saveTensorsForBackwardMode(b)}return x}}else{let{forwardFunc:c}=e,f=m=>{!n||(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:u,attrs:d}=e,h=Z1(e)?null:e.backwardsFunc,p;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=i():(p=this.profiler.profileKernel(l,u,()=>i()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(p),t=p.outputs)}),n&&this.addTapeNode(l,u,t,h,r,d),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-a,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-s,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(u).map(c=>u[c]!=null?u[c].shape:null),outputShapes:t.map(c=>c.shape),kernelTimeMs:p.timeMs,extraInfo:p.extraInfo}),Array.isArray(o)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(t=>this.keep(this.clone(t)))}getTensorsForGradient(e,t,r){let n=uy(e);if(n!=null){let a=n.inputsToSave||[],s=n.outputsToSave||[],i;n.saveAllInputs?(P(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),i=Object.keys(t).map(l=>t[l])):i=a.map(l=>t[l]);let o=r.filter((l,u)=>s[u]);return i.concat(o)}return[]}makeTensor(e,t,r,n){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");r=r||"float32",n=n||this.backend;let a=e;r==="string"&&Ts(e[0])&&(a=e.map(o=>hh(o)));let s=n.write(a,t,r),i=new nt(t,r,s,this.nextTensorId());if(this.trackTensor(i,n),r==="string"){let o=this.state.tensorInfo.get(s),l=Sw(a);this.state.numBytes+=l-o.bytes,o.bytes=l}return i}makeTensorFromDataId(e,t,r,n){r=r||"float32";let a=new nt(t,r,e,this.nextTensorId());return this.trackTensor(a,n),a}makeVariable(e,t=!0,r,n){r=r||this.nextVariableId().toString(),n!=null&&n!==e.dtype&&(e=e.cast(n));let a=new Op(e,t,r,this.nextTensorId());if(this.state.registeredVariables[a.name]!=null)throw new Error(`Variable with name ${a.name} was already registered`);return this.state.registeredVariables[a.name]=a,this.incRef(a,this.backend),a}trackTensor(e,t){this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++;let r=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(r=e.size*ly(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 Op||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*ly(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(n=>n.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-r;for(let n of this.state.activeProfile.kernels)n.kernelTimeMs=await n.kernelTimeMs,n.extraInfo=await n.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,r,n,a,s){let i={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:r,saved:a},o=uy(e);o!=null&&(n=o.gradFunc),n!=null&&(i.gradient=l=>(l=l.map((u,d)=>{if(u==null){let h=r[d],p=qf(h.size,h.dtype);return this.makeTensor(p,h.shape,h.dtype)}return u}),n(l.length>1?l:l[0],a,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=m2(e),r=new Set(t.map(a=>a.id));for(let a=0;a<this.state.activeScope.track.length;a++){let s=this.state.activeScope.track[a];!s.kept&&!r.has(s.id)&&s.dispose()}let n=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach(a=>{!a.kept&&a.scopeId===n.id&&this.track(a)})}gradients(e,t,r,n=!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 a=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));P(a instanceof nt,()=>"The result y returned by f() must be a tensor.");let s=ZR(this.state.activeTape,t,a);if(!n&&s.length===0&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",()=>{let i={};i[a.id]=r==null?lM(a.shape):r,YR(i,s,l=>this.tidy(l),uM);let o=t.map(l=>i[l.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(l=>{for(let u of l.saved)u.dispose()}),this.state.activeTape=null),{value:a,grads:o}})}customGrad(e){return P(Ms(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{P(t.every(i=>i instanceof nt),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let r,n={};t.forEach((i,o)=>{n[o]=i});let a=(i,o)=>(r=e(...t,o),P(r.value instanceof nt,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),P(Ms(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),u=Array.isArray(l)?l:[l];P(u.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),P(u.every(h=>h instanceof nt),()=>"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 d={};return u.forEach((h,p)=>{d[p]=()=>h}),d};return this.runKernelFunc({forwardFunc:a,backwardsFunc:s,inputs:n})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}readToGPU(e,t){return this.state.tensorInfo.get(e).backend.readToGPU(e,t)}async time(e){let t=zp(),r=await this.backend.time(e);return r.wallMs=zp()-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 _3;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}},g2=py;g2.nextTensorId=0;g2.nextVariableId=0;function lM(e){let t=d2(Tt(e),"float32");return B.makeTensor(t,e,"float32")}function Gw(){let e=Rw();if(e._tfengine==null){let t=new Ew(e);e._tfengine=new g2(t)}return FR(e._tfengine.ENV),tM(()=>e._tfengine),e._tfengine}var B=Gw();function uM(e,t){let r={a:e,b:t};return B.runKernel(Ja,r)}var fh={};Le(fh,{isBrowser:()=>jw,isMobile:()=>hM,mockIsMobile:()=>pM});function dM(){return typeof navigator!="undefined"&&navigator!=null}var hy;function pM(e){hy=e}function hM(e){if(hy!==void 0)return hy;if(e||dM()){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 jw(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var Un=Y();Un.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.")});Un.registerFlag("IS_BROWSER",()=>jw());Un.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");Un.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Un.registerFlag("PROD",()=>!1);Un.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Un.getBool("DEBUG"));Un.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Un.registerFlag("IS_TEST",()=>!1);Un.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);Un.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);Un.registerFlag("ENGINE_COMPILE_ONLY",()=>!1);function Ma(e,t){let r=e;if(Sr(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];let n=[];for(;Array.isArray(r)||Sr(r)&&t!=="string";)n.push(r.length),r=r[0];return Array.isArray(e)&&Y().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&Hw(e,n,[]),n}function Hw(e,t,r){if(r=r||[],!Array.isArray(e)&&!Sr(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 n=t.slice(1);for(let a=0;a<e.length;++a)Hw(e[a],n,r.concat(a))}function z3(e,t,r,n){if(e!=="string_or_numeric"){if(e==null)throw new Error("Expected dtype cannot be null.");if(e!=="numeric"&&e!==t||e==="numeric"&&t==="string")throw new Error(`Argument '${r}' passed to '${n}' must be ${e} tensor, but got ${t} tensor`)}}function F(e,t,r,n="numeric"){if(e instanceof nt)return z3(n,e.dtype,t,r),e;let a=Hf(e);if(a!=="string"&&["bool","int32","float32"].indexOf(n)>=0&&(a=n),z3(n,a,t,r),e==null||!Sr(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=Ma(e,a);!Sr(e)&&!Array.isArray(e)&&(e=[e]);let i=a!=="string"?xm(e,a):Eo(e,[],!0);return B.makeTensor(i,s,a)}function Dp(e,t,r,n="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${r} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map((a,s)=>F(a,`${t}[${s}]`,r,n))}var qw="__op";function W(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],n=e[r];r.endsWith("_")&&(r=r.substring(0,r.length-1)),r=r+qw;let a=(...s)=>{B.startScope(r);try{let i=n(...s);return h2(i)&&console.error("Cannot return a Promise inside of tidy."),B.endScope(i),i}catch(i){throw B.endScope(null),i}};return Object.defineProperty(a,"name",{value:r,configurable:!0}),a}function cM(e,t){let r=F(e,"real","complex"),n=F(t,"imag","complex");Vr(r.shape,n.shape,`real and imag shapes, ${r.shape} and ${n.shape}, must match in call to tf.complex().`);let a={real:r,imag:n};return B.runKernel(Xp,a)}var _s=W({complex_:cM});function Vi(e,t,r,n){if(n==null&&(n=Hf(e)),n==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!Sr(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){p2(t);let a=Tt(t),s=Tt(r);P(a===s,()=>`Based on the provided shape, [${t}], the tensor should have ${a} 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!Sr(e)&&!Array.isArray(e)&&(e=[e]),t=t||r,e=n!=="string"?xm(e,n):Eo(e,[],!0),B.makeTensor(e,t,n)}function ct(e,t,r){let n=Ma(e,r);return Vi(e,t,n,r)}var cy={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},xf=4;async function fM(e,t){let r=[],n=[],a=Array.isArray(e)?e.map(i=>i.name):Object.keys(e);for(let i=0;i<a.length;++i){let o=a[i],l=Array.isArray(e)?e[i].tensor:e[o];if(l.dtype!=="float32"&&l.dtype!=="int32"&&l.dtype!=="bool"&&l.dtype!=="string"&&l.dtype!=="complex64")throw new Error(`Unsupported dtype in weight '${o}': ${l.dtype}`);let u={name:o,shape:l.shape,dtype:l.dtype};if(l.dtype==="string"){let d=new Promise(async h=>{let p=await l.bytes(),c=p.reduce((g,y)=>g+y.length,0)+xf*p.length,f=new Uint8Array(c),m=0;for(let g=0;g<p.length;g++){let y=p[g],A=new Uint8Array(new Uint32Array([y.length]).buffer);f.set(A,m),m+=xf,f.set(y,m),m+=y.length}h(f)});n.push(d)}else n.push(l.data());t!=null&&(u.group=t),r.push(u)}let s=await Promise.all(n);return{data:mM(s),specs:r}}function Kw(e,t){let r={},n,a=0;for(let s of t){let i=s.name,o=s.dtype,l=s.shape,u=Tt(l),d;if("quantization"in s){let h=s.quantization;if(h.dtype==="uint8"||h.dtype==="uint16"){if(!("min"in h&&"scale"in h))throw new Error(`Weight ${s.name} with quantization ${h.dtype} doesn't have corresponding metadata min and scale.`)}else if(h.dtype==="float16"){if(o!=="float32")throw new Error(`Weight ${s.name} is quantized with ${h.dtype} which only supports weights of type float32 not ${o}.`)}else throw new Error(`Weight ${s.name} has unknown quantization dtype ${h.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);let p=cy[h.dtype],c=e.slice(a,a+u*p),f=h.dtype==="uint8"?new Uint8Array(c):new Uint16Array(c);if(o==="float32")if(h.dtype==="uint8"||h.dtype==="uint16"){d=new Float32Array(f.length);for(let m=0;m<f.length;m++){let g=f[m];d[m]=g*h.scale+h.min}}else if(h.dtype==="float16")n===void 0&&(n=vM()),d=n(f);else throw new Error(`Unsupported quantization type ${h.dtype} for weight type float32.`);else if(o==="int32"){if(h.dtype!=="uint8"&&h.dtype!=="uint16")throw new Error(`Unsupported quantization type ${h.dtype} for weight type int32.`);d=new Int32Array(f.length);for(let m=0;m<f.length;m++){let g=f[m];d[m]=Math.round(g*h.scale+h.min)}}else throw new Error(`Unsupported dtype in weight '${i}': ${o}`);a+=u*p}else if(o==="string"){let h=Tt(s.shape);d=[];for(let p=0;p<h;p++){let c=new Uint32Array(e.slice(a,a+xf))[0];a+=xf;let f=new Uint8Array(e.slice(a,a+c));d.push(f),a+=c}}else{let h=cy[o],p=e.slice(a,a+u*h);if(o==="float32")d=new Float32Array(p);else if(o==="int32")d=new Int32Array(p);else if(o==="bool")d=new Uint8Array(p);else if(o==="complex64"){d=new Float32Array(p);let c=new Float32Array(d.length/2),f=new Float32Array(d.length/2);for(let y=0;y<c.length;y++)c[y]=d[y*2],f[y]=d[y*2+1];let m=ct(c,l,"float32"),g=ct(f,l,"float32");r[i]=_s(m,g),m.dispose(),g.dispose()}else throw new Error(`Unsupported dtype in weight '${i}': ${o}`);a+=u*h}o!=="complex64"&&(r[i]=ct(d,l,o))}return r}function mM(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 n=new Uint8Array(t),a=0;return r.forEach(s=>{n.set(new Uint8Array(s.buffer),a),a+=s.byteLength}),n.buffer}var y2=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function O3(e){return y2?Buffer.byteLength(e):new Blob([e]).size}function gM(e){if(y2)return Buffer.from(e).toString("base64");let t=new Uint8Array(e),r="";for(let n=0,a=t.length;n<a;n++)r+=String.fromCharCode(t[n]);return btoa(r)}function yM(e){if(y2){let n=Buffer.from(e,"base64");return n.buffer.slice(n.byteOffset,n.byteOffset+n.byteLength)}let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;++n)r.set([t.charCodeAt(n)],n);return r.buffer}function A2(e){if(e.length===1)return e[0];let t=0;e.forEach(a=>{t+=a.byteLength});let r=new Uint8Array(t),n=0;return e.forEach(a=>{r.set(new Uint8Array(a),n),n+=a.byteLength}),r.buffer}function D3(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 Xw(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 x2(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[n,a]=await t(e.weightsManifest);r.weightSpecs=n,r.weightData=a}return e.signature!=null&&(r.signature=e.signature),e.userDefinedMetadata!=null&&(r.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(r.modelInitializer=e.modelInitializer),r}function mh(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:O3(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:O3(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function AM(){let e=r=>{let n=r<<13,a=0;for(;(n&8388608)===0;)a-=8388608,n<<=1;return n&=-8388609,a+=947912704,n|a},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 xM(){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 bM(){let e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function vM(){let e=AM(),t=xM(),r=bM();return n=>{let a=new ArrayBuffer(4*n.length),s=new Uint32Array(a);for(let i=0;i<n.length;i++){let o=n[i],l=e[r[o>>10]+(o&1023)]+t[o>>10];s[i]=l}return new Float32Array(a)}}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 n=[];return(t==="load"?Bt.getInstance().loadRouters:Bt.getInstance().saveRouters).forEach(a=>{let s=a(e,r);s!==null&&n.push(s)}),n}},wM=e=>Bt.registerSaveRouter(e),kM=e=>Bt.registerLoadRouter(e),IM=e=>Bt.getSaveHandlers(e),SM=(e,t)=>Bt.getLoadHandlers(e,t),fy="tensorflowjs",my=1,wo="models_store",Ns="model_info_store";function Zw(){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 gy(e){let t=e.result;t.createObjectStore(wo,{keyPath:"modelPath"}),t.createObjectStore(Ns,{keyPath:"modelPath"})}var Ro=class{constructor(e){if(this.indexedDB=Zw(),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,n)=>{let a=this.indexedDB.open(fy,my);a.onupgradeneeded=()=>gy(a),a.onsuccess=()=>{let s=a.result;if(t==null){let i=s.transaction(wo,"readonly"),o=i.objectStore(wo).get(this.modelPath);o.onsuccess=()=>{if(o.result==null)return s.close(),n(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));r(o.result.modelArtifacts)},o.onerror=l=>(s.close(),n(o.error)),i.oncomplete=()=>s.close()}else{let i=mh(t),o=s.transaction(Ns,"readwrite"),l=o.objectStore(Ns),u=l.put({modelPath:this.modelPath,modelArtifactsInfo:i}),d;u.onsuccess=()=>{d=s.transaction(wo,"readwrite");let h=d.objectStore(wo).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:i});h.onsuccess=()=>r({modelArtifactsInfo:i}),h.onerror=p=>{l=o.objectStore(Ns);let c=l.delete(this.modelPath);c.onsuccess=()=>(s.close(),n(h.error)),c.onerror=f=>(s.close(),n(h.error))}},u.onerror=h=>(s.close(),n(u.error)),o.oncomplete=()=>{d==null?s.close():d.oncomplete=()=>s.close()}}},a.onerror=s=>n(a.error)})}};Ro.URL_SCHEME="indexeddb://";var Yw=e=>Y().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Ro.URL_SCHEME)?TM(e.slice(Ro.URL_SCHEME.length)):null;Bt.registerSaveRouter(Yw);Bt.registerLoadRouter(Yw);function TM(e){return new Ro(e)}function NM(e){return e.startsWith(Ro.URL_SCHEME)?e.slice(Ro.URL_SCHEME.length):e}var CM=class{constructor(){this.indexedDB=Zw()}async listModels(){return new Promise((e,t)=>{let r=this.indexedDB.open(fy,my);r.onupgradeneeded=()=>gy(r),r.onsuccess=()=>{let n=r.result,a=n.transaction(Ns,"readonly"),s=a.objectStore(Ns).getAll();s.onsuccess=()=>{let i={};for(let o of s.result)i[o.modelPath]=o.modelArtifactsInfo;e(i)},s.onerror=i=>(n.close(),t(s.error)),a.oncomplete=()=>n.close()},r.onerror=n=>t(r.error)})}async removeModel(e){return e=NM(e),new Promise((t,r)=>{let n=this.indexedDB.open(fy,my);n.onupgradeneeded=()=>gy(n),n.onsuccess=()=>{let a=n.result,s=a.transaction(Ns,"readwrite"),i=s.objectStore(Ns),o=i.get(e),l;o.onsuccess=()=>{if(o.result==null)return a.close(),r(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{let u=i.delete(e),d=()=>{l=a.transaction(wo,"readwrite");let h=l.objectStore(wo).delete(e);h.onsuccess=()=>t(o.result.modelArtifactsInfo),h.onerror=p=>r(o.error)};u.onsuccess=d,u.onerror=h=>(d(),a.close(),r(o.error))}},o.onerror=u=>(a.close(),r(o.error)),s.oncomplete=()=>{l==null?a.close():l.oncomplete=()=>a.close()}},n.onerror=a=>r(n.error)})}},qa="/",hu="tensorflowjs_models",Jw="info",EM="model_topology",RM="weight_specs",MM="weight_data",FM="model_metadata";function Qw(e){return{info:[hu,e,Jw].join(qa),topology:[hu,e,EM].join(qa),weightSpecs:[hu,e,RM].join(qa),weightData:[hu,e,MM].join(qa),modelMetadata:[hu,e,FM].join(qa)}}function ek(e){for(let t of Object.values(e))window.localStorage.removeItem(t)}function $M(e){let t=e.split(qa);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(qa)}function PM(e){return e.startsWith(Mo.URL_SCHEME)?e.slice(Mo.URL_SCHEME.length):e}var Mo=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=Qw(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),n=mh(e);try{this.LS.setItem(this.keys.info,JSON.stringify(n)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,r),this.LS.setItem(this.keys.weightData,gM(e.weightData));let a={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(a)),{modelArtifactsInfo:n}}catch(a){throw ek(this.keys),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${n.modelTopologyBytes}, weightSpecsBytes=${n.weightSpecsBytes}, weightDataBytes=${n.weightDataBytes}.`)}}}async load(){let e=JSON.parse(this.LS.getItem(this.keys.info));if(e==null)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if(e.modelTopologyType!=="JSON")throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");let t={},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 n=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(n==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=n;let a=this.LS.getItem(this.keys.modelMetadata);if(a!=null){let i=JSON.parse(a);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=yM(s),t}};Mo.URL_SCHEME="localstorage://";var tk=e=>Y().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Mo.URL_SCHEME)?_M(e.slice(Mo.URL_SCHEME.length)):null;Bt.registerSaveRouter(tk);Bt.registerLoadRouter(tk);function _M(e){return new Mo(e)}var zM=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=hu+qa,r=qa+Jw;for(let n=0;n<this.LS.length;++n){let a=this.LS.key(n);if(a.startsWith(t)&&a.endsWith(r)){let s=$M(a);e[s]=JSON.parse(this.LS.getItem(a))}}return e}async removeModel(e){e=PM(e);let t=Qw(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 ek(t),r}},mu="://",Tn=class{constructor(){this.managers={}}static getInstance(){return Tn.instance==null&&(Tn.instance=new Tn),Tn.instance}static registerManager(e,t){P(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(mu)&&(e=e.slice(0,e.indexOf(mu))),P(e.length>0,()=>"scheme must not be an empty string.");let r=Tn.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 tf(e){if(e.indexOf(mu)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Tn.getSchemes().join(",")}`);return{scheme:e.split(mu)[0],path:e.split(mu)[1]}}async function rk(e,t,r=!1){P(e!==t,()=>`Old path and new path are the same: '${e}'`);let n=Bt.getLoadHandlers(e);P(n.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),P(n.length<2,()=>`Copying failed because more than one (${n.length}) load handlers for source URL ${e}.`);let a=n[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 (${n.length}) save handlers for destination URL ${t}.`);let i=s[0],o=tf(e).scheme,l=tf(e).path,u=o===tf(e).scheme,d=await a.load();r&&u&&await Tn.getManager(o).removeModel(l);let h=await i.save(d);return r&&!u&&await Tn.getManager(o).removeModel(l),h.modelArtifactsInfo}async function OM(){let e=Tn.getSchemes(),t={};for(let r of e){let n=await Tn.getManager(r).listModels();for(let a in n){let s=r+mu+a;t[s]=n[a]}}return t}async function DM(e){let t=tf(e);return Tn.getManager(t.scheme).removeModel(t.path)}async function LM(e,t){return rk(e,t,!1)}async function BM(e,t){return rk(e,t,!0)}var WM=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 WM);try{Tn.registerManager(Mo.URL_SCHEME,new zM)}catch(e){}try{Tn.registerManager(Ro.URL_SCHEME,new CM)}catch(e){}}var VM={importFetch:()=>YE()},Y1,UM=class{constructor(){this.util=JE(),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return Y().global.fetch!=null?Y().global.fetch(e,t):(Y1==null&&(Y1=VM.importFetch()),Y1(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 UM);function We(e,t="float32",r){return t=t||"float32",p2(e),new sr(e,t,r)}function GM(e,t){let r=F(e,"x","cast");if(!Iw(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 n={x:r},a={dtype:t};return B.runKernel(Js,n,a)}var me=W({cast_:GM});function jM(e){let t={x:F(e,"x","clone","string_or_numeric")};return B.runKernel(ci,t)}var Br=W({clone_:jM});function nk(e,t=!1){console.log(e.toString(t))}Gw();var HM={buffer:We,cast:me,clone:Br,print:nk};rM(HM);var Tr={};Le(Tr,{browserFiles:()=>QM,browserHTTPRequest:()=>aF,concatenateArrayBuffers:()=>A2,copyModel:()=>LM,decodeWeights:()=>Kw,encodeWeights:()=>fM,fromMemory:()=>iF,getLoadHandlers:()=>SM,getModelArtifactsForJSON:()=>x2,getModelArtifactsInfoForJSON:()=>mh,getSaveHandlers:()=>IM,http:()=>v2,isHTTPScheme:()=>Ay,listModels:()=>OM,loadWeights:()=>eF,moveModel:()=>BM,registerLoadRouter:()=>kM,registerSaveRouter:()=>wM,removeModel:()=>DM,weightsLoaderFactory:()=>sk,withSaveHandler:()=>oF});var qM="model",KM=".json",XM=".weights.bin";function L3(e){return new Promise(t=>setTimeout(t)).then(e)}var yy=class{constructor(e){if(!Y().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(yy.URL_SCHEME)&&(e=e.slice(yy.URL_SCHEME.length)),(e==null||e.length===0)&&(e=qM),this.modelJsonFileName=e+KM,this.weightDataFileName=e+XM}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}],n=Xw(e,r),a=window.URL.createObjectURL(new Blob([JSON.stringify(n)],{type:"application/json"})),s=this.modelJsonAnchor==null?document.createElement("a"):this.modelJsonAnchor;if(s.download=this.modelJsonFileName,s.href=a,await L3(()=>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 L3(()=>i.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:mh(e)}}}},bf=yy;bf.URL_SCHEME="downloads://";var ZM=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=n=>{let a=JSON.parse(n.target.result),s=a.modelTopology;if(s==null){t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));return}if(a.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=x2(a,o=>this.loadWeights(o));e(i)},r.onerror=n=>t(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),r.readAsText(this.jsonFile)})}loadWeights(e){let t=[],r=[];for(let s of e)t.push(...s.weights),r.push(...s.paths);let n=this.checkManifestAndWeightFiles(e),a=r.map(s=>this.loadWeightsFile(s,n[s]));return Promise.all(a).then(s=>[t,A2(s)])}loadWeightsFile(e,t){return new Promise((r,n)=>{let a=new FileReader;a.onload=s=>{let i=s.target.result;r(i)},a.onerror=s=>n(`Failed to weights data from file of path '${e}'.`),a.readAsArrayBuffer(t)})}checkManifestAndWeightFiles(e){let t=[],r=this.weightsFiles.map(a=>D3(a.name)),n={};for(let a of e)a.paths.forEach(s=>{let i=D3(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.`);n[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 n}},YM=e=>Y().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(bf.URL_SCHEME)?JM(e.slice(bf.URL_SCHEME.length)):null;Bt.registerSaveRouter(YM);function JM(e="model"){return new bf(e)}function QM(e){return new ZM(e)}function B3(e,t,r,n){i(e),r=r==null?0:r,n=n==null?1:n,o(r,n);let a=0,s=l=>(l.then(u=>{let d=r+ ++a/e.length*(n-r);return t(d),u}),l);function i(l){P(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function o(l,u){P(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),P(u>=0&&u<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${u}`),P(u>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${u}`)}return Promise.all(e.map(s))}async function ak(e,t){t==null&&(t={});let r=t.fetchFunc==null?Y().platform.fetch:t.fetchFunc,n=e.map(u=>r(u,t.requestInit,{isBinary:!0})),a=0,s=.5,i=(t.onProgress==null?await Promise.all(n):await B3(n,t.onProgress,a,s)).map(u=>u.arrayBuffer()),o=.5,l=1;return t.onProgress==null?await Promise.all(i):await B3(i,t.onProgress,o,l)}async function eF(e,t="",r,n){return sk(a=>ak(a,{requestInit:n}))(e,t,r)}function sk(e){return async(t,r="",n)=>{let a=t.map(()=>!1),s={},i=n!=null?n.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=cy[y]*Tt(g.shape),x=()=>{a[f]=!0,s[f]==null&&(s[f]=[]),s[f].push({manifestEntry:g,groupOffset:m,sizeBytes:A})};n!=null?n.forEach((b,v)=>{b===g.name&&(x(),i[v]=!0)}):x(),o.push(g.name),m+=A})}),!i.every(c=>c)){let c=n.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=a.reduce((c,f,m)=>(f&&c.push(m),c),[]),u=[];l.forEach(c=>{t[c].paths.forEach(f=>{let m=r+(r.endsWith("/")?"":"/")+f;u.push(m)})});let d=await e(u),h={},p=0;return l.forEach(c=>{let f=t[c].paths.length,m=0;for(let x=0;x<f;x++)m+=d[p+x].byteLength;let g=new ArrayBuffer(m),y=new Uint8Array(g),A=0;for(let x=0;x<f;x++){let b=new Uint8Array(d[p+x]);y.set(b,A),A+=b.byteLength}s[c].forEach(x=>{let b=g.slice(x.groupOffset,x.groupOffset+x.sizeBytes),v=Kw(b,[x.manifestEntry]);for(let S in v)h[S]=v[S]}),p+=f}),h}}var tF="application/octet-stream",rF="application/json",b2=class{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(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}],n=Xw(e,r);t.body.append("model.json",new Blob([JSON.stringify(n)],{type:rF}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:tF}),"model.weights.bin");let a=await this.fetch(this.path,t);if(a.ok)return{modelArtifactsInfo:mh(e),responses:[a]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${a.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(a){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,n=t.weightsManifest;if(r==null&&n==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return x2(t,a=>this.loadWeights(a))}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[r,n]=nF(t),a=this.weightPathPrefix||r,s=[];for(let u of e)s.push(...u.weights);let i=[],o=[];for(let u of e)for(let d of u.paths)this.weightUrlConverter!=null?o.push(this.weightUrlConverter(d)):i.push(a+d+n);this.weightUrlConverter&&i.push(...await Promise.all(o));let l=await ak(i,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[s,A2(l)]}};b2.URL_SCHEME_REGEX=/^https?:\/\//;function nF(e){let t=e.lastIndexOf("/"),r=e.lastIndexOf("?"),n=e.substring(0,t),a=r>t?e.substring(r):"";return[n+"/",a]}function Ay(e){return e.match(b2.URL_SCHEME_REGEX)!=null}var ik=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let r=!0;if(Array.isArray(e)?r=e.every(n=>Ay(n)):r=Ay(e),r)return v2(e,t)}return null};Bt.registerSaveRouter(ik);Bt.registerLoadRouter(ik);function v2(e,t){return new b2(e,t)}function aF(e,t){return v2(e,t)}var J1=class{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}},sF=class{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}};function iF(e,t,r,n){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new J1(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 J1({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 J1({modelTopology:e,weightSpecs:t,weightData:r,trainingConfig:n}))}function oF(e){return new sF(e)}var ok={};Le(ok,{confusionMatrix:()=>hF});function lF(e,t,r=!1,n=!1){let a=F(e,"a","matMul"),s=F(t,"b","matMul");[a,s]=Dt(a,s);let i={a,b:s},o={transposeA:r,transposeB:n};return B.runKernel(Ys,i,o)}var Je=W({matMul_:lF});function uF(e,t,r=1,n=0){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);let a={indices:F(e,"indices","oneHot","int32")},s={depth:t,onValue:r,offValue:n};return B.runKernel(ul,a,s)}var Lp=W({oneHot_:uF});function dF(e,t){let r=F(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 n={x:r},a={perm:t};return B.runKernel(Bi,n,a)}var tt=W({transpose_:dF});function pF(e,t,r){let n=F(e,"labels","confusionMatrix"),a=F(t,"predictions","confusionMatrix");P(r==null||r>0&&Number.isInteger(r),()=>`If provided, numClasses must be a positive integer, but got ${r}`),P(n.rank===1,()=>`Expected the rank of labels to be 1, but got ${n.rank}`),P(a.rank===1,()=>`Expected the rank of predictions to be 1, but got ${a.rank}`),P(n.shape[0]===a.shape[0],()=>`Mismatch in the number of examples: ${n.shape[0]} vs. ${a.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=Lp(me(n,"int32"),r),i=Lp(me(a,"int32"),r),o=tt(s),l=Je(o,i);return me(l,"int32")}var hF=W({confusionMatrix_:pF}),Nl={};Le(Nl,{assertAndGetBroadcastShape:()=>bt,getBroadcastDims:()=>lk,getReductionAxes:()=>Zt});function lk(e,t){let r=e.length,n=[];for(let a=0;a<r;a++){let s=r-1-a,i=e[s]||1;(t[t.length-1-a]||1)>1&&i===1&&n.unshift(s)}return n}function Zt(e,t){let r=[];for(let n=0;n<t.length;n++){let a=e[e.length-n-1],s=t.length-n-1,i=t[s];(a==null||a===1&&i>1)&&r.unshift(s)}return r}function bt(e,t){let r=[],n=Math.max(e.length,t.length);for(let a=0;a<n;a++){let s=e[e.length-a-1];s==null&&(s=1);let i=t[t.length-a-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 _n={};Le(_n,{fromPixels:()=>xF,fromPixelsAsync:()=>yF,toPixels:()=>AF});function uk(e,t,r){if(Wo(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let n=Ma(e,r);if(n.length!==3&&n.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Vi(e,t,n,r)}var co;function dk(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,n=!1,a=!1,s=!1,i=!1,o=!1;if(e.data instanceof Uint8Array)r=!0;else if(typeof ImageData!="undefined"&&e instanceof ImageData)n=!0;else if(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)a=!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(a&&a&&e.readyState<2)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.");if(yf(Pp,B.backendName)!=null){let p={pixels:e},c={numChannels:t};return B.runKernel(Pp,p,c)}let[l,u]=a?[e.videoWidth,e.videoHeight]:[e.width,e.height],d;if(i)d=e.getContext("2d").getImageData(0,0,l,u).data;else if(n||r)d=e.data;else if(s||a||o){if(co==null)if(typeof document=="undefined")if(typeof OffscreenCanvas!="undefined"&&typeof OffscreenCanvasRenderingContext2D!="undefined")co=new OffscreenCanvas(1,1).getContext("2d");else throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");else co=document.createElement("canvas").getContext("2d");co.canvas.width=l,co.canvas.height=u,co.drawImage(e,0,0,l,u),d=co.getImageData(0,0,l,u).data}let h;if(t===4)h=new Int32Array(d);else{let p=l*u;h=new Int32Array(p*t);for(let c=0;c<p;c++)for(let f=0;f<t;++f)h[c*t+f]=d[c*4+f]}return uk(h,[u,l,t],"int32")}function cF(e){return e!=null&&e.data instanceof Uint8Array}function fF(){return typeof window!="undefined"&&typeof ImageBitmap!="undefined"&&window.hasOwnProperty("createImageBitmap")}function mF(e){return e!=null&&e.width!==0&&e.height!==0}function gF(e){return fF()&&!(e instanceof ImageBitmap)&&mF(e)&&!cF(e)}async function yF(e,t=3){let r=null;if(Y().getBool("WRAP_TO_IMAGEBITMAP")&&gF(e)){let n;try{n=await createImageBitmap(e,{premultiplyAlpha:"none"})}catch(a){n=null}n!=null&&n.width===e.width&&n.height===e.height?r=n:r=e}else r=e;return dk(r,t)}async function AF(e,t){let r=F(e,"img","toPixels");if(!(e instanceof nt)){let u=r;r=me(u,"int32"),u.dispose()}if(r.rank!==2&&r.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${r.rank}.`);let[n,a]=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(a*n*4);for(let u=0;u<n*a;++u){let d=[0,0,0,255];for(let p=0;p<s;p++){let c=i[u*s+p];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?(d[0]=c*o,d[1]=c*o,d[2]=c*o):d[p]=c*o}let h=u*4;l[h+0]=Math.round(d[0]),l[h+1]=Math.round(d[1]),l[h+2]=Math.round(d[2]),l[h+3]=Math.round(d[3])}if(t!=null){t.width=a,t.height=n;let u=t.getContext("2d"),d=new ImageData(l,a,n);u.putImageData(d,0,0)}return r!==e&&r.dispose(),l}var xF=W({fromPixels_:dk}),w2={};Le(w2,{prepareAndValidate:()=>pk});function pk(e,t){let r=e.shape.length,n=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(n<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${n}.`);if(t.dtype!=="int32")throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[n-1]>r)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[n-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 a=t.shape,s=a[a.length-1],i=1;for(let h=0;h<a.length-1;++h)i*=a[h];let o=e.shape,l=a.slice();l.pop();let u=1;for(let h=s;h<r;++h)u*=o[h],l.push(o[h]);let d=[...Pu(e.shape).map(h=>h/u),1].slice(0,s);return[l,i,u,d]}var k2={};Le(k2,{calculateShapes:()=>hk,validateInput:()=>S2,validateUpdateShape:()=>I2});function I2(e,t,r){let n=t.rank>1?t.shape[t.rank-1]:1,a=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: ${n}, and batchDim: ${a}.`;if(r.rank<a)throw new Error(s+` update.rank < ${a}. `);if(e.length<n+(r.rank-a))throw new Error(s+` Output shape length < ${n+(r.rank-a)}`);if(r.rank!==a+e.length-n)throw new Error(s+` update.rank != ${a+e.length-n}`);for(let i=0;i<a;++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-a;++i)if(r.shape[i+a]!==e[i+n])throw new Error(s+` updates.shape[${i+a}] (${r.shape[i+a]}) != shape[${i+a}] (${e[i+a]})`)}function S2(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}`)}I2(r,t,e)}function hk(e,t,r){let n=t.shape.length,a=n>1?t.shape[n-1]:1,s=r.length,i=1;for(let h=a;h<s;++h)i*=r[h];let o=a<1?1:a,l=Tt(t.shape)/o,u=[...Pu(r.slice(0,a)),1],d=Tt(r);return{sliceRank:a,numUpdates:l,sliceSize:i,strides:u,outputSize:d}}var zt={};Le(zt,{assertParamsValid:()=>vF,computeFlatOffset:()=>TF,computeOutShape:()=>kF,getNormalizedAxes:()=>IF,isSliceContinous:()=>SF,maskToAxes:()=>wF,parseSliceParams:()=>vk,sliceInfo:()=>NF,startForAxis:()=>xk,startIndicesWithElidedDims:()=>gk,stopForAxis:()=>bk,stopIndicesWithElidedDims:()=>yk,stridesForAxis:()=>Ak,stridesWithElidedDims:()=>ck});var xy=-2,bF=-1;function vF(e,t,r){let n=e.shape.length;P(n===t.length,()=>`Error in slice${n}D: Length of begin ${t} must match the rank of the array (${n}).`),P(n===r.length,()=>`Error in slice${n}D: Length of size ${r} must match the rank of the array (${n}).`);for(let a=0;a<n;++a)P(t[a]+r[a]<=e.shape[a],()=>`Error in slice${n}D: begin[${a}] + size[${a}] (${t[a]+r[a]}) would overflow input.shape[${a}] (${e.shape[a]})`)}function wF(e){let t=[],r=0;for(;e>0;)e&1&&t.push(r),e/=2,r++;return t}function kF(e,t,r){let n=[];for(let a=0;a<e.length;a++)n[a]=Math.ceil((t[a]-e[a])/r[a]);return n}function ck(e,t,r,n){let a=[...e];for(let s=a.length;s<n.length;s++)a.push(1);for(let s=0;s<r;s++)s===0?a[t]=1:(a.splice(t,0,1),a.pop());return a}function fk(e,t,r){return r<=e?r:r-(t-1)}function mk(e,t){let r=[];for(let n=0;n<e;n++)r.push(t+n);return r}function IF(e,t,r,n,a,s,i,o,l){let u=e.length,d=new Array(u),h=new Array(u),p=new Array(u);if(t.length&&r>0){let c=t[0],f=r+1;d=gk(i,c,f,n,e),h=yk(o,c,f,a,e),p=ck(s,c,f,e)}else for(let c=0;c<u;c++)d[c]=xk(i,n,s,e,c,l),h[c]=bk(o,a,s,e,c,l),p[c]=Ak(s,c,l);return{begin:d,end:h,strides:p}}function gk(e,t,r,n,a){let s=[...a],i=mk(r,t);for(let o=0;o<s.length;o++)if(i.indexOf(o)>-1)s[o]=0;else{let l=fk(t,r,o),u=n[l];e&1<<l&&(u=0),s[o]=u}return s}function yk(e,t,r,n,a){let s=[...a],i=mk(r,t);for(let o=0;o<s.length;o++)if(i.indexOf(o)>-1)s[o]=Number.MAX_SAFE_INTEGER;else{let l=fk(t,r,o),u=n[l];e&1<<l&&(u=Number.MAX_SAFE_INTEGER),s[o]=u}for(let o=0;o<s.length;o++){let l=a[o];s[o]<0&&(s[o]+=l),s[o]=$p(0,s[o],a[o])}return s}function Ak(e,t,r){let n=e[t];return(r&1<<t||n==null)&&(n=1),n}function xk(e,t,r,n,a,s){let i=t[a],o=r[a]||1;(e&1<<a||s&1<<a||i==null)&&(o>0?i=Number.MIN_SAFE_INTEGER:i=Number.MAX_SAFE_INTEGER);let l=n[a];return i<0&&(i+=l),i=$p(0,i,l-1),i}function bk(e,t,r,n,a,s){let i=t[a],o=r[a]||1;(e&1<<a||s&1<<a||i==null)&&(o>0?i=Number.MAX_SAFE_INTEGER:i=Number.MIN_SAFE_INTEGER);let l=n[a];return i<0&&(i+=l),o>0?i=$p(0,i,l):i=$p(-1,i,l-1),i}function SF(e,t,r){let n=r.length;for(let a=0;a<r.length;a++)if(r[a]>1){n=a;break}for(let a=n+1;a<r.length;a++)if(t[a]>0||r[a]!==e[a])return!1;return!0}function TF(e,t){let r=e.length>0?e[e.length-1]:1;for(let n=0;n<e.length-1;n++)r+=e[n]*t[n];return r}function vk(e,t,r){let n,a=e.shape.length;typeof t=="number"?n=[t,...new Array(a-1).fill(0)]:t.length<a?n=t.concat(new Array(a-t.length).fill(0)):n=t.slice(),n.forEach(i=>{P(i!==-1,()=>"slice() does not support negative begin indexing.")});let s;return r==null?s=new Array(a).fill(-1):typeof r=="number"?s=[r,...new Array(a-1).fill(-1)]:r.length<a?s=r.concat(new Array(a-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]-n[o])),[n,s]}function NF(e,t,r,n,a,s,i,o,l){let u;if(n==null?(u=new Array(t.length),u.fill(1)):u=n,i!=null&&(i&i-1)!==0)throw new Error("Multiple ellipses in slice is not allowed.");let d=!1,h={dims:u.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:r.slice(),strides:u.slice(),beginMask:a,endMask:s,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};for(let A=0;A<h.dims;A++)d&&(1<<A&o)!==0&&h.numAddAxisAfterEllipsis++,1<<A&i&&(d=!0);d||(h.ellipsisMask|=1<<h.dims,h.dims++);let p={dims:e.length,beginMask:0,endMask:0,beginValid:!1,endValid:!1};CF(h,p);let c=!0,f=!0,m=!0,g=[],y=[];for(let A=0;A<e.length;++A){if(p.strides[A]===0)throw Error(`strides[${A}] must be non-zero`);let x=!!(p.shrinkAxisMask&1<<A),b=e[A];if(b===-1){g.push(x?1:-1);continue}let v=[p.beginMask&1<<A,p.endMask&1<<A],S=[p.strides[A]>0?0:-1,p.strides[A]>0?b:b-1];if(x&&p.strides[A]<=0)throw Error("only stride 1 allowed on non-range indexing.");m=m&&p.strides[A]===1;let T=!!(p.beginMask&1<<A&&p.endMask&1<<A);if(p.beginValid&&p.endValid){if(x){let M=p.begin[A]<0?b+p.begin[A]:p.begin[A];if(p.begin[A]=M,p.end[A]=p.begin[A]+1,M<0||M>=b)throw Error(`slice index ${p.begin[A]} of dimension ${A} out of bounds.`)}else p.begin[A]=W3(p.begin[A],0,p.strides[A],b,v,S),p.end[A]=W3(p.end[A],1,p.strides[A],b,v,S);let _=p.strides[A]===1&&p.begin[A]===0&&p.end[A]===b;c=c&&_,f=f&&(A===0&&p.strides[A]===1||_)}else c=c&&p.strides[A]===1&&T,f=f&&(A===0&&p.strides[A]===1||T);let E,R=!1;if(p.beginValid&&p.endValid?(E=p.end[A]-p.begin[A],R=!0):x?(E=1,R=!0):T&&b>=0&&(p.strides[A]<0?E=-b:E=b,R=!0),R){let _;E===0||E<0!=p.strides[A]<0?_=0:_=Math.trunc(E/p.strides[A])+(E%p.strides[A]!==0?1:0),g.push(_)}else g.push(-1)}for(let A=0;A<p.finalShapeGatherIndices.length;++A){let x=p.finalShapeGatherIndices[A];x>=0?y.push(g[x]):x===xy&&y.push(1)}return{finalShapeSparse:y.filter((A,x)=>p.finalShapeGatherIndices[x]!==xy),finalShape:y,isIdentity:c,sliceDim0:f,isSimpleSlice:m,begin:p.begin,end:p.end,strides:p.strides}}function CF(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 n=0;n<e.dims;n++)if(1<<n&e.ellipsisMask){let a=Math.min(t.dims-(e.dims-n)+1+e.numAddAxisAfterEllipsis,t.dims);for(;r<a;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]=n}else if(1<<n&e.newAxisMask)t.finalShapeGatherIndices.push(xy),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[n]),e.end!=null&&(t.end[r]=e.end[n]),t.strides[r]=e.strides[n],e.beginMask&1<<n&&(t.beginMask|=1<<r),e.endMask&1<<n&&(t.endMask|=1<<r),e.shrinkAxisMask&1<<n?(t.finalShapeGatherIndices.push(bF),t.finalShapeGatherIndicesSparse.push(-1),t.shrinkAxisMask|=1<<r):(t.finalShapeGatherIndices.push(r),t.finalShapeGatherIndicesSparse.push(n)),t.inputShapeGatherIndicesSparse[r]=n,r++}}function W3(e,t,r,n,a,s){if(a[t])return r>0?s[t]:s[t+1&1];{let i=e<0?n+e:e;return i<s[0]?s[0]:i>s[1]?s[1]:i}}var ue={};Le(ue,{Serializable:()=>wk,SerializationMap:()=>xo,registerClass:()=>Ui});var wk=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},xo=class{constructor(){this.classNameMap={}}static getMap(){return xo.instance==null&&(xo.instance=new xo),xo.instance}static register(e){xo.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function Ui(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."),xo.register(e)}var kk={};Le(kk,{TEST_EPSILON_FLOAT16:()=>Ik,encodeStrings:()=>Sk,expectArrayBuffersEqual:()=>_F,expectArraysClose:()=>RF,expectArraysEqual:()=>FF,expectNumbersClose:()=>$F,expectPromiseToFail:()=>MF,expectValuesInRange:()=>PF,testEpsilon:()=>T2});var EF=.001,Ik=.1;function RF(e,t,r){return r==null&&(r=T2()),by(e,t,(n,a)=>N2(n,a,r))}function T2(){return B.backend.floatPrecision()===32?EF:Ik}function by(e,t,r){let n=!0;if((Sr(e)||Sr(t))&&(n=!1),Sr(e)&&Sr(t)&&(n=!0),n){let i=e.constructor.name,o=t.constructor.name;if(i!==o)throw new Error(`Arrays are of different type. Actual: ${i}. Expected: ${o}`)}if(Array.isArray(e)&&Array.isArray(t)){let i=Ma(e),o=Ma(t);if(!qs(i,o))throw new Error(`Arrays have different shapes. Actual: [${i}]. Expected: [${o}]`)}let a=Sr(e)?e:Eo(e),s=Sr(t)?t:Eo(t);if(a.length!==s.length)throw new Error(`Arrays have different lengths actual: ${a.length} vs expected: ${s.length}.
|
|
Actual: ${a}.
|
|
Expected: ${s}.`);for(let i=0;i<s.length;++i){let o=a[i],l=s[i];if(!r(o,l))throw new Error(`Arrays differ: actual[${i}] = ${o}, expected[${i}] = ${l}.
|
|
Actual: ${a}.
|
|
Expected: ${s}.`)}}function MF(e,t){e().then(()=>t.fail(),()=>t())}function FF(e,t){let r=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Ts(e)||Ts(e[0])||Ts(t)||Ts(t[0])?by(e,r,(n,a)=>n==a):by(e,t,(n,a)=>N2(n,a,0))}function $F(e,t,r){if(r==null&&(r=T2()),!N2(e,t,r))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function N2(e,t,r){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>r)}function PF(e,t,r){for(let n=0;n<e.length;n++)if(e[n]<t||e[n]>r)throw new Error(`Value out of range:${e[n]} low: ${t}, high: ${r}`)}function _F(e,t){let r=new Float32Array(e),n=new Float32Array(t);if(r.length!==n.length)throw new Error(`Expected ArrayBuffer to be of length ${n.length}, but it was ${r.length}`);for(let a=0;a<n.length;a++)if(r[a]!==n[a])throw new Error(`Expected ArrayBuffer value at ${a} to be ${n[a]} but got ${r[a]} instead`)}function Sk(e){for(let t=0;t<e.length;t++){let r=e[t];Array.isArray(r)?Sk(r):e[t]=hh(r)}return e}var C2="0.0.0";function E2(){Y().set("PROD",!0)}function zF(){Y().set("DEBUG",!0)}function OF(){Y().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function R2(e){Y().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}nM(R2);function DF(){B.disposeVariables()}function nr(){return B}function vf(){return B.memory()}function LF(e){return B.profile(e)}function K(e,t){return B.tidy(e,t)}function re(e){m2(e).forEach(t=>t.dispose())}function fr(e){return B.keep(e)}function BF(e){return B.time(e)}function M2(e){return B.setBackend(e)}function ld(){return B.ready()}function Ur(){return B.backendName}function WF(e){B.removeBackend(e)}function F2(e){return B.findBackend(e)}function VF(e){return B.findBackendFactory(e)}function Cl(e,t,r=1){return B.registerBackend(e,t,r)}function zn(){return B.backend}function UF(e,t){Y().setPlatform(e,t)}function GF(e,t){let r=F(e,"a","add"),n=F(t,"b","add");[r,n]=Dt(r,n);let a={a:r,b:n};return B.runKernel(Ja,a)}var le=W({add_:GF});function jF(e,t){let r=F(e,"a","floorDiv"),n=F(t,"b","floorDiv");[r,n]=Dt(r,n);let a={a:r,b:n};return B.runKernel(di,a)}var gh=W({floorDiv_:jF});function HF(e,t){let r=F(e,"a","div"),n=F(t,"b","div");if([r,n]=Dt(r,n),r.dtype==="int32"&&n.dtype==="int32")return gh(r,n);let a={a:r,b:n},s={};return B.runKernel(ii,a,s)}var pe=W({div_:HF});function qF(e,t){let r=F(e,"a","mul"),n=F(t,"b","mul");[r,n]=Dt(r,n);let a={a:r,b:n};return B.runKernel(ki,a)}var L=W({mul_:qF});function KF(e){let t=F(e,"x","abs");if(t.dtype==="complex64"){let r={x:t};return B.runKernel(Zp,r)}else{let r={x:t};return B.runKernel(Vo,r)}}var rr=W({abs_:KF});function XF(e){let t={x:F(e,"x","acos")};return B.runKernel(_u,t)}var Tk=W({acos_:XF});function ZF(e){let t={x:F(e,"x","acosh")};return B.runKernel(zu,t)}var Nk=W({acosh_:ZF});function YF(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((a,s)=>F(a,`tensors${s}`,"addN")),r=t[0];t.forEach(a=>{if(a.dtype!==r.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(a=>{if(!qs(a.shape,r.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let n=t;return B.runKernel(Ks,n)}var bm=W({addN_:YF});function JF(e,t=null,r=!1){let n={x:F(e,"x","all","bool")},a={axis:t,keepDims:r};return B.runKernel(Ou,n,a)}var $2=W({all_:JF});function QF(e,t=null,r=!1){let n={x:F(e,"x","any","bool")},a={axis:t,keepDims:r};return B.runKernel(Du,n,a)}var wf=W({any_:QF});function e$(e,t=0){let r={x:F(e,"x","argMax")},n={axis:t};return B.runKernel(Xs,r,n)}var Cn=W({argMax_:e$});function t$(e,t=0){let r={x:F(e,"x","argMin")},n={axis:t};return B.runKernel(Lu,r,n)}var Ck=W({argMin_:t$});function r$(e){let t={x:F(e,"x","asin")};return B.runKernel(Bu,t)}var Ek=W({asin_:r$});function n$(e){let t={x:F(e,"x","asinh")};return B.runKernel(Wu,t)}var Rk=W({asinh_:n$});function a$(e){let t={x:F(e,"x","atan")};return B.runKernel(Vu,t)}var Mk=W({atan_:a$});function s$(e,t){let r=F(e,"a","atan2"),n=F(t,"b","atan2");[r,n]=Dt(r,n);let a={a:r,b:n};return B.runKernel(Gu,a)}var Fk=W({atan2_:s$});function i$(e){let t={x:F(e,"x","atanh")};return B.runKernel(Uu,t)}var $k=W({atanh_:i$});function o$(e,t,r,n,a="NHWC",s){let i=e[3],o=[...t,i],l=zk(a);return yh(e,o,r,s,n,null,null,l)}function Pk(e,t,r,n,a,s,i="channelsLast"){let[o,l]=kf(t),u;if(i==="channelsLast")u=[o,l,e[3],e[3]];else if(i==="channelsFirst")u=[o,l,e[1],e[1]];else throw new Error(`Unknown dataFormat ${i}`);return yh(e,u,r,n,a,s,!1,i)}function l$(e,t,r,n,a,s,i="NDHWC"){let[o,l,u]=vy(t),d,h;if(i==="NDHWC")h="channelsLast",d=[o,l,u,e[4],e[4]];else if(i==="NCDHW")h="channelsFirst",d=[o,l,u,e[1],e[1]];else throw new Error(`Unknown dataFormat ${i}`);return _k(e,d,r,n,a,!1,h,s)}function yh(e,t,r,n,a,s,i=!1,o="channelsLast"){let[l,u,d,h]=[-1,-1,-1,-1];if(o==="channelsLast")[l,u,d,h]=e;else if(o==="channelsFirst")[l,h,u,d]=e;else throw new Error(`Unknown dataFormat ${o}`);let[p,c,,f]=t,[m,g]=kf(r),[y,A]=kf(n),x=gu(p,y),b=gu(c,A),{padInfo:v,outHeight:S,outWidth:T}=p$(a,u,d,m,g,x,b,s,o),E=i?f*h:f,R;return o==="channelsFirst"?R=[l,E,S,T]:o==="channelsLast"&&(R=[l,S,T,E]),{batchSize:l,dataFormat:o,inHeight:u,inWidth:d,inChannels:h,outHeight:S,outWidth:T,outChannels:E,padInfo:v,strideHeight:m,strideWidth:g,filterHeight:p,filterWidth:c,effectiveFilterHeight:x,effectiveFilterWidth:b,dilationHeight:y,dilationWidth:A,inShape:e,outShape:R,filterShape:t}}function _k(e,t,r,n,a,s=!1,i="channelsLast",o){let[l,u,d,h,p]=[-1,-1,-1,-1,-1];if(i==="channelsLast")[l,u,d,h,p]=e;else if(i==="channelsFirst")[l,p,u,d,h]=e;else throw new Error(`Unknown dataFormat ${i}`);let[c,f,m,,g]=t,[y,A,x]=vy(r),[b,v,S]=vy(n),T=gu(c,b),E=gu(f,v),R=gu(m,S),{padInfo:_,outDepth:M,outHeight:I,outWidth:z}=h$(a,u,d,h,y,A,x,T,E,R,o),O=s?g*p:g,j;return i==="channelsFirst"?j=[l,O,M,I,z]:i==="channelsLast"&&(j=[l,M,I,z,O]),{batchSize:l,dataFormat:i,inDepth:u,inHeight:d,inWidth:h,inChannels:p,outDepth:M,outHeight:I,outWidth:z,outChannels:O,padInfo:_,strideDepth:y,strideHeight:A,strideWidth:x,filterDepth:c,filterHeight:f,filterWidth:m,effectiveFilterDepth:T,effectiveFilterHeight:E,effectiveFilterWidth:R,dilationDepth:b,dilationHeight:v,dilationWidth:S,inShape:e,outShape:j,filterShape:t}}function u$(e,t,r,n,a){n==null&&(n=P2(e,t,r));let s=e[0],i=e[1],o=So((s-t+2*n)/r+1,a),l=So((i-t+2*n)/r+1,a);return[o,l]}function d$(e,t,r,n,a,s){a==null&&(a=P2(e,t,n));let i=e[0],o=e[1],l=e[2],u=So((i-t+2*a)/n+1,s),d=So((o-t+2*a)/n+1,s),h=So((l-t+2*a)/n+1,s);return[u,d,h,r]}function P2(e,t,r,n=1){let a=gu(t,n);return Math.floor((e[0]*(r-1)-r+a)/2)}function kf(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function vy(e){return typeof e=="number"?[e,e,e]:e}function gu(e,t){return t<=1?e:e+(e-1)*(t-1)}function p$(e,t,r,n,a,s,i,o,l){let u,d,h;if(typeof e=="number"){u={top:e,bottom:e,left:e,right:e,type:e===0?"VALID":"NUMBER"};let p=u$([t,r],s,n,e,o);d=p[0],h=p[1]}else if(e==="same"){d=Math.ceil(t/n),h=Math.ceil(r/a);let p=Math.max(0,(d-1)*n+s-t),c=Math.max(0,(h-1)*a+i-r),f=Math.floor(p/2),m=p-f,g=Math.floor(c/2),y=c-g;u={top:f,bottom:m,left:g,right:y,type:"SAME"}}else if(e==="valid")u={top:0,bottom:0,left:0,right:0,type:"VALID"},d=Math.ceil((t-s+1)/n),h=Math.ceil((r-i+1)/a);else if(typeof e=="object"){let p=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];u={top:p,bottom:c,left:f,right:m,type:p===0&&c===0&&f===0&&m===0?"VALID":"EXPLICIT"},d=So((t-s+p+c)/n+1,o),h=So((r-i+f+m)/a+1,o)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:u,outHeight:d,outWidth:h}}function h$(e,t,r,n,a,s,i,o,l,u,d){let h,p,c,f;if(typeof e=="number"){h={top:e,bottom:e,left:e,right:e,front:e,back:e,type:e===0?"VALID":"NUMBER"};let m=d$([t,r,n,1],o,1,a,e,d);p=m[0],c=m[1],f=m[2]}else if(e==="same"){p=Math.ceil(t/a),c=Math.ceil(r/s),f=Math.ceil(n/i);let m=(p-1)*a+o-t,g=(c-1)*s+l-r,y=(f-1)*i+u-n,A=Math.floor(m/2),x=m-A,b=Math.floor(g/2),v=g-b,S=Math.floor(y/2),T=y-S;h={top:b,bottom:v,left:S,right:T,front:A,back:x,type:"SAME"}}else if(e==="valid")h={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},p=Math.ceil((t-o+1)/a),c=Math.ceil((r-l+1)/s),f=Math.ceil((n-u+1)/i);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:h,outDepth:p,outHeight:c,outWidth:f}}function So(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 zs(e){let[t,r,n]=kf(e);return t===1&&r===1&&n===1}function Pa(e,t){return zs(e)||zs(t)}function zk(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function Gr(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(xu(t),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${r} but got pad ${t}.`);else if(typeof t=="object")t.forEach(n=>{n.forEach(a=>{P(xu(a),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${r} but got pad ${a}.`)})});else throw Error(`Error in ${e}: Unknown padding parameter: ${t}`)}}function c$(e,t){let r={x:F(e,"x","reshape","string_or_numeric")},n={shape:t};return B.runKernel(pl,r,n)}var G=W({reshape_:c$});function f$(e,t,r,n,a){let s=F(e,"x","avgPool","float32"),i=1;P(Pa(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=G(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}.`),Gr("avgPool",n,a);let u={x:o},d={filterSize:t,strides:r,pad:n,dimRoundingMode:a},h=B.runKernel(Zs,u,d);return h=me(h,s.dtype),l?G(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var vm=W({avgPool_:f$});function m$(e,t,r,n,a,s="NDHWC"){let i=F(e,"x","avgPool3d","float32"),o=i,l=!1;i.rank===4&&(l=!0,o=G(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}`),Gr("avgPool3d",n,a);let u={x:o},d={filterSize:t,strides:r,pad:n,dimRoundingMode:a,dataFormat:s},h=B.runKernel(Kp,u,d);return h=me(h,o.dtype),l?G(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var _2=W({avgPool3d_:m$});function g$(e,t=0){P(e.length>=1,()=>"Pass at least one tensor to concat");let r=Dp(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 Br(r[0]);let n=r,a={axis:t};return B.runKernel(Go,n,a)}var kt=W({concat_:g$});function y$(e){let t={x:F(e,"x","sigmoid","float32")};return B.runKernel($i,t)}var Nr=W({sigmoid_:y$});function A$(e,t,r){let n=F(e,"x","slice","string_or_numeric");if(n.rank===0)throw new Error("Slicing scalar is not possible");let a={x:n},s={begin:t,size:r};return B.runKernel(gl,a,s)}var Pe=W({slice_:A$});function x$(e){let t={x:F(e,"x","tanh","float32")};return B.runKernel(Li,t)}var vu=W({tanh_:x$});function b$(e,t,r,n,a,s){let i=F(e,"forgetBias","basicLSTMCell"),o=F(t,"lstmKernel","basicLSTMCell"),l=F(r,"lstmBias","basicLSTMCell"),u=F(n,"data","basicLSTMCell"),d=F(a,"c","basicLSTMCell"),h=F(s,"h","basicLSTMCell"),p=kt([u,h],1),c=Je(p,o),f=le(c,l),m=f.shape[0],g=f.shape[1]/4,y=[m,g],A=Pe(f,[0,0],y),x=Pe(f,[0,g],y),b=Pe(f,[0,g*2],y),v=Pe(f,[0,g*3],y),S=le(L(Nr(A),vu(x)),L(d,Nr(le(i,b)))),T=L(vu(S),Nr(v));return[S,T]}var v$=W({basicLSTMCell_:b$});function w$(e,t,r){let n=F(e,"x","batchToSpaceND"),a=t.reduce((o,l)=>o*l);P(n.rank>=1+t.length,()=>`input rank is ${n.rank} but should be > than blockShape.length ${t.length}`),P(r.length===t.length,()=>`crops.length is ${r.length} but should be equal to blockShape.length ${t.length}`),P(n.shape[0]%a===0,()=>`input tensor batch is ${n.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${a}`);let s={x:n},i={blockShape:t,crops:r};return B.runKernel(Uo,s,i)}var wm=W({batchToSpaceND_:w$});function k$(e){let t;return e.rank===0||e.rank===1?t=G(e,[1,1,1,e.size]):e.rank===2?t=G(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=G(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function I$(e,t,r,n,a,s){s==null&&(s=.001);let i=F(e,"x","batchNorm"),o=F(t,"mean","batchNorm"),l=F(r,"variance","batchNorm"),u;a!=null&&(u=F(a,"scale","batchNorm"));let d;n!=null&&(d=F(n,"offset","batchNorm")),P(o.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),P(d==null||o.rank===d.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),P(u==null||o.rank===u.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let h={x:k$(i),scale:u,offset:d,mean:o,variance:l},p={varianceEpsilon:s},c=B.runKernel(pi,h,p);return G(c,i.shape)}var wu=W({batchNorm_:I$});function S$(e,t,r,n,a,s){let i=F(e,"x","batchNorm"),o=F(t,"mean","batchNorm"),l=F(r,"variance","batchNorm"),u;a!=null&&(u=F(a,"scale","batchNorm"));let d;return n!=null&&(d=F(n,"offset","batchNorm")),P(i.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`),P(o.rank===2||o.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${o.rank}.`),P(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),u!=null&&P(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`),d!=null&&P(d.rank===2||d.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${d.rank}.`),wu(i,o,l,d,u,s)}var Ok=W({batchNorm2d_:S$});function T$(e,t,r,n,a,s){let i=F(e,"x","batchNorm"),o=F(t,"mean","batchNorm"),l=F(r,"variance","batchNorm"),u;a!=null&&(u=F(a,"scale","batchNorm"));let d;return n!=null&&(d=F(n,"offset","batchNorm")),P(i.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`),P(o.rank===3||o.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${o.rank}.`),P(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),u!=null&&P(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`),d!=null&&P(d.rank===3||d.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${d.rank}.`),wu(i,o,l,d,u,s)}var Dk=W({batchNorm3d_:T$});function N$(e,t,r,n,a,s){let i=F(e,"x","batchNorm"),o=F(t,"mean","batchNorm"),l=F(r,"variance","batchNorm"),u;a!=null&&(u=F(a,"scale","batchNorm"));let d;return n!=null&&(d=F(n,"offset","batchNorm")),P(i.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}.`),P(o.rank===4||o.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${o.rank}.`),P(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),u!=null&&P(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`),d!=null&&P(d.rank===4||d.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${d.rank}.`),wu(i,o,l,d,u,s)}var Lk=W({batchNorm4d_:N$});function C$(e,t,r){let n=F(e,"x","bincount"),a=F(t,"weights","bincount");P(n.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${n.dtype}`),P(r>=0,()=>`size must be non-negative, but got ${r}.`),P(a.size===n.size||a.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${n.shape}, weights shape: ${a.shape}.`);let s={x:n,weights:a},i={size:r};return B.runKernel(Zf,s,i)}var z2=W({bincount_:C$});function E$(e,t){let r=F(e,"s0","broadcastArgs","int32"),n=F(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(n.rank!==1)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${n.rank}`);let a={s0:r,s1:n};return B.runKernel(Yf,a)}var Bk=W({broadcastArgs_:E$});function R$(e,t){let r=F(e,"broadcastTo","x"),n=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=G(r,l)}let a=r.shape,s=Array.from(t);for(let l=t.length-1;l>=0;l--)if(a[l]===t[l])s[l]=1;else if(r.shape[l]!==1)throw new Error(`broadcastTo(): [${n}] cannot be broadcast to [${t}].`);if(s.map((l,u)=>l>1?u:-1).filter(l=>l>=0).length===0)return Br(r);let i={x:r},o={reps:s};return B.runKernel(es,i,o)}var Ep=W({broadcastTo_:R$});function M$(e){let t={x:F(e,"x","ceil","float32")};return B.runKernel(Qs,t)}var Wk=W({ceil_:M$});function F$(e,t,r){let n=F(e,"x","clipByValue");P(t<=r,()=>`Error in clip: min (${t}) must be less than or equal to max (${r}).`);let a={x:n},s={clipValueMin:t,clipValueMax:r};return B.runKernel(Qa,a,s)}var cn=W({clipByValue_:F$});function $$(e){return kt(e,0)}var Vk=W({concat1d_:$$});function P$(e,t){return kt(e,t)}var ud=W({concat2d_:P$});function _$(e,t){return kt(e,t)}var Uk=W({concat3d_:_$});function z$(e,t){return kt(e,t)}var Gk=W({concat4d_:z$});function O$(e,t,r,n,a="NHWC",s=[1,1],i){let o=F(e,"x","conv2d","float32"),l=F(t,"filter","conv2d","float32"),u=o,d=!1;o.rank===3&&(d=!0,u=G(o,[1,o.shape[0],o.shape[1],o.shape[2]])),P(u.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`),P(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),Gr("conv2d",n,i);let h=a==="NHWC"?u.shape[3]:u.shape[1];P(h===l.shape[2],()=>`Error in conv2d: depth of input (${h}) must match input depth for filter ${l.shape[2]}.`),P(Pa(r,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${r} and dilations '${s}'`);let p={x:u,filter:l},c={strides:r,pad:n,dataFormat:a,dilations:s,dimRoundingMode:i},f=B.runKernel(ei,p,c);return d?G(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var Os=W({conv2d_:O$});function D$(e,t,r,n,a="NWC",s=1,i){let o=F(e,"x","conv1d"),l=F(t,"filter","conv1d"),u=o,d=!1;o.rank===2&&(d=!0,u=G(o,[1,o.shape[0],o.shape[1]])),P(u.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${u.rank}.`),P(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),Gr("conv1d",n,i),P(u.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`),P(Pa(r,s),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${r} and dilation '${s}'`),P(a==="NWC",()=>`Error in conv1d: got dataFormat of ${a} but only NWC is currently supported.`);let h=G(l,[1,l.shape[0],l.shape[1],l.shape[2]]),p=G(u,[u.shape[0],1,u.shape[1],u.shape[2]]),c=Os(p,h,[1,r],n,"NHWC",[1,s],i);return d?G(c,[c.shape[2],c.shape[3]]):G(c,[c.shape[0],c.shape[2],c.shape[3]])}var O2=W({conv1d_:D$});function L$(e,t,r,n,a,s="NHWC",i){P(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let o=e,l=t,u=!1;t.rank===3&&(u=!0,l=G(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 d=s==="NHWC"?o[3]:o[1],h=s==="NHWC"?l.shape[3]:l.shape[1];P(d===r.shape[2],()=>`Error in conv2dDerInput: depth of input (${d}) must match input depth for filter ${r.shape[2]}.`),P(h===r.shape[3],()=>`Error in conv2dDerInput: depth of output (${h}) must match output depth for filter ${r.shape[3]}.`),Gr("conv2dDerInput",a,i);let p={dy:l,filter:r},c={strides:n,pad:a,dataFormat:s,dimRoundingMode:i,inputShape:o},f=B.runKernel(ti,p,c);return u?G(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var D2=W({conv2DBackpropInput_:L$});function B$(e,t,r,n,a,s){let i=F(e,"x","conv2dTranspose"),o=F(t,"filter","conv2dTranspose");return D2(r,i,o,n,a,"NHWC",s)}var L2=W({conv2dTranspose_:B$});function W$(e,t,r,n,a="NDHWC",s=[1,1,1]){let i=F(e,"x","conv3d"),o=F(t,"filter","conv3d"),l=i,u=!1;i.rank===4&&(u=!0,l=G(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(Pa(r,s),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${r} and dilations '${s}'`),P(a==="NDHWC",()=>`Error in conv3d: got dataFormat of ${a} but only NDHWC is currently supported.`);let d={x:l,filter:o},h={strides:r,pad:n,dataFormat:a,dilations:s},p=B.runKernel(Yp,d,h);return u?G(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var B2=W({conv3d_:W$});function V$(e,t,r,n,a){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=G(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),s=[1,e[0],e[1],e[2],e[3]]);let l=s[4],u=i.shape[4];P(s.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`),P(i.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${i.rank}`),P(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(u===r.shape[4],()=>`Error in conv3dDerInput: depth of output (${u}) must match output depth for filter ${r.shape[4]}.`);let d={dy:i,filter:r},h={pad:a,strides:n,inputShape:s},p=B.runKernel(em,d,h);return o?G(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var jk=W({conv3DBackpropInput_:V$});function U$(e,t,r,n,a){let s=F(e,"x","conv3dTranspose"),i=F(t,"filter","conv3dTranspose");return jk(r,s,i,n,a)}var Hk=W({conv3dTranspose_:U$});function G$(e){let t={x:F(e,"x","cos","float32")};return B.runKernel(ri,t)}var km=W({cos_:G$});function j$(e){let t={x:F(e,"x","cosh","float32")};return B.runKernel(ni,t)}var W2=W({cosh_:j$});function H$(e,t=0,r=!1,n=!1){let a={x:F(e,"x","cumprod")},s={axis:t,exclusive:r,reverse:n};return B.runKernel(jo,a,s)}var If=W({cumprod_:H$});function q$(e,t=0,r=!1,n=!1){let a={x:F(e,"x","cumsum")},s={axis:t,exclusive:r,reverse:n};return B.runKernel(ai,a,s)}var V2=W({cumsum_:q$});function K$(e,t,r,n=!1){let a=F(e,"x","denseBincount"),s=F(t,"weights","denseBincount");P(a.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${a.dtype}`),P(a.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${a.rank}.`),P(r>=0,()=>`size must be non-negative, but got ${r}.`),P(s.size===a.size||s.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${a.shape}, weights shape: ${s.shape}.`);let i={x:a,weights:s},o={size:r,binaryOutput:n};return B.runKernel(tm,i,o)}var qk=W({denseBincount_:K$});function X$(e,t,r="NHWC"){let n=F(e,"x","depthToSpace","float32"),a=r==="NHWC"?n.shape[1]:n.shape[2],s=r==="NHWC"?n.shape[2]:n.shape[3],i=r==="NHWC"?n.shape[3]:n.shape[1];P(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`),P(a*t>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${a} and ${t} for depthToSpace with input shape
|
|
${n.shape}`),P(s*t>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${s} and ${t} for depthToSpace with input shape
|
|
${n.shape}`),P(i%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${i} for depthToSpace with input shape ${n.shape}`);let o={x:n},l={blockSize:t,dataFormat:r};return B.runKernel(qo,o,l)}var Kk=W({depthToSpace_:X$});function Z$(e,t,r,n,a="NHWC",s=[1,1],i){let o=F(e,"x","depthwiseConv2d","float32"),l=F(t,"filter","depthwiseConv2d","float32"),u=o,d=!1;o.rank===3&&(d=!0,u=G(o,[1,o.shape[0],o.shape[1],o.shape[2]])),P(u.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`),P(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),P(u.shape[3]===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${u.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`),Gr("depthwiseConv2d",n,i);let h={x:u,filter:l},p={strides:r,pad:n,dataFormat:a,dilations:s,dimRoundingMode:i},c=B.runKernel(si,h,p);return d?G(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var Ah=W({depthwiseConv2d_:Z$});function Y$(e){let t={x:F(e,"x","diag")};return B.runKernel(am,t)}var J$=W({diag_:Y$});function Q$(e,t,r,n,a=[1,1],s="NHWC"){let i=F(e,"x","dilation2d"),o=F(t,"filter","dilation2d");P(i.rank===3||i.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`),P(o.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${o.rank}.`),P(s==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${s}`);let l=i,u=!1;i.rank===3&&(l=G(i,[1,i.shape[0],i.shape[1],i.shape[2]]),u=!0);let d={x:l,filter:o},h={strides:r,pad:n,dilations:a},p=B.runKernel(Jp,d,h);return u?G(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var Xk=W({dilation2d_:Q$});function eP(e,t){let r=F(e,"a","equal","string_or_numeric"),n=F(t,"b","equal","string_or_numeric");[r,n]=Dt(r,n),bt(r.shape,n.shape);let a={a:r,b:n};return B.runKernel(Ko,a)}var En=W({equal_:eP});function tP(e,t,r){let n=F(t,"a","where"),a=F(r,"b","where"),s=F(e,"condition","where","bool"),i=bt(bt(s.shape,n.shape),a.shape),o=Ep(s,i),l=Ep(n,i),u=Ep(a,i),d={condition:o,t:l,e:u};return B.runKernel(ml,d)}var Wr=W({where_:tP});function rP(e){let t={x:F(e,"x","zerosLike")};return B.runKernel(Sl,t)}var at=W({zerosLike_:rP});function nP(e,t){let r=F(e,"a","div"),n=F(t,"b","div");[r,n]=Dt(r,n);let a=pe(r,n),s=at(a),i=En(n,s);return Wr(i,s,a)}var Zk=W({divNoNan_:nP});function aP(e,t){let r=F(e,"t1","dot"),n=F(t,"t2","dot");P((r.rank===1||r.rank===2)&&(n.rank===1||n.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${r.rank} and ${n.rank}.`);let a=r.rank===1?r.size:r.shape[1],s=n.rank===1?n.size:n.shape[0];if(P(a===s,()=>`Error in dot: inner dimensions of inputs must match, but got ${a} and ${s}.`),r.rank===1&&n.rank===1){let i=G(r,[1,-1]),o=G(n,[-1,1]),l=Je(i,o);return G(l,[])}else if(r.rank===1&&n.rank===2){let i=G(r,[1,-1]),o=G(n,[n.shape[0],n.shape[1]]),l=Je(i,o);return G(l,[l.size])}else if(r.rank===2&&n.rank===1){let i=G(n,[-1,1]),o=Je(r,i);return G(o,[o.size])}else{let i=G(n,[n.shape[0],n.shape[1]]);return Je(r,i)}}var sP=W({dot_:aP});function iP(e,...t){let r=t.map((a,s)=>F(a,`tensors${s}`,"einsum")),n={equation:e};return B.runKernel(Qp,r,n)}var Yk=W({einsum_:iP});function oP(e){let t={x:F(e,"x","elu","float32")};return B.runKernel(oi,t)}var xh=W({elu_:oP});function lP(e){let t=F(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(ju,r)}var Jk=W({erf_:lP});function uP(e){let t={x:F(e,"x","exp")};return B.runKernel(li,t)}var Rn=W({exp_:uP});function dP(e,t=0){let r=F(e,"x","expandDims","string_or_numeric");P(t<=r.rank,()=>"Axis must be <= rank of the tensor");let n={input:r},a={dim:t};return B.runKernel(Xo,n,a)}var qt=W({expandDims_:dP});function pP(e){let t={x:F(e,"x","expm1")};return B.runKernel(Zo,t)}var Qk=W({expm1_:pP});function hP(e,t){let r=F(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 n={x:r},a={reps:t};return B.runKernel(es,n,a)}var Vn=W({tile_:hP});function cP(e,t,r,n="float32"){t==null&&(t=e);let a=We([e,t],n),s=e<=t?e:t;for(let o=0;o<s;++o)a.set(1,o,o);let i=G(a.toTensor(),[e,t]);if(r==null)return i;if(r.length===1)return Vn(qt(i,0),[r[0],1,1]);if(r.length===2)return Vn(qt(qt(i,0),0),[r[0],r[1],1,1]);if(r.length===3)return Vn(qt(qt(qt(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 U2=W({eye_:cP});function dd(e,t,r){let n={shape:e,value:t,dtype:r};return B.runKernel(Hu,{},n)}function fP(e){let t={x:F(e,"x","floor","float32")};return B.runKernel(ui,t)}var bh=W({floor_:fP});function mP(e,t,r=0,n=0){let a=F(e,"x","gather"),s=F(t,"indices","gather","int32"),i={x:a,indices:s},o={axis:r,batchDims:n};return B.runKernel(Jo,i,o)}var ku=W({gather_:mP});function gP(e,t){let r=F(e,"a","greater","string_or_numeric"),n=F(t,"b","greater","string_or_numeric");[r,n]=Dt(r,n),bt(r.shape,n.shape);let a={a:r,b:n};return B.runKernel(el,a)}var fn=W({greater_:gP});function yP(e,t){let r=F(e,"a","greaterEqual","string_or_numeric"),n=F(t,"b","greaterEqual","string_or_numeric");[r,n]=Dt(r,n),bt(r.shape,n.shape);let a={a:r,b:n};return B.runKernel(hi,a)}var El=W({greaterEqual_:yP});function AP(e){let t={input:F(e,"input","imag")};return B.runKernel(eh,t)}var Im=W({imag_:AP});function xP(e){let t={x:F(e,"x","isFinite")};return B.runKernel(qu,t)}var bP=W({isFinite_:xP});function vP(e){let t={x:F(e,"x","isInf")};return B.runKernel(Ku,t)}var wP=W({isInf_:vP});function kP(e){let t={x:F(e,"x","isNaN")};return B.runKernel(Xu,t)}var e7=W({isNaN_:kP});function IP(e,t=.2){let r={x:F(e,"x","leakyRelu")},n={alpha:t};return B.runKernel(fi,r,n)}var Sm=W({leakyRelu_:IP});function SP(e,t){let r=F(e,"a","less","string_or_numeric"),n=F(t,"b","less","string_or_numeric");[r,n]=Dt(r,n),bt(r.shape,n.shape);let a={a:r,b:n};return B.runKernel(tl,a)}var G2=W({less_:SP});function TP(e,t){let r=F(e,"a","lessEqual","string_or_numeric"),n=F(t,"b","lessEqual","string_or_numeric");[r,n]=Dt(r,n),bt(r.shape,n.shape);let a={a:r,b:n};return B.runKernel(rl,a)}var Rl=W({lessEqual_:TP});function t7(e,t,r){if(r<=0)throw new Error("The number of values should be positive.");let n={start:e,stop:t,num:r};return B.runKernel(lm,{},n)}function NP(e,t=5,r=1,n=1,a=.5){let s=F(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(xu(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let i=s,o=!1;s.rank===3&&(o=!0,i=G(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let l={x:i},u={depthRadius:t,bias:r,alpha:n,beta:a},d=B.runKernel(rh,l,u);return o?G(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var r7=W({localResponseNormalization_:NP});function CP(e){let t={x:F(e,"x","log","float32")};return B.runKernel(mi,t)}var Mn=W({log_:CP});function EP(e){let t={x:F(e,"x","log1p")};return B.runKernel(Zu,t)}var Tm=W({log1p_:EP});function RP(e){return P(Ms(e),()=>"The f passed in grad(f) must be a function"),(t,r)=>{let n=F(t,"x","tf.grad","string_or_numeric"),a=r!=null?F(r,"dy","tf.grad"):null;return B.tidy(()=>{let{value:s,grads:i}=B.gradients(()=>e(n),[n],a);return a!=null&&Vr(s.shape,a.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Nm(i),i[0]})}}function MP(e){return P(Ms(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 n=Dp(t,"args","tf.grads","string_or_numeric"),a=r!=null?F(r,"dy","tf.grads"):null;return B.tidy(()=>{let{value:s,grads:i}=B.gradients(()=>e(...n),n,a);return a!=null&&Vr(s.shape,a.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Nm(i),i})}}function FP(e){return P(Ms(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,r)=>{P(t instanceof nt,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),P(r==null||r instanceof nt,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:n,value:a}=B.gradients(()=>e(t),[t],r);return Nm(n),{grad:n[0],value:a}}}function $P(e){return P(Ms(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,r)=>{P(Array.isArray(t)&&t.every(a=>a instanceof nt),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),P(r==null||r instanceof nt,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let n=B.gradients(()=>e(...t),t,r);return r!=null&&Vr(n.value.shape,r.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Nm(n.grads),n}}function n7(e,t){P(Ms(e),()=>"The f passed in variableGrads(f) must be a function"),P(t==null||Array.isArray(t)&&t.every(u=>u instanceof Op),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let r=t!=null;if(!r){t=[];for(let u in B.registeredVariables)t.push(B.registeredVariables[u])}let n=r?t.filter(u=>!u.trainable):null,a=t.length;t=t.filter(u=>u.trainable),P(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${a} variables is trainable.`);let s=!0,{value:i,grads:o}=B.gradients(e,t,null,s);P(o.some(u=>u!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),P(i.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${i.rank} tensor`);let l={};return t.forEach((u,d)=>{o[d]!=null&&(l[u.name]=o[d])}),n!=null&&n.forEach(u=>l[u.name]=null),{value:i,grads:l}}function Fa(e){return B.customGrad(e)}function Nm(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 PP(e){let t={x:F(e,"x","neg")};return B.runKernel(al,t)}var Ot=W({neg_:PP});function _P(e){let t={x:F(e,"x","softplus")};return B.runKernel(sd,t)}var pd=W({softplus_:_P});function zP(e){let t=F(e,"x","logSigmoid");return Fa(r=>({value:Ot(pd(Ot(r))),gradFunc:n=>L(n,Nr(Ot(r)))}))(t)}var OP=W({logSigmoid_:zP});function DP(e,t=null,r=!1){let n={x:F(e,"x","max")},a={reductionIndices:t,keepDims:r};return B.runKernel(gi,n,a)}var gr=W({max_:DP});function LP(e,t){let r=F(e,"a","sub"),n=F(t,"b","sub");[r,n]=Dt(r,n);let a={a:r,b:n};return B.runKernel(Di,a)}var ce=W({sub_:LP});function BP(e,t=null,r=!1){let n=F(e,"x","sum");n.dtype==="bool"&&(n=me(n,"int32"));let a={x:n},s={axis:t,keepDims:r};return B.runKernel(_i,a,s)}var ke=W({sum_:BP});function WP(e,t=-1){let r=F(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 Fa((n,a)=>{let s=gr(n,t,!0),i=ce(n,s),o=ce(me(i,"float32"),Mn(ke(Rn(i),t,!0)));return a([o]),{value:o,gradFunc:(l,u)=>{let[d]=u,h=!0,p=Rn(d);return ce(l,L(ke(l,t,h),p))}}})(r)}var j2=W({logSoftmax_:WP});function H2(e,t){for(let r=0;r<e.length;++r)if(e[e.length-r-1]!==t-1-r)return!1;return!0}function a7(e,t,r){let n=e.length+t.length,a=[],s=0,i=0;for(let o=0;o<n;o++)r.indexOf(o)===-1?a.push(e[s++]):a.push(t[i++]);return a}function s7(e,t){let r=[],n=e.length;for(let s=0;s<n;s++)t.indexOf(s)===-1&&r.push(e[s]);let a=t.map(s=>e[s]);return[r,a]}function Fo(e,t){let r=t.map(n=>1);return a7(e,r,t)}function VP(e,t,r){P(H2(t,r),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${r} input.`)}function i7(e,t){if(H2(e,t))return null;let r=[];for(let n=0;n<t;++n)e.indexOf(n)===-1&&r.push(n);return e.forEach(n=>r.push(n)),r}function q2(e){return e.map((t,r)=>[r,t]).sort((t,r)=>t[1]-r[1]).map(t=>t[0])}function UP(e,t){let r=[];for(let n=t-e;n<t;++n)r.push(n);return r}function GP(e,t=null,r=!1){let n=F(e,"x","logSumExp"),a=Gn(t,n.shape),s=gr(n,a,!0),i=ce(n,s),o=Rn(i),l=ke(o,a),u=Mn(l),d=le(G(s,u.shape),u);if(r){let h=Fo(d.shape,a);return G(d,h)}return d}var o7=W({logSumExp_:GP});function jP(e,t){let r=F(e,"a","logicalAnd","bool"),n=F(t,"b","logicalAnd","bool");bt(r.shape,n.shape);let a={a:r,b:n};return B.runKernel(nl,a)}var fa=W({logicalAnd_:jP});function HP(e){let t={x:F(e,"x","logicalNot","bool")};return B.runKernel(Yu,t)}var Cm=W({logicalNot_:HP});function qP(e,t){let r=F(e,"a","logicalOr","bool"),n=F(t,"b","logicalOr","bool");bt(r.shape,n.shape);let a={a:r,b:n};return B.runKernel(th,a)}var K2=W({logicalOr_:qP});function KP(e,t){let r=F(e,"a","logicalXor","bool"),n=F(t,"b","logicalXor","bool");return bt(r.shape,n.shape),fa(K2(e,t),Cm(fa(e,t)))}var XP=W({logicalXor_:KP});function ZP(e,t,r,n,a){let s=F(e,"x","maxPool"),i=1,o=s,l=!1;s.rank===3&&(l=!0,o=G(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(Pa(r,i),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${r} and dilations '${i}'`),Gr("maxPool",n,a);let u={x:o},d={filterSize:t,strides:r,pad:n,dimRoundingMode:a},h=B.runKernel(Ai,u,d);return l?G(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var Em=W({maxPool_:ZP});function YP(e,t=[1,1,1],r,n,a,s="NDHWC"){let i=F(e,"x","maxPool3d"),o=i,l=!1;i.rank===4&&(l=!0,o=G(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}`),Gr("maxPool3d",n,a);let u={x:o},d={filterSize:t,strides:r,pad:n,dimRoundingMode:a,dataFormat:s},h=B.runKernel(nh,u,d);return l?G(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var X2=W({maxPool3d_:YP});function JP(e,t,r,n,a=!1){let s={x:F(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:r,pad:n,includeBatchInIndex:a},o=B.runKernel(hm,s,i);return{result:o[0],indexes:o[1]}}var l7=W({maxPoolWithArgmax_:JP});function QP(e,t){let r=F(e,"a","maximum"),n=F(t,"b","maximum");[r,n]=Dt(r,n),r.dtype==="bool"&&(r=me(r,"int32"),n=me(n,"int32")),bt(r.shape,n.shape);let a={a:r,b:n};return B.runKernel(yi,a)}var ts=W({maximum_:QP});function e_(e,t=null,r=!1){let n={x:F(e,"x","mean")},a={axis:t,keepDims:r};return B.runKernel(xi,n,a)}var Wt=W({mean_:e_});function Pt(e,t="float32"){if(t==="complex64"){let n=Pt(e,"float32"),a=Pt(e,"float32");return _s(n,a)}let r=qf(Tt(e),t);return B.makeTensor(r,e,t)}function hn(e,t="float32"){if(t==="complex64"){let n=hn(e,"float32"),a=Pt(e,"float32");return _s(n,a)}let r=d2(Tt(e),t);return B.makeTensor(r,e,t)}function t_(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 n=F(e,"x","meshgrid",e instanceof nt?e.dtype:"float32");if(t===void 0)return[n];let a=F(t,"y","meshgrid",t instanceof nt?t.dtype:"float32"),s=Tt(n.shape),i=Tt(a.shape);return r==="xy"?(n=G(n,[1,-1]),a=G(a,[-1,1]),[Je(hn([i,1],n.dtype),n),Je(a,hn([1,s],a.dtype))]):(n=G(n,[-1,1]),a=G(a,[1,-1]),[Je(n,hn([1,i],n.dtype)),Je(hn([s,1],a.dtype),a)])}function r_(e,t=null,r=!1){let n={x:F(e,"x","min")},a={axis:t,keepDims:r};return B.runKernel(bi,n,a)}var Ds=W({min_:r_});function n_(e,t){let r=F(e,"a","minimum"),n=F(t,"b","minimum");[r,n]=Dt(r,n),r.dtype==="bool"&&(r=me(r,"int32"),n=me(n,"int32")),bt(r.shape,n.shape);let a={a:r,b:n};return B.runKernel(vi,a)}var vh=W({minimum_:n_});function a_(e,t,r){P(r==="reflect"||r==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${r}.`);let n=F(e,"x","mirrorPad");if(n.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");P(t.length===n.rank,()=>`Padding doesn't match input. Must be ${n.rank}. Got ${t.length}.`);let a=r==="reflect"?1:0;for(let o=0;o<n.rank;o++)P(t[o].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),P(t[o][0]>=0&&t[o][0]<=n.shape[o]-a&&t[o][1]>=0&&t[o][1]<=n.shape[o]-a,()=>`Padding in dimension ${o} cannot be greater than or equal to ${n.shape[o]-a} or less than 0 for input of shape ${n.shape}`);let s={paddings:t,mode:r},i={x:n};return B.runKernel(wi,i,s)}var u7=W({mirrorPad_:a_});function s_(e,t){let r=F(e,"a","mod"),n=F(t,"b","mod");[r,n]=Dt(r,n);let a={a:r,b:n};return B.runKernel(Ju,a)}var hd=W({mod_:s_});function i_(e){let t=F(e,"x","square"),r={};return B.runKernel("Square",{x:t},r)}var At=W({square_:i_});function o_(e,t=null,r=!1){e=F(e,"x","moments");let n=Gn(t,e.shape),a=Wt(e,n,r),s=a.shape;r||(s=Fo(a.shape,n));let i=At(ce(me(e,"float32"),G(a,s))),o=Wt(i,n,r);return{mean:a,variance:o}}var Rm=W({moments_:o_});function l_(e,t,r,n){let a=F(t,"data","multiRNNCell"),s=Dp(r,"c","multiRNNCell"),i=Dp(n,"h","multiRNNCell"),o=a,l=[];for(let h=0;h<e.length;h++){let p=e[h](o,s[h],i[h]);l.push(p[0]),l.push(p[1]),o=p[1]}let u=[],d=[];for(let h=0;h<l.length;h+=2)u.push(l[h]),d.push(l[h+1]);return[u,d]}var u_=W({multiRNNCell_:l_});function d_(e,t,r,n=!1){let a=F(e,"logits","multinomial"),s=a.size,i=a.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?G(a,[1,-1]):a},l={numSamples:t,seed:r,normalized:n},u=B.runKernel(cm,o,l);return i===1?G(u,[u.size]):u}var d7=W({multinomial_:d_});function p_(e,t){let r=F(e,"a","notEqual","string_or_numeric"),n=F(t,"b","notEqual","string_or_numeric");[r,n]=Dt(r,n),bt(r.shape,n.shape);let a={a:r,b:n};return B.runKernel(sl,a)}var Iu=W({notEqual_:p_});function h_(e){let t={x:F(e,"x","onesLike")};return B.runKernel(ll,t)}var Fn=W({onesLike_:h_});function c_(e,t){let r=F(e,"v1","outerProduct"),n=F(t,"v2","outerProduct");P(r.rank===1&&n.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${r.rank} and ${n.rank}.`);let a=G(r,[-1,1]),s=G(n,[1,-1]);return Je(a,s)}var f_=W({outerProduct_:c_});function m_(e,t,r=0){let n=F(e,"x","pad");if(n.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");let a={paddings:t,constantValue:r},s={x:n};return B.runKernel(Ii,s,a)}var Hn=W({pad_:m_});function g_(e,t,r=0){return P(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),Hn(e,[t],r)}var y_=W({pad1d_:g_});function A_(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."),Hn(e,t,r)}var x_=W({pad2d_:A_});function b_(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."),Hn(e,t,r)}var v_=W({pad3d_:b_});function w_(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."),Hn(e,t,r)}var k_=W({pad4d_:w_});function I_(e,t,r){let n=F(e,"x","spaceToBatchND");P(n.rank>=1+t.length,()=>`input rank ${n.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(n.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 ${n.shape.slice(1)} with paddings ${r.toString()} must be divisible by blockShapes ${t.toString()}`);let a={x:n},s={blockShape:t,paddings:r};return B.runKernel(Al,a,s)}var Mm=W({spaceToBatchND_:I_});function S_(e,t,r,n,a,s,i){a==null&&(a=[1,1]),s==null&&(s=1),n===0&&(n="valid");let o=F(e,"x","maxPool"),l=o,u=!1;o.rank===3&&(u=!0,l=G(o,[1,o.shape[0],o.shape[1],o.shape[2]])),P(Pa(s,a),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${a}'`);let d=Pk(l.shape,t,s,a,n),h=[d.dilationHeight,d.dilationWidth],p;n==="same"?p=N_([d.filterHeight,d.filterWidth],h):p=[[0,0],[0,0]];let c=h[0]===1&&h[1]===1,[f,m]=T_([d.inHeight,d.inWidth],h,p),g=c?n:"valid",y=c?l:Mm(l,h,f),A=(r==="avg"?()=>vm(y,t,s,g,i):()=>Em(y,t,s,g,i))(),x=c?A:wm(A,h,m);return u?G(x,[x.shape[1],x.shape[2],x.shape[3]]):x}function T_(e,t,r){let n=r.map(d=>d[0]),a=r.map(d=>d[1]),s=e.concat(n,a),i=t.map((d,h)=>(d-s[h]%d)%d),o=a.map((d,h)=>d+i[h]),l=t.map((d,h)=>[n[h],o[h]]),u=t.map((d,h)=>[0,i[h]]);return[l,u]}function N_(e,t){let r=e.map((s,i)=>s+(s-1)*(t[i]-1)).map(s=>s-1),n=r.map(s=>Math.floor(s/2)),a=r.map((s,i)=>s-n[i]);return r.map((s,i)=>[n[i],a[i]])}var C_=W({pool_:S_});function E_(e,t){let r=F(e,"base","pow"),n=F(t,"exp","pow");[r,n]=Dt(r,n);let a={a:r,b:n};return B.runKernel(Si,a)}var Ls=W({pow_:E_});function R_(e,t){let r=F(e,"x","prelu"),n=F(t,"alpha","prelu"),a={x:r,alpha:n};return B.runKernel(Ti,a)}var Fm=W({prelu_:R_});function M_(e,t=null,r=!1){let n=F(e,"x","prod");n.dtype==="bool"&&(n=me(n,"int32"));let a={x:n},s={axis:t,keepDims:r};return B.runKernel(Ni,a,s)}var Z2=W({prod_:M_});function F_(e,t,r){let n=Tt(e),a=null;if(r==null||r==="float32")a=new Float32Array(n);else if(r==="int32")a=new Int32Array(n);else if(r==="bool")a=new Uint8Array(n);else throw new Error(`Unknown data type ${r}`);for(let s=0;s<n;s++)a[s]=t();return B.makeTensor(a,e,r)}var $_=W({rand_:F_}),Y2=Bo(jf()),J2=class{constructor(e,t,r,n,a){this.mean=e,this.stdDev=t,this.dtype=r,this.nextVal=NaN,this.truncated=n,this.truncated&&(this.upper=this.mean+this.stdDev*2,this.lower=this.mean-this.stdDev*2);let s=a||Math.random();this.random=Y2.alea(s.toString())}nextValue(){if(!isNaN(this.nextVal)){let n=this.nextVal;return this.nextVal=NaN,n}let e,t,r=!1;for(;!r;){let n,a,s;do n=2*this.random()-1,a=2*this.random()-1,s=n*n+a*a;while(s>=1||s===0);let i=Math.sqrt(-2*Math.log(s)/s);e=this.mean+this.stdDev*n*i,t=this.mean+this.stdDev*a*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}},P_=class{constructor(e,t,r,n){this.alpha=e,this.beta=1/t,this.dtype=r;let a=n||Math.random();this.randu=Y2.alea(a.toString()),this.randn=new J2(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,n,a,s;for(;;){do n=this.randn.nextValue(),s=1+this.c*n;while(s<=0);if(s*=s*s,e=n*n,t=1-.331*e*e,r=.5*e+this.d*(1-s+Math.log(s)),a=this.randu(),a<t||Math.log(a)<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)}},__=class{constructor(e=0,t=1,r,n){if(this.canReturnFloat=()=>this.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=r,n==null&&(n=Math.random()),typeof n=="number"&&(n=n.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=Y2.alea(n)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function z_(e,t,r=1,n="float32",a){if(r==null&&(r=1),n==null&&(n="float32"),n!=="float32"&&n!=="int32")throw new Error(`Unsupported data type ${n}`);let s=new P_(t,r,n,a),i=We(e,n);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var O_=W({randomGamma_:z_});function D_(e,t=0,r=1,n,a){if(n!=null&&n==="bool")throw new Error(`Unsupported data type ${n}`);let s=new J2(t,r,n,!1,a),i=We(e,n);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var p7=W({randomNormal_:D_});function L_(e,t=0,r=1,n="float32",a){let s=We(e,n),i=new __(t,r,null,a);for(let o=0;o<s.values.length;o++)s.values[o]=i.nextValue();return s.toTensor()}var cd=W({randomUniform_:L_});function Su(e,t,r=1,n="float32"){if(r===0)throw new Error("Cannot have a step of zero");let a={start:e,stop:t,step:r,dtype:n};return B.runKernel(ed,{},a)}function B_(e){let t={input:F(e,"input","real")};return B.runKernel(ah,t)}var Bp=W({real_:B_});function W_(e){let t={x:F(e,"x","reciprocal")};return B.runKernel(td,t)}var h7=W({reciprocal_:W_});function V_(e){let t={x:F(e,"x","relu")};return B.runKernel(Ci,t)}var _a=W({relu_:V_});function U_(e){let t={x:F(e,"x","relu6")};return B.runKernel(Ri,t)}var Q2=W({relu6_:U_});function G_(e,t){let r={x:F(e,"x","reverse")},n={dims:t};return B.runKernel(hl,r,n)}var $n=W({reverse_:G_});function j_(e){let t=F(e,"x","reverse");return P(t.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),$n(t,0)}var H_=W({reverse1d_:j_});function q_(e,t){let r=F(e,"x","reverse");return P(r.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${r.rank}.`),$n(r,t)}var K_=W({reverse2d_:q_});function X_(e,t){let r=F(e,"x","reverse");return P(r.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${r.rank}.`),$n(r,t)}var Z_=W({reverse3d_:X_});function Y_(e,t){let r=F(e,"x","reverse");return P(r.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${r.rank}.`),$n(r,t)}var J_=W({reverse4d_:Y_});function Q_(e){let t={x:F(e,"x","round")};return B.runKernel(cl,t)}var eA=W({round_:Q_});function ez(e){let t={x:F(e,"x","rsqrt","float32")};return B.runKernel(Mi,t)}var tA=W({rsqrt_:ez});function Se(e,t){if((Sr(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"&&Sr(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Vi(e,[],[],t)}function tz(e){let t={x:F(e,"x","selu")};return B.runKernel(nd,t)}var rA=W({selu_:tz});function rz(e,t,r,n,a,s=[1,1],i="NHWC"){let o=F(e,"x","separableConv2d"),l=F(t,"depthwiseFilter","separableConv2d"),u=F(r,"pointwiseFilter","separableConv2d"),d=o,h=!1;if(o.rank===3&&(h=!0,d=G(o,[1,o.shape[0],o.shape[1],o.shape[2]])),i==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");P(d.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${d.rank}.`),P(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),P(u.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),P(u.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${u.shape[0]}.`),P(u.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${u.shape[1]}.`);let p=l.shape[2],c=l.shape[3];P(u.shape[2]===p*c,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${p*c}, but got ${u.shape[2]}.`);let f=Ah(d,l,n,a,i,s),m=Os(f,u,1,"valid",i);return h?G(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var c7=W({separableConv2d_:rz});async function nz(e,t){let r=F(e,"x","setdiff1d"),n=F(t,"y","setdiff1d");P(r.dtype===n.dtype,()=>`x and y should have the same dtype, but got x (${r.dtype}) and y (${n.dtype}).`),P(r.rank===1,()=>`x should be 1D tensor, but got x (${r.shape}).`),P(n.rank===1,()=>`y should be 1D tensor, but got y (${n.shape}).`);let a=await r.data(),s=await n.data(),i=new Set(s),o=0;for(let d=0;d<a.length;d++)i.has(a[d])||o++;let l=new sr([o],r.dtype),u=new sr([o],"int32");for(let d=0,h=0;d<a.length;d++)i.has(a[d])||(l.values[h]=a[d],u.values[h]=d,h++);return[l.toTensor(),u.toTensor()]}var f7=nz;function az(e){let t={x:F(e,"x","sign")};return B.runKernel(ad,t)}var m7=W({sign_:az});function sz(e){let t={x:F(e,"x","sin","float32")};return B.runKernel(Fi,t)}var nA=W({sin_:sz});function iz(e){let t={x:F(e,"x","sinh")};return B.runKernel(yl,t)}var aA=W({sinh_:iz});function oz(e,t,r){let n=F(e,"x","slice1d");return P(n.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${n.rank} tensor`),Pe(n,[t],[r])}var $m=W({slice1d_:oz});function lz(e,t,r){let n=F(e,"x","slice2d");return P(n.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${n.rank} tensor`),Pe(n,t,r)}var sA=W({slice2d_:lz});function uz(e,t,r){let n=F(e,"x","slice3d");return P(n.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${n.rank} tensor`),Pe(n,t,r)}var Ml=W({slice3d_:uz});function dz(e,t,r){let n=F(e,"x","slice4d");return P(n.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${n.rank} tensor`),Pe(n,t,r)}var $o=W({slice4d_:dz});function pz(e,t=-1){let r=F(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 n={logits:r},a={dim:t};return B.runKernel(zi,n,a)}var fd=W({softmax_:pz});function hz(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(im,t)}var Pm=W({fft_:hz});function cz(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(om,t)}var Wp=W({ifft_:cz});function fz(e){let t=e.shape[e.shape.length-1],r=e.size/t,n;if(t<=2){let a=G(e,[r,t]);n=Wp(a)}else{let a=[r,2*(t-1)],s=G(Bp(e),[r,t]),i=G(Im(e),[r,t]),o=$n(Pe(s,[0,1],[r,t-2]),1),l=L($n(Pe(i,[0,1],[r,t-2]),1),Se(-1)),u=kt([s,o],1),d=kt([i,l],1),h=G(_s(u,d),[a[0],a[1]]);n=Wp(h)}if(n=Bp(n),e.rank===3&&e.shape[0]!==0){let a=n,s=e.shape[0];n=G(n,[s,n.shape[0]/s,n.shape[1]]),a.dispose()}return n}var iA=W({irfft_:fz});function mz(e,t,r=0){let n={x:F(e,"x","split")},a={numOrSizeSplits:t,axis:r};return B.runKernel(xl,n,a)}var Xt=W({split_:mz});function gz(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],n=e.size/r,a;if(t!=null&&t<r){let f=e.shape.map(g=>0),m=e.shape.map(g=>g);m[e.shape.length-1]=t,a=Pe(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,a=kt([e,Pt(f)],e.shape.length-1),r=t}else a=e;let s=at(a),i=G(_s(a,s),[n,r]),o=Pm(i),l=Math.floor(r/2)+1,u=Bp(o),d=Im(o),h=Xt(u,[l,r-l],u.shape.length-1),p=Xt(d,[l,r-l],d.shape.length-1),c=a.shape.slice();return c[a.shape.length-1]=l,G(_s(h[0],p[0]),c)}var _m=W({rfft_:gz});function yz(e){let t={x:F(e,"x","sqrt","float32")};return B.runKernel(Pi,t)}var Er=W({sqrt_:yz});function Az(e,t){let r=F(e,"a","squaredDifference"),n=F(t,"b","squaredDifference");[r,n]=Dt(r,n),bt(r.shape,n.shape);let a={a:r,b:n},s={};return B.runKernel(Oi,a,s)}var oA=W({squaredDifference_:Az});function xz(e,t){let r=F(e,"x","squeeze");return G(r,bw(r.shape,t).newShape)}var rt=W({squeeze_:xz});function bz(e,t=0){let r=Dp(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 n=r,a={axis:t};return B.runKernel(dl,n,a)}var lr=W({stack_:bz});function vz(e,t=0){let r={x:F(e,"x","step")},n={alpha:t};return B.runKernel(Wi,r,n)}var wh=W({step_:vz});function wz(e,t,r,n,a=0,s=0,i=0,o=0,l=0){let u={x:F(e,"x","stridedSlice","string_or_numeric")},d={begin:t,end:r,strides:n,beginMask:a,endMask:s,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};return B.runKernel(bl,u,d)}var g7=W({stridedSlice_:wz});function kz(e){let t={x:F(e,"x","tan","float32")};return B.runKernel(vl,t)}var y7=W({tan_:kz});function St(e,t){Wo(e);let r=Ma(e,t);if(r.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Vi(e,null,r,t)}function pa(e,t,r){if(Wo(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let n=Ma(e,r);if(n.length!==2&&n.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Vi(e,t,n,r)}function Iz(e,t,r){if(Wo(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let n=Ma(e,r);if(n.length!==4&&n.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Vi(e,t,n,r)}function Sz(e,t,r){if(Wo(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let n=Ma(e,r);if(n.length!==5&&n.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Vi(e,t,n,r)}function Tz(e,t,r){if(Wo(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let n=Ma(e,r);if(n.length!==6&&n.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(n.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||n,Vi(e,t,n,r)}function Nz(e,t=1,r=!0){let n=F(e,"x","topk");if(n.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let a=n.shape[n.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>a)throw new Error(`'k' passed to topk() must be <= the last dimension (${a}) but got ${t}`);let s={x:n},i={k:t,sorted:r},[o,l]=B.runKernel(wl,s,i);return{values:o,indices:l}}var A7=W({topk_:Nz});function Cz(e,t=0,r=1,n,a){if(n!=null&&n==="bool")throw new Error("Unsupported data type $ { dtype }");let s=new J2(t,r,n,!0,a),i=We(e,n);for(let o=0;o<i.values.length;o++)i.values[o]=s.nextValue();return i.toTensor()}var zm=W({truncatedNormal_:Cz});function Ez(e,t=0){let r=F(e,"x","unique","string_or_numeric");P(r.rank>0,()=>"The input tensor must be at least 1D");let n={x:r},a={axis:t},[s,i]=B.runKernel(Am,n,a);return{values:s,indices:i}}var wy=W({unique_:Ez});function Rz(e,t,r){let n=F(e,"x","unsortedSegmentSum"),a=F(t,"segmentIds","unsortedSegmentSum","int32");P(xu(r),()=>"numSegments must be of dtype int");let s={x:n,segmentIds:a},i={numSegments:r};return B.runKernel(dh,s,i)}var x7=W({unsortedSegmentSum_:Rz});function Mz(e,t=0){let r=F(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 n={value:r},a={axis:t};return B.runKernel(Il,n,a)}var rn=W({unstack_:Mz});function b7(e,t=!0,r,n){return B.makeVariable(e,t,r,n)}function v7(e,t){let r=[];for(let s=0;s<t.length;s++)t[s]&&r.push(s);let n=We(e,"int32"),a=We([r.length,e.length],"int32");for(let s=0;s<r.length;s++){let i=n.indexToLoc(r[s]),o=s*e.length;a.values.set(i,o)}return a.toTensor()}async function Fz(e){let t=F(e,"condition","whereAsync","bool"),r=await t.data(),n=v7(t.shape,r);return e!==t&&t.dispose(),n}var lA=Fz;async function $z(e,t,r){let n=F(e,"tensor","boolMask"),a=F(t,"mask","boolMask","bool"),s=r==null?0:r,i=a.rank,o=n.shape;P(i>0,()=>"mask cannot be scalar"),Vr(o.slice(s,s+i),a.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let m=s;m<s+i;m++)l*=o[m];let u=o.slice(0,s).concat([l],o.slice(s+i)),d=G(n,u),h=G(a,[-1]),p=await lA(h),c=rt(p,[1]),f=ku(d,c,s);return e!==n&&n.dispose(),t!==a&&a.dispose(),c.dispose(),d.dispose(),h.dispose(),p.dispose(),f}var Pz=$z;function _z(e,t="euclidean",r=null,n=!1){e=F(e,"x","norm");let a=w7(e,t,r),s=a.shape;if(n){let i=Gn(r,e.shape);s=Fo(a.shape,i)}return G(a,s)}function w7(e,t,r=null){if(e.rank===0)return rr(e);if(e.rank!==1&&r===null)return w7(G(e,[-1]),t,r);if(e.rank===1||typeof r=="number"||Array.isArray(r)&&r.length===1){if(t===1)return ke(rr(e),r);if(t===1/0)return gr(rr(e),r);if(t===-1/0)return Ds(rr(e),r);if(t==="euclidean"||t===2)return Er(ke(Ls(rr(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 gr(ke(rr(e),r[0]),r[1]-1);if(t===1/0)return gr(ke(rr(e),r[1]),r[0]);if(t===-1/0)return Ds(ke(rr(e),r[1]),r[0]);if(t==="fro"||t==="euclidean")return Er(ke(At(e),r));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${r}`)}var uA=W({norm_:_z});function zz(e,t,r,n,a=!0){let s=F(e,"v","movingAverage"),i=F(t,"x","movingAverage"),o=F(r,"decay","movingAverage");Vw(s,i),P(qs(s.shape,i.shape),()=>"Shape mismatch in v and x");let l=Se(1),u=ce(l,o),d=L(ce(i,s),u);if(a){P(n!=null,()=>"When using zeroDebias: true, step is required.");let h=F(n,"step","movingAverage");d=pe(d,ce(l,Ls(o,h)))}return le(s,d)}var Oz=W({movingAverage_:zz});function Dz(e,t,r){let n=F(e,"indices","scatterND","int32"),a=F(t,"updates","scatterND");S2(a,n,r);let s={indices:n,updates:a},i={shape:r};return B.runKernel(fl,s,i)}var k7=W({scatterND_:Dz});function Lz(e,t,r,n){if(e.dtype!=="int32")throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);let a=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===a))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${a}]`);if(t.dtype!==n.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function Bz(e,t,r,n=0){let a=F(e,"sparseIndices","sparseToDense","int32"),s=F(t,"sparseValues","sparseToDense"),i=F(n,"defaultValue","sparseToDense",s.dtype);Lz(a,s,r,i);let o={sparseIndices:a,sparseValues:s,defaultValue:i},l={outputShape:r};return B.runKernel(lh,o,l)}var dA=W({sparseToDense_:Bz});function Wz(e,t){let r=F(t,"indices","gatherND","int32"),n={params:F(e,"x","gatherND","string_or_numeric"),indices:r};return B.runKernel(Qo,n)}var I7=W({gatherND_:Wz});function Vz(e,t){if(t==null)return e.shape.slice();if(qs(e.shape,t))return t;if(e.shape.length===t.length){let r=[];for(let n=0;n<e.shape.length;n++)t[n]==null&&e.shape[n]!=null?r.push(e.shape[n]):r.push(t[n]);return r}return t}function Uz(e,t,r,n){let a=F(e,"x","dropout");if(P(a.dtype==="float32",()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${a.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 nt?a.clone():a;let s=Vz(a,r),i=1-t,o=pe(bh(le(cd(s,0,1,"float32",n),i)),i);return L(a,o)}var S7=W({dropout_:Uz});function T7(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function pA(e,t,r){let n=1-e%2,a=new Float32Array(e);for(let s=0;s<e;++s){let i=2*Math.PI*s/(e+n-1);a[s]=t-r*Math.cos(i)}return St(a,"float32")}async function Gz(e,t,r=1){let n=F(e,"predictions","inTopK"),a=F(t,"targets","inTopK");P(n.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${n.rank}`),P(n.rank-1===a.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${n.rank} and targets rank ${a.rank}`),Vr(n.shape.slice(0,n.shape.length-1),a.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");let s=n.shape[n.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 n.data(),o=await a.data(),[l,u]=[i.length/s,s],d=vw("bool",l);for(let h=0;h<l;h++){let p=h*u,c=i.subarray(p,p+u),f=[];for(let m=0;m<c.length;m++)f.push({value:c[m],index:m});f.sort((m,g)=>g.value-m.value),d[h]=0;for(let m=0;m<r;m++)if(f[m].index===o[h]){d[h]=1;break}}return e!==n&&n.dispose(),t!==a&&a.dispose(),ct(d,a.shape,"bool")}var jz=Gz,Bs={};Le(Bs,{conv2d:()=>Kz,depthwiseConv2d:()=>Jz,matMul:()=>eO});function Hz(e,t,r,n,a,s="NHWC",i){let o=e;e.rank===3&&(o=G(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=G(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 u=s==="NHWC"?o.shape[3]:o.shape[1],d=s==="NHWC"?l.shape[3]:l.shape[1];P(u===r[2],()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${r[2]}.`),P(d===r[3],()=>`Error in conv2dDerFilter: depth of dy (${d}) must match output depth for filter (${r[3]}).`),Gr("conv2dDerFilter",a,i);let h={x:o,dy:l},p={strides:n,pad:a,dataFormat:s,dimRoundingMode:i,filterShape:r};return B.runKernel(Jf,h,p)}var hA=W({conv2DBackpropFilter_:Hz});function Om(e,t,r){if(r==null||r==="linear")return e;if(r==="relu")return L(e,wh(t));throw new Error(`Cannot compute gradient for fused activation ${r}.`)}function Dm(e,t){let r=t,n=Zt(e.shape,t.shape);return n.length>0&&(r=ke(r,n)),G(r,e.shape)}function Lm(e,t,r,n){if(t==="linear")return e;if(t==="relu")return _a(e);if(t==="elu")return xh(e);if(t==="relu6")return Q2(e);if(t==="prelu")return Fm(e,r);if(t==="leakyrelu")return Sm(e,n);if(t==="sigmoid")return Nr(e);throw new Error(`Unknown fused activation ${t}.`)}var Bm=(e,t)=>!(e>0)||t==="linear";function qz({x:e,filter:t,strides:r,pad:n,dataFormat:a="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:d}){if(l=l||"linear",Bm(B.state.gradientDepth,l)===!1){let v=Os(e,t,r,n,a,s,i);return o!=null&&(v=le(v,o)),Lm(v,l,u,d)}let h=F(e,"x","conv2d","float32"),p=F(t,"filter","conv2d","float32"),c=h,f=!1;h.rank===3&&(f=!0,c=G(h,[1,h.shape[0],h.shape[1],h.shape[2]])),P(c.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${c.rank}.`),P(p.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${p.rank}.`),Gr("fused conv2d",n,i),P(c.shape[3]===p.shape[2],()=>`Error in conv2d: depth of input (${c.shape[3]}) must match input depth for filter ${p.shape[2]}.`),P(Pa(r,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${r} and dilations '${s}'`),P(a==="NHWC",()=>`Error in conv2d: got dataFormat of ${a} but only NHWC is currently supported.`);let m=yh(c.shape,p.shape,r,s,n,i),g;o!=null&&(g=F(o,"bias","fused conv2d"),[g]=Dt(g,h),bt(m.outShape,g.shape));let y;u!=null&&(y=F(u,"prelu weights","fused conv2d"));let A=(v,S)=>{let[T,E,R,_]=S,M=Om(v,R,l);P(zs(s),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let I=D2(E.shape,M,T,r,n),z=hA(E,M,T.shape,r,n),O=[I,z];if(_!=null){let j=Dm(_,M);O.push(j)}return O},x={x:c,filter:p,bias:g,preluActivationWeights:y},b={strides:r,pad:n,dataFormat:a,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:d};return o==null?Fa((v,S,T)=>{let E=B.runKernel($s,x,b);return T([S,v,E]),f&&(E=G(E,[E.shape[1],E.shape[2],E.shape[3]])),{value:E,gradFunc:A}})(c,p):Fa((v,S,T,E)=>{let R=B.runKernel($s,x,b);return E([S,v,R,T]),f&&(R=G(R,[R.shape[1],R.shape[2],R.shape[3]])),{value:R,gradFunc:A}})(c,p,g)}var Kz=W({fusedConv2d_:qz});function Xz(e,t,r,n,a,s=[1,1],i){let o=e;e.rank===3&&(o=G(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=G(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let u={x:o,dy:l},d={strides:n,pad:a,dimRoundingMode:i,dilations:s,filterShape:r};return B.runKernel(rm,u,d)}var N7=W({depthwiseConv2dNativeBackpropFilter_:Xz});function Zz(e,t,r,n,a,s=[1,1],i){let o=t,l=!1;t.rank===3&&(l=!0,o=G(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let u={dy:o,filter:r},d={strides:n,pad:a,dimRoundingMode:i,dilations:s,inputShape:e},h=B.runKernel(nm,u,d);return l?G(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var C7=W({depthwiseConv2dNativeBackpropInput_:Zz});function Yz({x:e,filter:t,strides:r,pad:n,dataFormat:a="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:d}){if(Bm(B.state.gradientDepth,l)===!1){let v=Ah(e,t,r,n,a,s,i);return o!=null&&(v=le(v,o)),Lm(v,l,u,d)}let h=F(e,"x","depthwiseConv2d","float32"),p=F(t,"filter","depthwiseConv2d","float32"),c=h,f=!1;h.rank===3&&(f=!0,c=G(h,[1,h.shape[0],h.shape[1],h.shape[2]])),P(c.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`),P(p.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${p.rank}.`),P(c.shape[3]===p.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${c.shape[3]}) must match the inChannels dimension in filter ${p.shape[2]}.`),s==null&&(s=[1,1]),P(Pa(r,s),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${r} and dilations '${s}'`),Gr("fused depthwiseConv2d",n,i);let m=yh(c.shape,p.shape,r,s,n,i,!0),g;o!=null&&(g=F(o,"bias","fused conv2d"),[g]=Dt(g,h),bt(m.outShape,g.shape));let y;u!=null&&(y=F(u,"prelu weights","fused depthwiseConv2d"));let A=(v,S)=>{P(zs(s),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);let[T,E,R,_]=S,M=Om(v,R,l),I=C7(E.shape,M,T,r,n,s,i),z=N7(E,M,T.shape,r,n,s,i);if(_!=null){let O=Dm(g,M);return[I,z,O]}return[I,z]},x={x:c,filter:p,bias:g,preluActivationWeights:y},b={strides:r,pad:n,dataFormat:a,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:d};return o==null?Fa((v,S,T)=>{let E=B.runKernel(Ps,x,b);return T([S,v,E]),f&&(E=G(E,[E.shape[1],E.shape[2],E.shape[3]])),{value:E,gradFunc:A}})(c,p):Fa((v,S,T,E)=>{let R=B.runKernel(Ps,x,b);return E([S,v,R,T]),f&&(R=G(R,[R.shape[1],R.shape[2],R.shape[3]])),{value:R,gradFunc:A}})(c,p,g)}var Jz=W({fusedDepthwiseConv2d_:Yz});function Qz({a:e,b:t,transposeA:r=!1,transposeB:n=!1,bias:a,activation:s="linear",preluActivationWeights:i,leakyreluAlpha:o}){if(Bm(B.state.gradientDepth,s)===!1){let _=Je(e,t,r,n);return a!=null&&(_=le(_,a)),Lm(_,s,i,o)}let l=F(e,"a","fused matMul"),u=F(t,"b","fused matMul");[l,u]=Dt(l,u);let d=r?l.shape[l.rank-2]:l.shape[l.rank-1],h=n?u.shape[u.rank-1]:u.shape[u.rank-2],p=r?l.shape[l.rank-1]:l.shape[l.rank-2],c=n?u.shape[u.rank-2]:u.shape[u.rank-1],f=l.shape.slice(0,-2),m=u.shape.slice(0,-2),g=Tt(f),y=Tt(m);P(d===h,()=>`Error in fused matMul: inner shapes (${d}) and (${h}) of Tensors with shapes ${l.shape} and ${u.shape} and transposeA=${r} and transposeB=${n} must match.`);let A=bt(l.shape.slice(0,-2),u.shape.slice(0,-2)).concat([p,c]),x=r?G(l,[g,d,p]):G(l,[g,p,d]),b=n?G(u,[y,c,h]):G(u,[y,h,c]),v;a!=null&&(v=F(a,"bias","fused matMul"),[v]=Dt(v,l),bt(A,v.shape));let S;i!=null&&(S=F(i,"prelu weights","fused matMul"));let T=(_,M)=>{let[I,z,O,j]=M,X=Om(G(_,O.shape),O,s),D,Q;if(!r&&!n?(D=Je(X,z,!1,!0),Q=Je(I,X,!0,!1)):!r&&n?(D=Je(X,z,!1,!1),Q=Je(X,I,!0,!1)):r&&!n?(D=Je(z,X,!1,!0),Q=Je(I,X,!1,!1)):(D=Je(z,X,!0,!0),Q=Je(X,I,!0,!0)),a!=null){let V=Dm(j,X);return[D,Q,V]}else return[D,Q]},E={a:x,b,bias:v,preluActivationWeights:S},R={transposeA:r,transposeB:n,activation:s,leakyreluAlpha:o};return a==null?Fa((_,M,I)=>{let z=B.runKernel(Fs,E,R);return I([_,M,z]),{value:G(z,A),gradFunc:T}})(x,b):Fa((_,M,I,z)=>{let O=B.runKernel(Fs,E,R);return z([_,M,O,I]),{value:G(O,A),gradFunc:T}})(x,b,v)}var eO=W({fusedMatMul_:Qz});function tO(e){return pA(e,.54,.46)}var rO=W({hammingWindow_:tO});function nO(e){return pA(e,.5,.5)}var E7=W({hannWindow_:nO});function aO(e,t,r,n=!1,a=0){let s=0,i=[];for(;s+t<=e.size;)i.push(Pe(e,s,t)),s+=r;if(n)for(;s<e.size;){let o=s+t-e.size,l=kt([Pe(e,s,t-o),dd([o],a)]);i.push(l),s+=r}return i.length===0?pa([],[0,t]):G(kt(i),[i.length,t])}var R7=W({frame_:aO});function sO(e,t,r,n,a=E7){n==null&&(n=T7(t));let s=R7(e,t,r),i=L(s,a(t));return _m(i,n)}var iO=W({stft_:sO});function oO(e,t,r,n,a="bilinear",s=0){let i=F(e,"image","cropAndResize"),o=F(t,"boxes","cropAndResize","float32"),l=F(r,"boxInd","cropAndResize","int32"),u=o.shape[0];P(i.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`),P(o.rank===2&&o.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${u},4] but had shape ${o.shape}.`),P(l.rank===1&&l.shape[0]===u,()=>`Error in cropAndResize: boxInd must be have size [${u}] but had shape ${o.shape}.`),P(n.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${n.length}.`),P(n[0]>=1&&n[1]>=1,()=>`cropSize must be atleast [1,1], but was ${n}`),P(a==="bilinear"||a==="nearest",()=>`method must be bilinear or nearest, but was ${a}`);let d={image:i,boxes:o,boxInd:l},h={method:a,extrapolationValue:s,cropSize:n};return B.runKernel(Ho,d,h)}var lO=W({cropAndResize_:oO});function uO(e){let t=F(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(Yo,r,{})}var dO=W({flipLeftRight_:uO});function pO(e){let t=F(e,"image","grayscaleToRGB"),r=t.rank-1,n=t.shape[r];P(t.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`),P(n===1,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${n}.`);let a=new Array(t.rank);return a.fill(1,0,r),a[r]=3,Vn(t,a)}var hO=W({grayscaleToRGB_:pO});function cO(e,t,r=0,n=.5){let a=F(e,"image","rotateWithOffset","float32");P(a.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${a.rank}.`);let s={image:a},i={radians:t,fillValue:r,center:n};return B.runKernel(Tl,s,i)}var fO=W({rotateWithOffset_:cO});function md(e,t,r,n,a,s){n==null&&(n=.5),a==null&&(a=Number.NEGATIVE_INFINITY),s==null&&(s=0);let i=e.shape[0];return r=Math.min(r,i),P(0<=n&&n<=1,()=>`iouThreshold must be in [0, 1], but was '${n}'`),P(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),P(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),P(t.rank===1,()=>"scores must be a 1D tensor"),P(t.shape[0]===i,()=>`scores has incompatible shape with boxes. Expected ${i}, but was ${t.shape[0]}`),P(0<=s&&s<=1,()=>`softNmsSigma must be in [0, 1], but was '${s}'`),{maxOutputSize:r,iouThreshold:n,scoreThreshold:a,softNmsSigma:s}}function mO(e,t,r,n=.5,a=Number.NEGATIVE_INFINITY){let s=F(e,"boxes","nonMaxSuppression","float32"),i=F(t,"scores","nonMaxSuppression","float32"),o=md(s,i,r,n,a);r=o.maxOutputSize,n=o.iouThreshold,a=o.scoreThreshold;let l={maxOutputSize:r,iouThreshold:n,scoreThreshold:a};return B.runKernel(il,{boxes:s,scores:i},l)}var gO=W({nonMaxSuppression_:mO});function yO(e,t,r){let n=AO(e,t,r),a=n<0?-(n+1):n;e.splice(a,0,t)}function AO(e,t,r){return bO(e,t,r||xO)}function xO(e,t){return e>t?1:e<t?-1:0}function bO(e,t,r){let n=0,a=e.length,s=0,i=!1;for(;n<a;){s=n+(a-n>>>1);let o=r(t,e[s]);o>0?n=s+1:(a=s,i=!o)}return i?n:-n-1}function M7(e,t,r,n,a){return cA(e,t,r,n,a,0)}function F7(e,t,r,n,a,s){return cA(e,t,r,n,a,0,!1,s,!0)}function $7(e,t,r,n,a,s){return cA(e,t,r,n,a,s,!0)}function cA(e,t,r,n,a,s,i=!1,o=!1,l=!1){let u=[];for(let g=0;g<t.length;g++)t[g]>a&&u.push({score:t[g],boxIndex:g,suppressBeginIndex:0});u.sort(V3);let d=s>0?-.5/s:0,h=[],p=[];for(;h.length<r&&u.length>0;){let g=u.pop(),{score:y,boxIndex:A,suppressBeginIndex:x}=g;if(y<a)break;let b=!1;for(let v=h.length-1;v>=x;--v){let S=vO(e,A,h[v]);if(S>=n){b=!0;break}if(g.score=g.score*wO(n,d,S),g.score<=a)break}g.suppressBeginIndex=h.length,b||(g.score===y?(h.push(A),p.push(g.score)):g.score>a&&yO(u,g,V3))}let c=h.length,f=r-c;o&&f>0&&(h.push(...new Array(f).fill(0)),p.push(...new Array(f).fill(0)));let m={selectedIndices:h};return i&&(m.selectedScores=p),l&&(m.validOutputs=c),m}function vO(e,t,r){let n=e.subarray(t*4,t*4+4),a=e.subarray(r*4,r*4+4),s=Math.min(n[0],n[2]),i=Math.min(n[1],n[3]),o=Math.max(n[0],n[2]),l=Math.max(n[1],n[3]),u=Math.min(a[0],a[2]),d=Math.min(a[1],a[3]),h=Math.max(a[0],a[2]),p=Math.max(a[1],a[3]),c=(o-s)*(l-i),f=(h-u)*(p-d);if(c<=0||f<=0)return 0;let m=Math.max(s,u),g=Math.max(i,d),y=Math.min(o,h),A=Math.min(l,p),x=Math.max(y-m,0)*Math.max(A-g,0);return x/(c+f-x)}function wO(e,t,r){let n=Math.exp(t*r*r);return r<=e?n:0}function V3(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function kO(e,t,r,n=.5,a=Number.NEGATIVE_INFINITY){let s=F(e,"boxes","nonMaxSuppressionAsync"),i=F(t,"scores","nonMaxSuppressionAsync"),o=md(s,i,r,n,a);r=o.maxOutputSize,n=o.iouThreshold,a=o.scoreThreshold;let l=await Promise.all([s.data(),i.data()]),u=l[0],d=l[1],{selectedIndices:h}=M7(u,d,r,n,a);return s!==e&&s.dispose(),i!==t&&i.dispose(),St(h,"int32")}var IO=kO;function SO(e,t,r,n=.5,a=Number.NEGATIVE_INFINITY,s=0){let i=F(e,"boxes","nonMaxSuppression"),o=F(t,"scores","nonMaxSuppression"),l=md(i,o,r,n,a,s);r=l.maxOutputSize,n=l.iouThreshold,a=l.scoreThreshold,s=l.softNmsSigma;let u={boxes:i,scores:o},d={maxOutputSize:r,iouThreshold:n,scoreThreshold:a,softNmsSigma:s},h=B.runKernel(ol,u,d);return{selectedIndices:h[0],selectedScores:h[1]}}var TO=W({nonMaxSuppressionWithScore_:SO});async function NO(e,t,r,n=.5,a=Number.NEGATIVE_INFINITY,s=0){let i=F(e,"boxes","nonMaxSuppressionAsync"),o=F(t,"scores","nonMaxSuppressionAsync"),l=md(i,o,r,n,a,s);r=l.maxOutputSize,n=l.iouThreshold,a=l.scoreThreshold,s=l.softNmsSigma;let u=await Promise.all([i.data(),o.data()]),d=u[0],h=u[1],{selectedIndices:p,selectedScores:c}=$7(d,h,r,n,a,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:St(p,"int32"),selectedScores:St(c)}}var CO=NO;function EO(e,t,r,n=.5,a=Number.NEGATIVE_INFINITY,s=!1){let i=F(e,"boxes","nonMaxSuppression"),o=F(t,"scores","nonMaxSuppression"),l=md(i,o,r,n,a,null),u=l.maxOutputSize,d=l.iouThreshold,h=l.scoreThreshold,p={boxes:i,scores:o},c={maxOutputSize:u,iouThreshold:d,scoreThreshold:h,padToMaxOutputSize:s},f=B.runKernel(Qu,p,c);return{selectedIndices:f[0],validOutputs:f[1]}}var RO=W({nonMaxSuppressionPadded_:EO});async function MO(e,t,r,n=.5,a=Number.NEGATIVE_INFINITY,s=!1){let i=F(e,"boxes","nonMaxSuppressionAsync"),o=F(t,"scores","nonMaxSuppressionAsync"),l=md(i,o,r,n,a,null),u=l.maxOutputSize,d=l.iouThreshold,h=l.scoreThreshold,[p,c]=await Promise.all([i.data(),o.data()]),{selectedIndices:f,validOutputs:m}=F7(p,c,u,d,h,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:St(f,"int32"),validOutputs:Se(m,"int32")}}var FO=MO;function $O(e,t,r=!1,n=!1){let a=F(e,"images","resizeBilinear");P(a.rank===3||a.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${a.rank}.`),P(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),P(n===!1||r===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let s=a,i=!1;a.rank===3&&(i=!0,s=G(a,[1,a.shape[0],a.shape[1],a.shape[2]]));let[]=t,o={images:s},l={alignCorners:r,halfPixelCenters:n,size:t},u=B.runKernel(Ei,o,l);return i?G(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var PO=W({resizeBilinear_:$O});function _O(e,t,r=!1,n=!1){let a=F(e,"images","resizeNearestNeighbor");P(a.rank===3||a.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${a.rank}.`),P(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),P(a.dtype==="float32"||a.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),P(n===!1||r===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let s=a,i=!1;a.rank===3&&(i=!0,s=G(a,[1,a.shape[0],a.shape[1],a.shape[2]]));let[]=t,o={images:s},l={alignCorners:r,halfPixelCenters:n,size:t},u=B.runKernel(rd,o,l);return i?G(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var zO=W({resizeNearestNeighbor_:_O});function OO(e,t="binary",r=!1,n=.5){let a=F(e,"image","threshold"),s=.2989,i=.587,o=.114,l=a.shape[0]*a.shape[1],u=L(St([n]),255),d,h,p,c;if(P(a.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${a.rank}.`),P(a.shape[2]===3||a.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${a.shape[2]}.`),P(a.dtype==="int32"||a.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${a.dtype}.`),P(t==="otsu"||t==="binary",()=>`Method must be binary or otsu, but was ${t}`),a.shape[2]===3){[d,h,p]=Xt(a,[1,1,1],-1);let m=L(d,s),g=L(h,i),y=L(p,o);c=le(le(m,g),y)}else c=e;if(t==="otsu"){let m=z2(me(eA(c),"int32"),ct([]),256);u=DO(m,l)}let f=r?Rl(c,u):fn(c,u);return me(L(f,255),"int32")}function DO(e,t){let r=St([-1]),n=St([0]),a=St([0]),s,i,o,l,u,d;for(let h=0;h<e.size-1;h++){s=Pe(e,0,h+1),i=Pe(e,h+1),u=pe(ke(s),t),d=pe(ke(i),t);let p=ke(L(s,Su(0,s.size)));o=pe(p,ke(s));let c=dd(i.shape,s.size),f=le(Su(0,i.size),c),m=L(i,f);l=pe(ke(m),ke(i));let g=ce(o,l),y=ce(o,l),A=L(u,d);a=L(L(A,g),y);let x=fn(a,n);n=Wr(x,a,n),r=Wr(x,St([h]),r)}return r}var LO=W({threshold_:OO});function BO(e,t,r="nearest",n="constant",a=0,s){let i=F(e,"image","transform","float32"),o=F(t,"transforms","transform","float32");P(i.rank===4,()=>`Error in transform: image must be rank 4,but got rank ${i.rank}.`),P(o.rank===2&&(o.shape[0]===i.shape[0]||o.shape[0]===1)&&o.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),P(s==null||s.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${s}.`);let l={image:i,transforms:o},u={interpolation:r,fillMode:n,fillValue:a,outputShape:s};return B.runKernel(kl,l,u)}var WO=W({transform_:BO});function VO(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 n=F(e,"a","bandPart");P(n.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${n.rank}.`);let a=n.shape,[s,i]=n.shape.slice(-2);if(!(t<=s))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${s}).`);if(!(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=G(Su(0,s,1,"int32"),[-1,1]),l=Su(0,i,1,"int32"),u=ce(o,l),d=fa(Rl(u,Se(+t,"int32")),El(u,Se(-r,"int32"))),h=Pt([s,i],n.dtype);return G(lr(rn(G(n,[-1,s,i])).map(p=>Wr(d,p,h))),a)}var UO=W({bandPart_:VO});function GO(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 a=e[0].shape[0];for(let s=1;s<e.length;++s)P(e[s].shape[0]===a,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[s].shape[0]} vs. ${a})`)}else t=!0,e=Xt(e,e.shape[0],0).map(a=>rt(a,[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=[],n=e;for(let a=0;a<e.length;++a)r.push(B.tidy(()=>{let s=n[a];if(a>0)for(let i=0;i<a;++i){let o=L(ke(L(r[i],s)),r[i]);s=ce(s,o)}return pe(s,uA(s,"euclidean"))}));return t?lr(r,0):r}var jO=W({gramSchmidt_:GO});function HO(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 U3(e,t);{let r=e.shape.slice(0,e.shape.length-2).reduce((l,u)=>l*u),n=rn(G(e,[r,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),a=[],s=[];n.forEach(l=>{let[u,d]=U3(l,t);a.push(u),s.push(d)});let i=G(lr(a,0),e.shape),o=G(lr(s,0),e.shape);return[i,o]}}function U3(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],n=e.shape[1],a=U2(r),s=Br(e),i=pa([[1]],[1,1]),o=Br(i),l=r>=n?n:r;for(let u=0;u<l;++u){let d=s,h=o,p=a;[o,s,a]=B.tidy(()=>{let c=Pe(s,[u,u],[r-u,1]),f=uA(c),m=Pe(s,[u,u],[1,1]),g=Wr(fn(m,0),pa([[-1]]),pa([[1]])),y=ce(m,L(g,f)),A=pe(c,y);A.shape[0]===1?o=Br(i):o=kt([i,Pe(A,[1,0],[A.shape[0]-1,A.shape[1]])],0);let x=Ot(pe(Je(g,y),f)),b=Pe(s,[u,0],[r-u,n]),v=L(x,o),S=tt(o);if(u===0)s=ce(b,Je(v,Je(S,b)));else{let R=ce(b,Je(v,Je(S,b)));s=kt([Pe(s,[0,0],[u,n]),R],0)}let T=tt(v),E=Pe(a,[0,u],[r,a.shape[1]-u]);if(u===0)a=ce(E,Je(Je(E,o),T));else{let R=ce(E,Je(Je(E,o),T));a=kt([Pe(a,[0,0],[r,u]),R],1)}return[o,s,a]}),re([d,h,p])}return!t&&r>n&&(a=Pe(a,[0,0],[r,n]),s=Pe(s,[0,0],[n,n])),[a,s]})}var qO=W({qr_:HO}),P7=(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))(P7||{});function KO(e,t,r=3){let n=F(e,"losses","computeWeightedLoss"),a=null;t!=null&&(a=F(t,"weights","computeWeightedLoss"));let s=a==null?n:L(n,a);if(r===0)return s;if(r===2)return ke(s);if(r===1){if(a==null)return Wt(s);{let i=n.size/a.size,o=pe(ke(s),ke(a));return i>1?pe(o,Se(i)):o}}if(r===3){if(a==null)return pe(ke(s),Se(n.size));{let i=L(a,hn(n.shape)),o=me(ke(Iu(i,Se(0))),"float32");return pe(ke(s),o)}}throw Error(`Unknown reduction: ${r}`)}var rs=W({computeWeightedLoss_:KO});function XO(e,t,r,n=3){let a=F(e,"labels","absoluteDifference"),s=F(t,"predictions","absoluteDifference"),i=null;r!=null&&(i=F(r,"weights","absoluteDifference")),Vr(a.shape,s.shape,"Error in absoluteDifference: ");let o=rr(ce(a,s));return rs(o,i,n)}var ZO=W({absoluteDifference_:XO});function YO(e,t,r,n,a=3){let s=F(e,"labels","cosineDistance"),i=F(t,"predictions","cosineDistance"),o=null;n!=null&&(o=F(n,"weights","cosineDistance")),Vr(s.shape,i.shape,"Error in cosineDistance: ");let l=Se(1),u=ce(l,ke(L(s,i),r,!0));return rs(u,o,a)}var JO=W({cosineDistance_:YO});function QO(e,t,r,n=3){let a=F(e,"labels","hingeLoss"),s=F(t,"predictions","hingeLoss"),i=null;r!=null&&(i=F(r,"weights","hingeLoss")),Vr(a.shape,s.shape,"Error in hingeLoss: ");let o=Se(1);a=ce(L(Se(2),a),o);let l=_a(ce(o,L(a,s)));return rs(l,i,n)}var eD=W({hingeLoss_:QO});function tD(e,t,r,n=1,a=3){let s=F(e,"labels","huberLoss"),i=F(t,"predictions","huberLoss"),o=null;r!=null&&(o=F(r,"weights","huberLoss")),Vr(s.shape,i.shape,"Error in huberLoss: ");let l=Se(n),u=rr(ce(i,s)),d=vh(u,l),h=ce(u,d),p=le(L(Se(.5),At(d)),L(l,h));return rs(p,o,a)}var rD=W({huberLoss_:tD});function nD(e,t,r,n=1e-7,a=3){let s=F(e,"labels","logLoss"),i=F(t,"predictions","logLoss"),o=null;r!=null&&(o=F(r,"weights","logLoss")),Vr(s.shape,i.shape,"Error in logLoss: ");let l=Se(1),u=Se(n),d=Ot(L(s,Mn(le(i,u)))),h=L(ce(l,s),Mn(le(ce(l,i),u))),p=ce(d,h);return rs(p,o,a)}var aD=W({logLoss_:nD});function sD(e,t,r,n=3){let a=F(e,"labels","meanSquaredError"),s=F(t,"predictions","meanSquaredError"),i=null;r!=null&&(i=F(r,"weights","meanSquaredError")),Vr(a.shape,s.shape,"Error in meanSquaredError: ");let o=oA(a,s);return rs(o,i,n)}var iD=W({meanSquaredError_:sD});function oD(e,t){let r=F(e,"labels","sigmoidCrossEntropyWithLogits"),n=F(t,"logits","sigmoidCrossEntropyWithLogits");Vr(r.shape,n.shape,"Error in sigmoidCrossEntropyWithLogits: ");let a=_a(n),s=L(n,r),i=Tm(Rn(Ot(rr(n))));return le(ce(a,s),i)}function lD(e,t,r,n=0,a=3){let s=F(e,"multiClassLabels","sigmoidCrossEntropy"),i=F(t,"logits","sigmoidCrossEntropy"),o=null;if(r!=null&&(o=F(r,"weights","sigmoidCrossEntropy")),Vr(s.shape,i.shape,"Error in sigmoidCrossEntropy: "),n>0){let u=Se(n),d=Se(1),h=Se(.5);s=le(L(s,ce(d,u)),L(h,u))}let l=oD(s,i);return rs(l,o,a)}var uD=W({sigmoidCrossEntropy_:lD});function dD(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 Fa((n,a,s)=>{let i=o7(a,[r],!0),o=ce(me(a,"float32"),i);s([n,o]);let l=Ot(L(o,n));return{value:ke(l,[r]),gradFunc:(u,d)=>{let[h,p]=d,c=Fo(u.shape,[r]);return[L(G(u,c),ce(me(h,"float32"),Rn(p))),L(G(u,c),ce(Rn(p),me(h,"float32")))]}}})(e,t)}function pD(e,t,r,n=0,a=3){let s=F(e,"onehotLabels","softmaxCrossEntropy"),i=F(t,"logits","softmaxCrossEntropy"),o=null;if(r!=null&&(o=F(r,"weights","softmaxCrossEntropy")),Vr(s.shape,i.shape,"Error in softmaxCrossEntropy: "),n>0){let u=Se(n),d=Se(1),h=Se(s.shape[1]);s=le(L(s,ce(d,u)),pe(u,h))}let l=dD(s,i);return rs(l,o,a)}var hD=W({softmaxCrossEntropy_:pD});function cD(e,t,r,n){let a=F(e,"indices","sparseFillEmptyRows","int32"),s=F(t,"values","sparseFillEmptyRows"),i=F(r,"denseShape","sparseFillEmptyRows","int32"),o=F(n,"defaultValue","sparseFillEmptyRows",s.dtype);if(a.rank!==2)throw new Error(`Indices should be Tensor2D but received shape
|
|
${a.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:a,values:s,denseShape:i,defaultValue:o},u=B.runKernel(sh,l);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}var fD=W({sparseFillEmptyRows_:cD});function mD(e,t,r){let n=F(e,"inputIndices","sparseReshape","int32"),a=F(t,"inputShape","sparseReshape","int32"),s=F(r,"newShape","sparseReshape","int32");if(n.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape
|
|
${n.shape}`);if(a.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${a.shape}`);if(s.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${s.shape}`);let i={inputIndices:n,inputShape:a,newShape:s},o=B.runKernel(id,i);return{outputIndices:o[0],outputShape:o[1]}}var gD=W({sparseReshape_:mD});function yD(e,t,r){let n=F(e,"data","sparseSegmentMean"),a=F(t,"indices","sparseSegmentMean","int32"),s=F(r,"segmentIds","sparseSegmentMean","int32");if(n.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(a.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
|
|
${a.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
|
|
${s.shape}`);let i={data:n,indices:a,segmentIds:s};return B.runKernel(ih,i)}var AD=W({sparseSegmentMean_:yD});function xD(e,t,r){let n=F(e,"data","sparseSegmentSum"),a=F(t,"indices","sparseSegmentSum","int32"),s=F(r,"segmentIds","sparseSegmentSum","int32");if(n.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(a.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
|
|
${a.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
|
|
${s.shape}`);let i={data:n,indices:a,segmentIds:s};return B.runKernel(oh,i)}var bD=W({sparseSegmentSum_:xD});function vD(e,t,r,n,a,s,i,o){let l=F(e,"data","stringNGrams","string");if(l.dtype!=="string")throw new Error("Data must be of datatype string");if(l.shape.length!==1)throw new Error(`Data must be a vector, saw: ${l.shape}`);let u=F(t,"dataSplits","stringNGrams");if(u.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let d={separator:r,nGramWidths:n,leftPad:a,rightPad:s,padWidth:i,preserveShortSequences:o},h={data:l,dataSplits:u},p=B.runKernel(uh,h,d);return{nGrams:p[0],nGramsSplits:p[1]}}var wD=W({stringNGrams_:vD});function kD(e,t,r=!0){let n=F(e,"input","stringSplit","string"),a=F(t,"delimiter","stringSplit","string");if(n.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${n.shape}`);if(a.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${a.shape}`);let s={skipEmpty:r},i={input:n,delimiter:a},o=B.runKernel(gm,i,s);return{indices:o[0],values:o[1],shape:o[2]}}var ID=W({stringSplit_:kD});function SD(e,t){let r=F(e,"input","stringToHashBucketFast","string"),n={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");let a={input:r};return B.runKernel(ym,a,n)}var TD=W({stringToHashBucketFast_:SD}),ND={fft:Pm,ifft:Wp,rfft:_m,irfft:iA},CD={hammingWindow:rO,hannWindow:E7,frame:R7,stft:iO},Ie={flipLeftRight:dO,grayscaleToRGB:hO,resizeNearestNeighbor:zO,resizeBilinear:PO,rotateWithOffset:fO,cropAndResize:lO,nonMaxSuppression:gO,nonMaxSuppressionAsync:IO,nonMaxSuppressionWithScore:TO,nonMaxSuppressionWithScoreAsync:CO,nonMaxSuppressionPadded:RO,nonMaxSuppressionPaddedAsync:FO,threshold:LO,transform:WO},_7={bandPart:UO,gramSchmidt:jO,qr:qO},ED={absoluteDifference:ZO,computeWeightedLoss:rs,cosineDistance:JO,hingeLoss:eD,huberLoss:rD,logLoss:aD,meanSquaredError:iD,sigmoidCrossEntropy:uD,softmaxCrossEntropy:hD},bp={sparseFillEmptyRows:fD,sparseReshape:gD,sparseSegmentMean:AD,sparseSegmentSum:bD},rf={stringNGrams:wD,stringSplit:ID,stringToHashBucketFast:TD},ns=class extends wk{minimize(e,t=!1,r){let{value:n,grads:a}=this.computeGradients(e,r);if(r!=null){let s=r.map(i=>({name:i.name,tensor:a[i.name]}));this.applyGradients(s)}else this.applyGradients(a);return re(a),t?n:(n.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return n7(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(ns,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var Wm=class extends ns{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 n=B.registeredVariables[t],a=!1;this.accumulatedGrads[r]==null&&(this.accumulatedGrads[r]={originalName:`${t}/accum_grad`,variable:K(()=>at(n).variable(a))}),this.accumulatedUpdates[r]==null&&(this.accumulatedUpdates[r]={originalName:`${t}/accum_var`,variable:K(()=>at(n).variable(a))});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;K(()=>{let l=le(L(i,this.rho),L(At(s),1-this.rho)),u=L(pe(Er(le(o,this.epsilon)),Er(le(i,this.epsilon))),s),d=le(L(o,this.rho),L(At(u),1-this.rho));i.assign(l),o.assign(d);let h=le(L(u,-this.learningRate),n);n.assign(h)})}),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(n=>({originalName:n.name,variable:n.tensor.variable(r)})),this.accumulatedUpdates=e.slice(t,t*2).map(n=>({originalName:n.name,variable:n.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)}};Wm.className="Adadelta";Ui(Wm);var Vm=class extends ns{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 n=B.registeredVariables[t];this.accumulatedGrads[r]==null&&(this.accumulatedGrads[r]={originalName:`${t}/accumulator`,variable:K(()=>dd(n.shape,this.initialAccumulatorValue).variable(!1))});let a=Array.isArray(e)?e[r].tensor:e[t];if(a==null)return;let s=this.accumulatedGrads[r].variable;K(()=>{let i=le(s,At(a));s.assign(i);let o=le(L(pe(a,Er(le(i,B.backend.epsilon()))),-this.learningRate),n);n.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)}};Vm.className="Adagrad";Ui(Vm);var Um=class extends ns{constructor(e,t,r,n=null){super(),this.learningRate=e,this.beta1=t,this.beta2=r,this.epsilon=n,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],K(()=>{this.accBeta1=Se(t).variable(),this.accBeta2=Se(r).variable()}),n==null&&(this.epsilon=B.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(r=>r.name):Object.keys(e);K(()=>{let r=ce(1,this.accBeta1),n=ce(1,this.accBeta2);t.forEach((a,s)=>{let i=B.registeredVariables[a],o=!1;this.accumulatedFirstMoment[s]==null&&(this.accumulatedFirstMoment[s]={originalName:`${a}/m`,variable:K(()=>at(i).variable(o))}),this.accumulatedSecondMoment[s]==null&&(this.accumulatedSecondMoment[s]={originalName:`${a}/v`,variable:K(()=>at(i).variable(o))});let l=Array.isArray(e)?e[s].tensor:e[a];if(l==null)return;let u=this.accumulatedFirstMoment[s].variable,d=this.accumulatedSecondMoment[s].variable,h=le(L(u,this.beta1),L(l,1-this.beta1)),p=le(L(d,this.beta2),L(At(l),1-this.beta2)),c=pe(h,r),f=pe(p,n);u.assign(h),d.assign(p);let m=le(L(pe(c,le(Er(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),K(()=>{this.accBeta1.assign(Ls(this.beta1,this.iterations_+1)),this.accBeta2.assign(Ls(this.beta2,this.iterations_+1))});let t=e.length/2,r=!1;this.accumulatedFirstMoment=e.slice(0,t).map(n=>({originalName:n.name,variable:n.tensor.variable(r)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(n=>({originalName:n.name,variable:n.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)}};Um.className="Adam";Ui(Um);var Gm=class extends ns{constructor(e,t,r,n=null,a=0){super(),this.learningRate=e,this.beta1=t,this.beta2=r,this.epsilon=n,this.decay=a,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],K(()=>{this.iteration=Se(0).variable(),this.accBeta1=Se(t).variable()}),n==null&&(this.epsilon=B.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(r=>r.name):Object.keys(e);K(()=>{let r=ce(1,this.accBeta1),n=pe(-this.learningRate,le(L(this.iteration,this.decay),1));t.forEach((a,s)=>{let i=B.registeredVariables[a],o=!1;this.accumulatedFirstMoment[s]==null&&(this.accumulatedFirstMoment[s]={originalName:`${a}/m`,variable:at(i).variable(o)}),this.accumulatedWeightedInfNorm[s]==null&&(this.accumulatedWeightedInfNorm[s]={originalName:`${a}/v`,variable:at(i).variable(o)});let l=Array.isArray(e)?e[s].tensor:e[a];if(l==null)return;let u=this.accumulatedFirstMoment[s].variable,d=this.accumulatedWeightedInfNorm[s].variable,h=le(L(u,this.beta1),L(l,1-this.beta1)),p=L(d,this.beta2),c=rr(l),f=ts(p,c);u.assign(h),d.assign(f);let m=le(L(pe(n,r),pe(h,le(f,this.epsilon))),i);i.assign(m)}),this.iteration.assign(le(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)}};Gm.className="Adamax";Ui(Gm);var kh=class extends ns{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 n=Array.isArray(e)?e[r].tensor:e[t];if(n==null)return;let a=B.registeredVariables[t];K(()=>{let s=le(L(this.c,n),a);a.assign(s)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=fr(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)}};kh.className="SGD";Ui(kh);var jm=class extends kh{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 n=B.registeredVariables[t];this.accumulations[r]==null&&(this.accumulations[r]={originalName:`${t}/momentum`,variable:K(()=>at(n).variable(!1))});let a=this.accumulations[r].variable,s=Array.isArray(e)?e[r].tensor:e[t];s!=null&&K(()=>{let i,o=le(L(this.m,a),s);this.useNesterov?i=le(L(this.c,le(s,L(o,this.m))),n):i=le(L(this.c,o),n),a.assign(o),n.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)}};jm.className="Momentum";Ui(jm);var Hm=class extends ns{constructor(e,t=.9,r=0,n=null,a=!1){if(super(),this.learningRate=e,this.decay=t,this.momentum=r,this.epsilon=n,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=a,n==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 n=B.registeredVariables[t],a=!1;this.accumulatedMeanSquares[r]==null&&(this.accumulatedMeanSquares[r]={originalName:`${t}/rms`,variable:K(()=>at(n).variable(a))}),this.accumulatedMoments[r]==null&&(this.accumulatedMoments[r]={originalName:`${t}/momentum`,variable:K(()=>at(n).variable(a))}),this.accumulatedMeanGrads[r]==null&&this.centered&&(this.accumulatedMeanGrads[r]={originalName:`${t}/mg`,variable:K(()=>at(n).variable(a))});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;K(()=>{let l=le(L(i,this.decay),L(At(s),1-this.decay));if(this.centered){let u=this.accumulatedMeanGrads[r].variable,d=le(L(u,this.decay),L(s,1-this.decay)),h=pe(L(s,this.learningRate),Er(ce(l,le(At(d),this.epsilon)))),p=le(L(o,this.momentum),h);i.assign(l),u.assign(d),o.assign(p);let c=ce(n,p);n.assign(c)}else{let u=le(L(i,this.decay),L(At(s),1-this.decay)),d=le(L(o,this.momentum),pe(L(s,this.learningRate),Er(le(u,this.epsilon))));i.assign(u),o.assign(d);let h=ce(n,d);n.assign(h)}})}),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(n=>({originalName:n.name,variable:n.tensor.variable(r)})),this.accumulatedMoments=e.slice(t,t*2).map(n=>({originalName:n.name,variable:n.tensor.variable(r)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(n=>({originalName:n.name,variable:n.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)}};Hm.className="RMSProp";Ui(Hm);var ks=class{static sgd(e){return new kh(e)}static momentum(e,t,r=!1){return new jm(e,t,r)}static rmsprop(e,t=.9,r=0,n=null,a=!1){return new Hm(e,t,r,n,a)}static adam(e=.001,t=.9,r=.999,n=null){return new Um(e,t,r,n)}static adadelta(e=.001,t=.95,r=null){return new Wm(e,t,r)}static adamax(e=.002,t=.9,r=.999,n=null,a=0){return new Gm(e,t,r,n,a)}static adagrad(e,t=.1){return new Vm(e,t)}},go={sgd:ks.sgd,momentum:ks.momentum,adadelta:ks.adadelta,adagrad:ks.adagrad,rmsprop:ks.rmsprop,adamax:ks.adamax,adam:ks.adam},RD=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function fA(){return new Promise(e=>RD(()=>e()))}var N={};Le(N,{ERF_A1:()=>WD,ERF_A2:()=>VD,ERF_A3:()=>UD,ERF_A4:()=>GD,ERF_A5:()=>jD,ERF_P:()=>BD,PARALLELIZE_THRESHOLD:()=>mA,SELU_SCALE:()=>O7,SELU_SCALEALPHA:()=>z7,applyActivation:()=>Lm,assertAndGetBroadcastShape:()=>bt,assertAxesAreInnerMostDims:()=>VP,assertParamsConsistent:()=>MD,assignToTypedArray:()=>YD,axesAreInnerMostDims:()=>H2,calculateShapes:()=>hk,checkEinsumDimSizes:()=>nL,checkPadOnDimRoundingMode:()=>Gr,combineLocations:()=>a7,complexWithEvenIndex:()=>KD,complexWithOddIndex:()=>XD,computeConv2DInfo:()=>yh,computeConv3DInfo:()=>_k,computeDefaultPad:()=>P2,computeDilation2DInfo:()=>o$,computeOptimalWindowSize:()=>$D,computeOutAndReduceShapes:()=>s7,computeOutShape:()=>FD,computePool2DInfo:()=>Pk,computePool3DInfo:()=>l$,convertConv2DDataFormat:()=>zk,decodeEinsumEquation:()=>tL,eitherStridesOrDilationsAreOne:()=>Pa,expandShapeToKeepDim:()=>Fo,exponent:()=>QD,exponents:()=>JD,fromStringArrayToUint8:()=>IL,fromUint8ToStringArray:()=>kL,getAxesPermutation:()=>i7,getBroadcastDims:()=>lk,getComplexWithIndex:()=>ZD,getEinsumComputePath:()=>aL,getEinsumPermutation:()=>rL,getFusedBiasGradient:()=>Dm,getFusedDyActivation:()=>Om,getImageCenter:()=>PD,getInnerMostAxes:()=>UP,getPermuted:()=>zD,getReductionAxes:()=>Zt,getReshaped:()=>_D,getReshapedPermuted:()=>OD,getSliceBeginCoords:()=>DD,getSliceSize:()=>LD,getSparseFillEmptyRowsIndicesDenseShapeMismatch:()=>lL,getSparseFillEmptyRowsNegativeIndexErrorMessage:()=>uL,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:()=>dL,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:()=>cL,getSparseReshapeInputOutputMismatchErrorMessage:()=>mL,getSparseReshapeInputOutputMultipleErrorMessage:()=>fL,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:()=>pL,getSparseReshapeNegativeOutputDimErrorMessage:()=>hL,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:()=>xL,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:()=>gL,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:()=>yL,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:()=>AL,getUndoAxesPermutation:()=>q2,isIdentityPermutation:()=>sL,log:()=>_R,mergeRealAndImagArrays:()=>HD,prepareAndValidate:()=>pk,prepareSplitSize:()=>oL,segment_util:()=>D7,shouldFuse:()=>Bm,slice_util:()=>zt,splitRealAndImagArrays:()=>qD,tupleValuesAreOne:()=>zs,upcastType:()=>Cr,validateInput:()=>S2,validateUpdateShape:()=>I2,warn:()=>Ss});function MD(e,t){let r=e[0].length;e.forEach((a,s)=>{P(a.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 n=e[0];e.forEach((a,s)=>{for(let i=0;i<r;i++)P(i===t||a[i]===n[i],()=>`Error in concat${r}D: Shape of tensors[${s}] (${a}) does not match the shape of the rest (${n}) along the non-concatenated axis ${s}.`)})}function FD(e,t){let r=e[0].slice();for(let n=1;n<e.length;n++)r[t]+=e[n][t];return r}var mA=30;function $D(e){return e<=mA?e:ff(e,Math.floor(Math.sqrt(e)))}function PD(e,t,r){let n=r*(typeof e=="number"?e:e[0]),a=t*(typeof e=="number"?e:e[1]);return[n,a]}function _D(e,t,r,n=!0){let a=[];if(n)a=a.concat(t.slice(0)),a.push(e[0]/r),a=a.concat(e.slice(1));else{a=a.concat(e[0]);let s=t.length;for(let i=0;i<s;++i)a=a.concat([e[i+1]/t[i],t[i]]);a=a.concat(e.slice(s+1))}return a}function zD(e,t,r=!0){let n=[];if(r){n.push(t);for(let a=t+1;a<e;++a)a<=2*t?(n.push(a),n.push(a-(t+1))):n.push(a)}else{let a=[],s=[];for(let i=1;i<e;++i)i>=t*2+1||i%2===1?s.push(i):a.push(i);n.push(...a),n.push(0),n.push(...s)}return n}function OD(e,t,r,n=!0){let a=[];n?a.push(e[0]/r):a.push(e[0]*r);for(let s=1;s<e.length;++s)s<=t.length?n?a.push(t[s-1]*e[s]):a.push(e[s]/t[s-1]):a.push(e[s]);return a}function DD(e,t){let r=[0];for(let n=0;n<t;++n)r.push(e[n][0]);return r}function LD(e,t,r){let n=e.slice(0,1);for(let a=0;a<r;++a)n.push(e[a+1]-t[a][0]-t[a][1]);return n}var z7=1.7580993408473768,O7=1.0507009873554805,BD=.3275911,WD=.254829592,VD=-.284496736,UD=1.421413741,GD=-1.453152027,jD=1.061405429;function HD(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 n=0;n<r.length;n+=2)r[n]=e[n/2],r[n+1]=t[n/2];return r}function qD(e){let t=new Float32Array(e.length/2),r=new Float32Array(e.length/2);for(let n=0;n<e.length;n+=2)t[n/2]=e[n],r[n/2]=e[n+1];return{real:t,imag:r}}function KD(e){let t=Math.ceil(e.length/4),r=new Float32Array(t),n=new Float32Array(t);for(let a=0;a<e.length;a+=4)r[Math.floor(a/4)]=e[a],n[Math.floor(a/4)]=e[a+1];return{real:r,imag:n}}function XD(e){let t=Math.floor(e.length/4),r=new Float32Array(t),n=new Float32Array(t);for(let a=2;a<e.length;a+=4)r[Math.floor(a/4)]=e[a],n[Math.floor(a/4)]=e[a+1];return{real:r,imag:n}}function ZD(e,t){let r=e[t*2],n=e[t*2+1];return{real:r,imag:n}}function YD(e,t,r,n){e[n*2]=t,e[n*2+1]=r}function JD(e,t){let r=new Float32Array(e/2),n=new Float32Array(e/2);for(let a=0;a<Math.ceil(e/2);a++){let s=(t?2:-2)*Math.PI*(a/e);r[a]=Math.cos(s),n[a]=Math.sin(s)}return{real:r,imag:n}}function QD(e,t,r){let n=(r?2:-2)*Math.PI*(e/t),a=Math.cos(n),s=Math.sin(n);return{real:a,imag:s}}var Q1="->",eL=/->/g,G3=",",j3="...";function tL(e,t){e=e.replace(/\s/g,"");let r=(e.length-e.replace(eL,"").length)/Q1.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 ("${Q1}").`);let[n,a]=e.split(Q1);P(n.indexOf(j3)===-1,()=>`The ellipsis notation ("${j3}") is not supported yet.`);let s=n.split(G3),i=s.length;if(t!==i)throw new Error(`Expected ${i} input tensors, received ${t}`);if(i>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");let o=[];for(let p=0;p<a.length;++p){let c=a[p];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 p=0;p<n.length;++p){let c=n[p];o.indexOf(c)===-1&&c!==G3&&o.push(c)}let l=new Array(s.length);for(let p=0;p<i;++p){if(new Set(s[p].split("")).size!==s[p].length)throw new Error(`Found duplicate axes in input component ${s[p]}. Support for duplicate axes in input is not implemented yet.`);l[p]=[];for(let c=0;c<s[p].length;++c)l[p].push(o.indexOf(s[p][c]))}let u=o.length,d=a.length,h=[];for(let p=d;p<u;++p)h.push(p);return{allDims:o,summedDims:h,idDims:l}}function rL(e,t){let r=new Array(e);r.fill(-1);for(let a=0;a<t.length;++a)r[t[a]]=a;let n=[];for(let a=0;a<e;++a)r[a]===-1&&n.push(a);return r=r.filter(a=>a!==-1),{permutationIndices:r,expandDims:n}}function nL(e,t,r){let n=new Array(e);for(let a=0;a<r.length;++a){let s=r[a].shape;for(let i=0;i<t[a].length;++i)n[t[a][i]]===void 0?n[t[a][i]]=s[i]:P(n[t[a][i]]===s[i],()=>`Expected dimension ${n[t[a][i]]} at axis ${i} of input shaped ${JSON.stringify(s)}, but got dimension ${s[i]}`)}}function aL(e,t){let r=e,n=[],a=0;e.length===0&&r.push(-1),a=e.length+1;for(let i=0;i<a;++i)n.push([]);let s=[];for(let i=0;i<r.length;++i){let o=r[i],l=iL(t,o);for(let u of l)s.indexOf(u)===-1&&(n[i].push(u),s.push(u))}return{path:r,steps:n}}function sL(e){return e.every((t,r)=>t===r)}function iL(e,t){let r=[];for(let n=0;n<e.length;++n)(e[n].length===0||e[n].indexOf(t)!==-1||t===-1)&&r.push(n);return r}function oL(e,t,r=0){let n=[];if(typeof t=="number")P(e.shape[r]%t===0,()=>"Number of splits must evenly divide the axis."),n=new Array(t).fill(e.shape[r]/t);else{let a=t.reduce((i,o)=>(o===-1&&(i+=1),i),0);P(a<=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."),n=t}return n}function lL(e){return`Received SparseTensor with denseShape[0] = 0 but
|
|
indices.shape[0] = ${e}`}function uL(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function dL(e,t,r){return`indices(${e}, 0) is invalid: ${t} >= ${r}`}function pL(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function hL(e,t){return`size ${e} must be non-negative, not ${t}`}function cL(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function fL(e,t){let r=Tt(e),n=Tt(t);return`Input to reshape is a SparseTensor with ${r}
|
|
dense values, but the requested shape requires a multiple of ${n}. inputShape=${e} outputShape= ${t}`}function mL(e,t){let r=Tt(e),n=Tt(t);return`Input to reshape is a tensor with ${r} dense values, but the requested shape has ${n}. inputShape=${e} outputShape=${t}`}function gL(){return"segment ids must be >= 0"}function yL(){return"segment ids are not increasing"}function AL(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function xL(e,t,r){return`Bad: indices[${e}] == ${t} out of range [0, ${r})`}var D7={};Le(D7,{collectGatherOpShapeInfo:()=>wL,computeOutShape:()=>vL,segOpComputeOptimalWindowSize:()=>bL});function bL(e,t){let r=!1,n;for(e<=mA?(n=e,r=!0):n=ff(e,Math.floor(Math.sqrt(e)));!r;)n>t||n===e?r=!0:n=ff(e,n+1);return n}function vL(e,t,r){let n=[],a=e.length;for(let s=0;s<a;s++)s!==t?n.push(e[s]):n.push(r);return n}function wL(e,t,r,n){let a=t.shape.length,s=e.shape.length;if(n!==0&&(n<-a||n>a))throw new Error(`Expect batchDims in the range of [-${a}, ${a}], but got ${n}`);if(n<0&&(n+=a),n>s)throw new Error(`batchDims (${n}) must be less than rank(x) (
|
|
${s}).`);if(r<n)throw new Error(`batchDims (${n}) must be less than or equal to axis (${r}).`);for(let h=0;h<n;++h)if(e.shape[h]!==t.shape[h])throw new Error(`x.shape[${h}]: ${e.shape[h]} should be equal to indices.shape[${h}]: ${t.shape[h]}.`);let i=e.shape[r],o=[],l=1,u=1,d=1;for(let h=0;h<n;++h)o.push(e.shape[h]),l*=e.shape[h];for(let h=n;h<r;h++)o.push(e.shape[h]),u*=e.shape[h];for(let h=n;h<a;h++)o.push(t.shape[h]);for(let h=r+1;h<s;h++)o.push(e.shape[h]),d*=e.shape[h];return{batchSize:l,sliceSize:d,outerSize:u,dimSize:i,outputShape:o}}function kL(e){try{return e.map(t=>Af(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function IL(e){return e.map(t=>hh(t))}var qn={};Le(qn,{nonMaxSuppressionV3Impl:()=>M7,nonMaxSuppressionV4Impl:()=>F7,nonMaxSuppressionV5Impl:()=>$7,whereImpl:()=>v7});var Ga=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Ga.prototype)}},la=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,la.prototype)}},q=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,q.prototype)}},Ve=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Ve.prototype)}},L7=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,L7.prototype)}},B7=class{constructor(e){this.maxEntries=e||100,this.cache=new Map}get(e){let t;return this.cache.has(e)&&(t=this.cache.get(e),this.cache.delete(e),this.cache.set(e,t)),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxEntries){let r=this.cache.keys().next().value;this.cache.delete(r)}this.cache.set(e,t)}getMaxEntries(){return this.maxEntries}setMaxEntries(e){if(e<0)throw new Error(`The maxEntries of LRU caches must be at least 0, but got ${e}.`);if(this.maxEntries>e)for(let t=0;t<this.maxEntries-e;t++){let r=this.cache.keys().next().value;this.cache.delete(r)}this.maxEntries=e}};function Po(e,t){if(Array.isArray(e)){let r=[];for(let n=0;n<t;n++)r=r.concat(e);return r}else{let r=new Array(t);return r.fill(e),r}}function Ta(e,t){if(!e)throw new L7(t)}function H3(e,t){let r=0;for(let n of e)n===t&&r++;return r}function en(e){return e.length===1?e[0]:e}function It(e){return Array.isArray(e)?e:[e]}function ja(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 bo(e){return e.length<=1||e.indexOf("_")===-1?e:e.replace(/[_]+(\w|$)/g,(t,r)=>r.toUpperCase())}var Bn={};function gA(e){if(e==null)return null;let t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function ky(e){if(!(e==null||typeof e!="object"))if(Array.isArray(e))e.forEach(t=>ky(t));else{let t=Object.keys(e);for(let r of t){let n=e[r];n!=null&&typeof n=="object"&&(!Array.isArray(n)&&n.type==="ndarray"&&typeof n.value=="number"?e[r]=n.value:ky(n))}}}function Ih(e,t={},r={},n="object",a=!1){if(typeof e=="string"){let s=e,i;if(s in r)i=r[s];else if(s in Bn)i=Bn[s];else if(i=t[s],i==null)throw new q(`Unknown ${n}: ${e}. This may be due to one of the following reasons:
|
|
1. The ${n} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
|
|
2. The custom ${n} 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 q(`${n}: 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 Bn?[o,l]=Bn.className:i in t&&([o,l]=t[i]),o==null)throw new q(`Unknown ${n}: ${i}. This may be due to one of the following reasons:
|
|
1. The ${n} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
|
|
2. The custom ${n} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(l!=null){let u={};for(let c of Object.keys(Bn))u[c]=Bn[c];for(let c of Object.keys(r))u[c]=r[c];let d=s.config;d.customObjects=u;let h={...Bn};for(let c of Object.keys(r))Bn[c]=r[c];ky(s.config);let p=l(o,s.config,r,a);return Bn={...h},p}else{let u={...Bn};for(let h of Object.keys(r))Bn[h]=r[h];let d=new o(s.config);return Bn={...u},d}}}function SL(e,t){return e<t?-1:e>t?1:0}function Gc(e,t){return-1*SL(e,t)}function Es(e){if(e==null)return e;let t=[];for(let r of e)t.indexOf(r)===-1&&t.push(r);return t}function TL(e){if(e==null)throw new q(`Invalid value in obj: ${JSON.stringify(e)}`);for(let t in e)if(e.hasOwnProperty(t))return!1;return!0}function Fl(e,t,r){if(r!=null&&e.indexOf(r)<0)throw new q(`${r} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function yA(e,t,r=0,n=1/0){return Ta(r>=0),Ta(n>=r),Array.isArray(e)&&e.length>=r&&e.length<=n&&e.every(a=>typeof a===t)}function mr(e,t){Array.isArray(e)?(w.assert(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((r,n)=>mr(r,`element ${n+1} of ${t}`))):w.assert(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${W7(e)}.`)}function W7(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>W7(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function NL(e,t,r){let n=r!=null?r():w.now(),a;return(...s)=>{let i=r!=null?r():w.now();return i-n<t||(n=i,a=e(...s)),a}}function V7(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}var CL=0;function U7(){return CL++}var jc={};function qm(e=""){return e in jc||(jc[e]=0),jc[e]+=1,e+jc[e].toString()}var EL=["channelsFirst","channelsLast"],RL=["nearest","bilinear"],ML=["valid","same","causal"],FL=["max","avg"],$L=["sum","mul","concat","ave"],iu=new Map;function Gt(e){Fl(EL,"DataFormat",e)}function PL(e){Fl(RL,"InterpolationFormat",e)}function On(e){Fl(ML,"PaddingMode",e)}function G7(e){Fl(FL,"PoolMode",e)}var Rp=[],q3="/";function To(e,t){Rp.push(e);try{let r=t();return Rp.pop(),r}catch(r){throw Rp.pop(),r}}function _L(){return Rp.length===0?"":Rp.join(q3)+q3}function j7(e){if(!q7(e))throw new Error("Not a valid tensor name: '"+e+"'");return _L()+e}function H7(e){if(!q7(e))throw new Error("Not a valid tensor name: '"+e+"'");iu.has(e)||iu.set(e,0);let t=iu.get(e);if(iu.set(e,iu.get(e)+1),t>0){let r=`${e}_${t}`;return iu.set(r,1),r}else return e}var zL=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function q7(e){return!!e.match(zL)}function OL(e){return e===parseInt(e.toString(),10)}function Rs(e,t,r){t==null&&(t=0),r==null&&(r=e.length);let n=1;for(let a=t;a<r;++a)n*=e[a];return n}function Tu(e){if(e.length===0)return Number.NaN;let t=Number.POSITIVE_INFINITY;for(let r=0;r<e.length;r++){let n=e[r];n<t&&(t=n)}return t}function Ws(e){if(e.length===0)return Number.NaN;let t=Number.NEGATIVE_INFINITY;for(let r=0;r<e.length;r++){let n=e[r];n>t&&(t=n)}return t}function ma(e,t){if(t<e)throw new q(`end (${t}) < begin (${e}) is forbidden.`);let r=[];for(let n=e;n<t;++n)r.push(n);return r}var ey;function ar(){return ey==null&&(ey=zn().epsilon()),ey}function ga(){return"channelsLast"}function Km(e,t){return me(e,t)}function Sh(e,t=-1){let r=e.shape.slice();return t<0&&(t=r.length+t+1),r.splice(t,0,1),G(e,r)}function DL(e,t){return K(()=>{if(e.shape.length!==2)throw new q(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);let r=Sh(e,1);return Iy(r,[1,t,1])})}function LL(e){let t=[Rs(e.shape)];return G(e,t)}function BL(e){if(e.rank<=1)throw new q(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);let t=[e.shape[0],Rs(e.shape,1)];return G(e,t)}function No(e,t,r){return K(()=>{switch(e.rank){case 1:return $m(e,t,r);case 2:return sA(e,[t,0],[r,e.shape[1]]);case 3:return Ml(e,[t,0,0],[r,e.shape[1],e.shape[2]]);case 4:return $o(e,[t,0,0,0],[r,e.shape[1],e.shape[2],e.shape[3]]);case 5:return Pe(e,[t,0,0,0,0],[r,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return Pe(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 q(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}})}function ty(e,t,r){return K(()=>{switch(e.rank){case 1:return $m(e,t,r);case 2:return sA(e,[0,t],[e.shape[0],r]);case 3:return Ml(e,[0,0,t],[e.shape[0],e.shape[1],r]);case 4:return $o(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],r]);default:throw new q(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Hc(e,t,r,n){return K(()=>{switch(e.rank){case 1:return $m(e,t,r);case 2:switch(n){case 1:return No(e,t,r);case 2:return ty(e,t,r);default:throw new q(`The axis is not within the rank of the tensor ${n}`)}case 3:switch(n){case 1:return No(e,t,r);case 2:return Ml(e,[0,t,0],[e.shape[0],r,e.shape[2]]);case 3:return ty(e,t,r);default:throw new q(`The axis is not within the rank of the tensor ${n}`)}case 4:switch(n){case 1:return No(e,t,r);case 2:return $o(e,[0,t,0,0],[e.shape[0],r,e.shape[2],e.shape[3]]);case 3:return $o(e,[0,0,t,0],[e.shape[0],e.shape[1],r,e.shape[3]]);case 4:return ty(e,t,r);default:throw new q(`The axis is not within the rank of the tensor ${n}`)}default:throw new q(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function AA(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 K3(e,t){switch(e.rank){case 1:return Vk([e,t]);case 2:return ud([e,t],0);case 3:return Uk([e,t],0);case 4:return Gk([e,t],0);default:throw new q(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function Iy(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new q(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return Vn(e,t)}function Xm(e,t=0,r=1,n,a){return p7(e,t,r,n,a)}function Ea(e,t,r,n){if(e.rank<2||t.rank<2)throw new Ve(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);if(t.rank>=3){let a=e.shape.slice(-1)[0],s=t.shape.slice(-2)[0];if(a!==s)throw new Ve(`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 Bs.matMul({a:e,b:t,transposeA:!1,transposeB:!1,bias:n?Sy(e.rank,n,ga()):null,activation:r});{let a=e.shape.slice(),s=a.pop();e=G(e,[-1,s]);let i=t.shape.slice(),o=i.pop(),l=i.pop(),u=[...i,o],d=Array.from({length:t.rank},(f,m)=>m===0?t.rank-2:m<=t.rank-2?m-1:m);t=G(tt(t,d),[l,-1]);let h=[...a,...u],p=!1,c=!1;return G(Bs.matMul({a:e,b:t,transposeA:p,transposeB:c,bias:n?Sy(e.rank,n,ga()):null,activation:r}),h)}}function K7(e,t,r){return K(()=>(Array.isArray(t)?t=St(t,"int32"):t=me(t,"int32"),ku(e,t,r)))}function Th(e){return L(e,e)}function Sy(e,t,r){let n=t.shape;if(t.rank!==1&&t.rank!==e)throw new q(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(e===5){if(r==="channelsFirst")return n.length===1?G(t,[1,n[0],1,1,1]):G(t,[1,n[3],n[0],n[1],n[2]]);if(r==="channelsLast")return n.length===1?G(t,[1,1,1,1,n[0]]):G(t,[1].concat(n))}else if(e===4){if(r==="channelsFirst")return n.length===1?G(t,[1,n[0],1,1]):G(t,[1,n[2],n[0],n[1]]);if(r==="channelsLast")return n.length===1?G(t,[1,1,1,n[0]]):G(t,[1].concat(n))}else if(e===3){if(r==="channelsFirst")return n.length===1?G(t,[1,n[0],1]):G(t,[1,n[1],n[0]]);if(r==="channelsLast")return n.length===1?G(t,[1,1,n[0]]):G(t,[1].concat(n))}else if(e<3)return t;throw new q(`Unsupported input rank by biasAdd: ${t.rank}`)}function xa(e,t,r){return K(()=>(r==null&&(r=ga()),Gt(r),le(e,Sy(e.rank,t,r))))}function WL(e,t=1){if(t!==1)throw new Ve(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return xh(e)}function VL(e){return K(()=>pe(e,le(rr(e),1)))}function X7(e,t,r,n){return K(()=>S7(e,t,r,n))}function UL(e){return K(()=>{let t=le(.5,L(.2,e));return cn(t,0,1)})}function Nh(e,t,r=!1){return r?e():t()}var GL=["fanIn","fanOut","fanAvg"],jL=["normal","uniform","truncatedNormal"];function HL(e){Fl(GL,"FanMode",e)}function qL(e){Fl(jL,"Distribution",e)}var Kn=class extends ue.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}},xA=class extends Kn{apply(e,t){return Pt(e,t)}};xA.className="Zeros";ue.registerClass(xA);var Zm=class extends Kn{apply(e,t){return hn(e,t)}};Zm.className="Ones";ue.registerClass(Zm);var bA=class extends Kn{constructor(e){if(super(),typeof e!="object")throw new q(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new q(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return K(()=>L(Se(this.value),hn(e,t)))}getConfig(){return{value:this.value}}};bA.className="Constant";ue.registerClass(bA);var vA=class extends Kn{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 cd(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}};vA.className="RandomUniform";ue.registerClass(vA);var wA=class extends Kn{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 Ve(`randomNormal does not support dType ${t}.`);return Xm(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};wA.className="RandomNormal";ue.registerClass(wA);var kA=class extends Kn{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 Ve(`truncatedNormal does not support dType ${t}.`);return zm(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};kA.className="TruncatedNormal";ue.registerClass(kA);var IA=class extends Kn{constructor(e){super(),this.gain=e.gain!=null?e.gain:1}apply(e,t){return K(()=>{if(e.length!==2||e[0]!==e[1])throw new q("Identity matrix initializer can only be used for 2D square matrices.");return L(this.gain,U2(e[0]))})}getConfig(){return{gain:this.gain}}};IA.className="Identity";ue.registerClass(IA);function KL(e,t="channelsLast"){let r,n;if(Gt(t),e.length===2)r=e[0],n=e[1];else if([3,4,5].indexOf(e.length)!==-1){if(t==="channelsFirst"){let a=Rs(e,2);r=e[1]*a,n=e[0]*a}else if(t==="channelsLast"){let a=Rs(e,0,e.length-2);r=e[e.length-2]*a,n=e[e.length-1]*a}}else{let a=Rs(e);r=Math.sqrt(a),n=Math.sqrt(a)}return[r,n]}var nn=class extends Kn{constructor(e){if(super(),e.scale<0)throw new q(`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,HL(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,qL(this.distribution),this.seed=e.seed}apply(e,t){let r=KL(e),n=r[0],a=r[1],s=this.scale;if(this.mode==="fanIn"?s/=Math.max(1,n):this.mode==="fanOut"?s/=Math.max(1,a):s/=Math.max(1,(n+a)/2),this.distribution==="normal"){let i=Math.sqrt(s);if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Ve(`${this.getClassName()} does not support dType ${t}.`);return zm(e,0,i,t,this.seed)}else{let i=Math.sqrt(3*s);return cd(e,-i,i,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}};nn.className="VarianceScaling";ue.registerClass(nn);var Ym=class extends nn{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return nn.className}};Ym.className="GlorotUniform";ue.registerClass(Ym);var Jm=class extends nn{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return nn.className}};Jm.className="GlorotNormal";ue.registerClass(Jm);var Qm=class extends nn{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return nn.className}};Qm.className="HeNormal";ue.registerClass(Qm);var e0=class extends nn{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return nn.className}};e0.className="HeUniform";ue.registerClass(e0);var t0=class extends nn{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return nn.className}};t0.className="LeCunNormal";ue.registerClass(t0);var r0=class extends nn{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return nn.className}};r0.className="LeCunNormal";ue.registerClass(r0);var SA=class extends Kn{constructor(e){if(super(),this.DEFAULT_GAIN=1,this.gain=e.gain==null?this.DEFAULT_GAIN:e.gain,this.seed=e.seed,this.seed!=null)throw new Ve("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return K(()=>{if(e.length<2)throw new Ve("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,n=Xm(r,0,1,"float32"),a=_7.gramSchmidt(n);return e[0]>e[1]&&(a=tt(a)),L(this.gain,a)})}getConfig(){return{gain:this.gain,seed:this.seed}}};SA.className="Orthogonal";ue.registerClass(SA);var X3={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 Z3(e,t={}){return Ih(e,ue.SerializationMap.getMap().classNameMap,t,"initializer")}function _t(e){return gA(e)}function Et(e){if(typeof e=="string"){let t=e in X3?X3[e]:e;if(t==="GlorotNormal")return new Jm;if(t==="GlorotUniform")return new Ym;if(t==="HeNormal")return new Qm;if(t==="HeUniform")return new e0;if(t==="LeCunNormal")return new t0;if(t==="LeCunUniform")return new r0;{let r={};return r.className=t,r.config={},Z3(r)}}else return e instanceof Kn?e:Z3(e)}function Ty(e){return Array.isArray(e)&&Array.isArray(e[0])}function Sf(e){return e.length===0?[]:Array.isArray(e[0])?e:[e]}function je(e){let t;if(Array.isArray(e)){if(e.length!==1)throw new q(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function ft(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(e.length===1)return e=e,e[0];throw new q(`Expected exactly 1 Shape; got ${e.length}`)}else return e}function Tf(e){let t=0;for(let r of e)r.shape.length===0?t+=1:t+=r.shape.reduce((n,a)=>n*a);return t}var Y3="Variable",Z7=class{constructor(e,t="float32",r=Y3,n=!0,a=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=U7(),r=r==null?Y3:r,this.originalName=j7(r),this.name=H7(this.originalName),this.trainable_=n,this.constraint=a,this.val=b7(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),XL(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 XL(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}function Ny(e){return e.map(t=>t.read())}function TA(e){e.forEach(t=>{t[0].write(t[1])})}var Kt=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||{}}},ua=class{constructor(e,t,r,n,a,s,i){this.dtype=e,this.shape=t,this.sourceLayer=r,this.inputs=n,this.callArgs=a,this.outputTensorIndex=i,this.id=U7(),s!=null&&(this.originalName=j7(s),this.name=H7(this.originalName)),this.rank=t.length}},ZL=0,n0=class{constructor(e,t){this.callArgs=t,this.id=ZL++,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}}},YL=0,st=class extends ue.Serializable{constructor(e={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=YL++,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=ja(r)+"_"+qm(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 a=null;e.batchSize!=null&&(a=e.batchSize),r=[a].concat(e.inputShape)}this.batchInputShape=r;let n=e.dtype;n==null&&(n=e.inputDType),n==null&&(n="float32"),this.dtype=n}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 la(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new q(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return en(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return en(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new Ga(`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 Ga(`Layer ${this.name} is not connected, no input to return.`);return en(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new Ga(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new Ga(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return en(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 q(`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 n=e[r],a=t[r];if(a==null)continue;let s=n.rank;if(a.ndim!=null&&s!==a.ndim)throw new q(`Input ${r} is incompatible with layer ${this.name}: expected ndim=${a.ndim}, found ndim=${s}`);if(a.maxNDim!=null&&s>a.maxNDim)throw new q(`Input ${r} is incompatible with layer ${this.name}: expected max_ndim=${a.maxNDim}, found ndim=${s}`);if(a.minNDim!=null&&s<a.minNDim)throw new q(`Input ${r} is incompatible with layer ${this.name}: expected min_ndim=${a.minNDim}, found ndim=${s}.`);if(a.dtype!=null&&n.dtype!==a.dtype)throw new q(`Input ${r} is incompatible with layer ${this.name} : expected dtype=${a.dtype}, found dtype=${n.dtype}.`);if(a.axes){let i=n.shape;for(let o in a.axes){let l=Number(o),u=a.axes[o],d=l>=0?i[l]:i[i.length+l];if(u!=null&&[u,null].indexOf(d)===-1)throw new q(`Input ${r} is incompatible with layer ${this.name}: expected axis ${l} of input shape to have value ${u} but got shape ${i}.`)}}if(a.shape!=null)for(let i=0;i<a.shape.length;++i){let o=a.shape[i],l=n.shape[i];if(o!=null&&l!=null&&o!==l)throw new q(`Input ${r} is incompatible with layer ${this.name}: expected shape=${a.shape}, found shape=${n.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),n=!0;for(let s of r)if(!(s instanceof ua)){n=!1;break}let a=!0;for(let s of r)if(s instanceof ua){a=!1;break}if(n===a)throw new q("Arguments to apply() must be all SymbolicTensors or all Tensors");return To(this.name,()=>{if(!this.built){this.assertInputCompatibility(e);let s=[];for(let i of It(e))s.push(i.shape);this.build(en(s)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&a&&(this._refCount=1)}if(this.assertInputCompatibility(e),a){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=en(o),this.activityRegularizer!=null)throw new Ve("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return s}else{let s=JL(e),i=this.computeOutputShape(s),o,l=QL(e);if(this.warnOnIncompatibleInputShape(Array.isArray(e)?s[0]:s),i!=null&&i.length>0&&Array.isArray(i[0])?o=i.map((u,d)=>new ua(l,u,this,It(e),t,this.name,d)):o=new ua(l,i,this,It(e),t,this.name),this.addInboundNode(e,o,null,null,s,i,t),this._refCount++,this.activityRegularizer!=null)throw new Ve("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,n)=>{r!=null&&e[n]!=null&&e[n]!==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 Ga(`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 Ga(`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 la(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return Tf(this.weights)}build(e){this.built=!0}getWeights(e=!1){return Ny(e?this.trainableWeights:this.weights)}setWeights(e){K(()=>{let t=this.weights;if(t.length!==e.length)throw new q(`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=[],n=Ny(t);for(let a=0;a<n.length;++a){let s=n[a],i=t[a],o=e[a];if(!w.arraysEqual(s.shape,o.shape))throw new q(`Layer weight shape ${s.shape} not compatible with provided weight shape ${o.shape}`);r.push([i,o])}TA(r)})}addWeight(e,t,r,n,a,s,i,o){if(this._addedWeightNames.indexOf(e)!==-1)throw new q(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),r==null&&(r="float32"),this.fastWeightInitDuringBuild&&(n=o!=null?o():Et("zeros"));let l=n.apply(t,r),u=new Z7(l,r,e,s,i);return l.dispose(),a!=null&&this.addLoss(()=>a.apply(u.read())),s==null&&(s=!0),s?this._trainableWeights.push(u):this._nonTrainableWeights.push(u),u}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){e==null||Array.isArray(e)&&e.length===0||(e=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,n,a,s,i=null){let o=It(e);t=It(t),r=It(r),n=It(n),a=Sf(a),s=Sf(s);let l=[],u=[],d=[];for(let h of o)l.push(h.sourceLayer),u.push(h.nodeIndex),d.push(h.tensorIndex);new n0({outboundLayer:this,inboundLayers:l,nodeIndices:u,tensorIndices:d,inputTensors:o,outputTensors:t,inputMasks:r,outputMasks:n,inputShapes:a,outputShapes:s},i);for(let h=0;h<t.length;h++)t[h].sourceLayer=this,t[h].nodeIndex=this.inboundNodes.length-1,t[h].tensorIndex=h}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 JL(e){e=It(e);let t=[];for(let r of e)t.push(r.shape);return en(t)}function QL(e){return"float32"}function Y7(e,t,r){if((t==null||r!=null&&r>0)&&(t=e.sourceLayer,r=e.nodeIndex),t.inboundNodes.length===0)return[e];{let n=t.inboundNodes[r];if(n.inboundLayers.length===0)return n.inputTensors;{let a=[];for(let s=0;s<n.inboundLayers.length;s++){let i=n.inputTensors[s],o=n.inboundLayers[s],l=n.nodeIndices[s],u=Y7(i,o,l);for(let d of u)a.indexOf(d)===-1&&a.push(d)}return a}}}var gd=class extends st{constructor(e){if(super({dtype:e.dtype,name:e.name!=null?e.name:qm("input").toString()}),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 q("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 q("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(e.batchSize!=null)throw new q("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 n=new ua(this.dtype,this.batchInputShape,this,[],{},this.name);n.nodeIndex=0,n.tensorIndex=0,new n0({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[n],outputTensors:[n],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new q(`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}}};gd.className="InputLayer";ue.registerClass(gd);function J7(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 q("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 gd({batchInputShape:t,name:e.name,dtype:r,sparse:e.sparse}).inboundNodes[0].outputTensors[0]}function eB(e,t){if(e.dtype==null||e.dtype===t.dtype)return t;try{return me(t,e.dtype)}catch(r){throw new q(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${e.name}' (${e.dtype}).`)}}var ko=class{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof ko)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]=eB(e,t),this.name2Id[e.name]=e.id,r!=null&&(this.id2Mask[e.id]=r);else throw new q(`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 ua){if(this.id2Value[e.id]==null)throw new q(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}else{let t=this.name2Id[e];if(t==null)throw new q(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof ua){if(this.id2Value[e.id]==null)throw new q(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}else{let t=this.name2Id[e];if(t==null)throw new q(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){this.id2Mask!=null&&re(this.id2Mask)}},Nf=new B7,Cf=new B7;function tB(e){Nf!=null&&Nf.setMaxEntries(e),Cf!=null&&Cf.setMaxEntries(e)}function vp(e,t,r,n){let a=r==null?!1:r.training,s=Array.isArray(e),i=s?e:[e],o=i.map(f=>f.name),l=[],u=t.names();for(let f of o)u.indexOf(f)!==-1?l.push(t.getValue(f)):l.push(null);n!=null&&(n.maxNumTensors=-1/0,n.minNumTensors=1/0);let d=o.join(",")+"|"+t.names().join(","),h=Nf.get(d),p;if(h==null){let f=rB(i,t);h=f.sorted,p=f.recipientCounts,Nf.put(d,h),Cf.put(d,p)}p={},a||Object.assign(p,Cf.get(d));let c=new ko(t);for(let f=0;f<h.length;++f){if(n!=null){let R=vf().numTensors;R>n.maxNumTensors&&(n.maxNumTensors=R),R<n.minNumTensors&&(n.minNumTensors=R)}let m=h[f],g=m.sourceLayer;if(g instanceof gd)continue;let y=[],A=[],x=[],b=!1;for(let R of m.inputs){let _=c.getValue(R),M=c.getMask(R);y.push(_),A.push(M),M!=null&&(b=!0),a||(p[R.name]--,p[R.name]===0&&!t.hasKey(R)&&o.indexOf(R.name)===-1&&!_.isDisposed&&R.sourceLayer.stateful!==!0&&x.push(_))}b&&(r=r||{},r.mask=A[0]);let v=It(g.apply(y,r)),S=null;g.supportsMasking&&(S=g.computeMask(y,A));let T=aB(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(S)?S[0]:S);let _=o.indexOf(E[R].name);_!==-1&&(l[_]=v[R])}a||re(x)}return c.disposeMasks(),s?l:l[0]}function rB(e,t){w.assert(e!=null&&e.length>0,()=>"Expected at least one fetch, got none");let r=[],n={};if(e.length===1){let a=J3(e[0],t);r=a.sorted,n=a.recipientMap}else{let a=new Set;for(let s of e){let{sorted:i,recipientMap:o}=J3(s,t);for(let l of i)a.has(l.name)||(r.push(l),a.add(l.name));for(let l in o)n[l]==null&&(n[l]=new Set),o[l].forEach(u=>n[l].add(u))}}return{sorted:r,recipientCounts:nB(n)}}function nB(e){let t={};for(let r in e)t[r]=e[r].size;return t}function J3(e,t){let r=new Set,n=[],a={};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(),n.push(o),r.add(o.name),l&&i.pop();else{i.push(s.length-1);for(let u of o.inputs)a[u.name]==null&&(a[u.name]=new Set),a[u.name].add(o.name),!r.has(u.name)&&s.push(u)}}return{sorted:n,recipientMap:a}}function aB(e){let t;if(e.sourceLayer.inboundNodes.length===1)t=e.sourceLayer.output;else{let r=null;for(let n=0;n<e.sourceLayer.inboundNodes.length;++n)for(let a of e.sourceLayer.inboundNodes[n].outputTensors)if(a.id===e.id){r=n;break}t=e.sourceLayer.getOutputAt(r)}return t}var sB=Y();sB.registerFlag("TOPOLOGICAL_SORT_CACHE_MAX_ENTRIES",()=>100,tB);var Q7={kernelName:Vo,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(e,wh(me(r,"float32"),-1))}}},iB={kernelName:_u,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>{let n=At(me(r,"float32")),a=Er(ce(Se(1),n));return Ot(pe(e,a))}}}},oB={kernelName:zu,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>{let n=Er(ce(At(me(r,"float32")),1));return pe(e,n)}}}},lB={kernelName:Ja,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t,a=bt(r.shape,n.shape);return{a:()=>{let s=e,i=Zt(r.shape,a);return i.length>0&&(s=ke(s,i)),G(s,r.shape)},b:()=>{let s=e,i=Zt(n.shape,a);return i.length>0&&(s=ke(s,i)),G(s,n.shape)}}}},uB={kernelName:Ks,saveAllInputs:!0,gradFunc:(e,t)=>{let r={};return t.forEach((n,a)=>{r[a]=()=>e.clone()}),r}},dB={kernelName:Xs,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>at(r)}}},pB={kernelName:Lu,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>at(r)}}},hB={kernelName:Bu,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>pe(e,Er(ce(Se(1),At(me(r,"float32")))))}}},cB={kernelName:Wu,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>{let n=Er(le(Se(1),At(me(r,"float32"))));return pe(e,n)}}}},fB={kernelName:Gu,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t,a=bt(r.shape,n.shape);return{a:()=>{let s=le(At(r),At(n)),i=L(e,pe(n,s)),o=Zt(r.shape,a);return o.length>0&&(i=ke(i,o)),G(i,r.shape)},b:()=>{let s=le(At(r),At(n)),i=Ot(L(e,pe(r,s))),o=Zt(n.shape,a);return o.length>0&&(i=ke(i,o)),G(i,n.shape)}}}},mB={kernelName:Vu,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>pe(e,le(At(me(r,"float32")),1))}}},gB={kernelName:Uu,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>pe(e,ce(Se(1),At(me(r,"float32"))))}}};function yB(e,t,r,n,a,s){let i=F(e,"dy","avgPool3dGrad"),o=F(t,"input","avgPool3dGrad"),l=i,u=o,d=!1;o.rank===4&&(d=!0,l=G(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),u=G(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(u.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${u.rank}.`),Gr("avgPool3dGrad",a,s);let h={dy:l,input:u},p={filterSize:r,strides:n,pad:a,dimRoundingMode:s},c=B.runKernel(Xf,h,p);return d?G(c,[c.shape[1],c.shape[2],c.shape[3],c.shape[4]]):c}var AB=W({avgPool3dGrad_:yB}),xB={kernelName:Kp,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{filterSize:a,strides:s,pad:i,dimRoundingMode:o}=r;return{x:()=>AB(e,n,a,s,i,o)}}};function bB(e,t,r,n,a){let s=F(e,"dy","avgPoolGrad"),i=F(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,u=!1;i.rank===3&&(u=!0,o=G(i,[1,i.shape[0],i.shape[1],i.shape[2]]),l=G(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 d={dy:l,input:o},h={filterSize:r,strides:n,pad:a},p=B.runKernel(Kf,d,h);return u?G(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var vB=W({avgPoolGrad_:bB}),wB={kernelName:Zs,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{filterSize:a,strides:s,pad:i}=r;return{x:()=>vB(e,n,a,s,i)}}},kB={kernelName:Ys,inputsToSave:["a","b"],gradFunc:(e,t,r)=>{let[n,a]=t,{transposeA:s,transposeB:i}=r;return!s&&!i?{a:()=>Je(e,a,!1,!0),b:()=>Je(n,e,!0,!1)}:!s&&i?{a:()=>Je(e,a,!1,!1),b:()=>Je(e,n,!0,!1)}:s&&!i?{a:()=>Je(a,e,!1,!0),b:()=>Je(n,e,!1,!1)}:{a:()=>Je(a,e,!0,!0),b:()=>Je(e,n,!0,!0)}}},IB={kernelName:Uo,gradFunc:(e,t,r)=>{let{blockShape:n,crops:a}=r;return{x:()=>Mm(e,n,a)}}},SB={kernelName:Mw,gradFunc:(e,t,r)=>{let n=r,a=n.inputShape,s=n.shape,i=Array.from(s);for(let l=a.length-1;l>=0;l--)if(a[l]===s[l])i[l]=1;else if(a[l]!==1)throw new Error(`broadcastTo(): [${a}] 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)}}},TB={kernelName:Js,gradFunc:e=>({x:()=>e.clone()})},NB={kernelName:Qs,gradFunc:e=>({x:()=>at(e)})},CB={kernelName:Qa,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{clipValueMin:a,clipValueMax:s}=r;return{x:()=>Wr(fa(El(n,a),Rl(n,s)),e,at(e))}}},EB={kernelName:Zp,inputsToSave:["x"],gradFunc:Q7.gradFunc},RB={kernelName:Go,saveAllInputs:!0,gradFunc:(e,t,r)=>{let n=t.map(o=>o.shape),{axis:a}=r,s=Gn(a,t[0].shape)[0],i=n.map(o=>o[s]);return Xt(e,i,s).map(o=>()=>o)}},MB={kernelName:ei,inputsToSave:["x","filter"],gradFunc:(e,t,r)=>{let[n,a]=t,{dilations:s,strides:i,pad:o,dataFormat:l}=r;return P(zs(s),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`),{x:()=>D2(n.shape,e,a,i,o,l),filter:()=>hA(n,e,a.shape,i,o,l)}}},FB={kernelName:ti,inputsToSave:["dy","filter"],gradFunc:(e,t,r)=>{let[n,a]=t,{strides:s,pad:i,dataFormat:o,dimRoundingMode:l}=r;return{dy:()=>Os(e,a,s,i,o,1,l),filter:()=>hA(e,n,a.shape,s,i,o,l)}}};function $B(e,t,r,n,a){let s=e;e.rank===4&&(s=G(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let i=t;i.rank===4&&(i=G(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:n,pad:a,filterShape:r};return B.runKernel(Qf,o,l)}var PB=W({conv3DBackpropFilter_:$B}),_B={kernelName:Yp,inputsToSave:["x","filter"],gradFunc:(e,t,r)=>{let{dilations:n,strides:a,pad:s}=r;P(zs(n),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${n}'`);let[i,o]=t;return{x:()=>jk(i.shape,e,o,a,s),filter:()=>PB(i,e,o.shape,a,s)}}},zB={kernelName:ri,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(Ot(nA(me(r,"float32"))),e)}}},OB={kernelName:ni,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(aA(me(r,"float32")),e)}}},DB={kernelName:ai,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{axis:a,exclusive:s,reverse:i}=r;return{x:()=>{let o=i7([a],n.rank),l=V2(e,a,s,!i);return o!=null&&(l=tt(l,o)),l}}}},LB={kernelName:si,inputsToSave:["x","filter"],gradFunc:(e,t,r)=>{let{dilations:n,strides:a,pad:s,dimRoundingMode:i}=r,o=n==null?[1,1]:n;P(zs(o),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`);let[l,u]=t;return P(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),P(u.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${u.rank}.`),P(l.shape[3]===u.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${u.shape[2]}.`),P(Pa(a,o),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${a} and dilations '${o}'.`),Gr("depthwiseConv2d",s,i),{x:()=>C7(l.shape,e,u,a,s,o,i),filter:()=>N7(l,e,u.shape,a,s,o,i)}}},BB={kernelName:Jp,inputsToSave:["x","filter"],gradFunc:(e,t,r)=>{let[n,a]=t,s={x:n,filter:a,dy:e},i={x:n,filter:a,dy:e};return{x:()=>B.runKernel(mf,s,r),filter:()=>B.runKernel(gf,i,r)}}},WB={kernelName:oi,outputsToSave:[!0],gradFunc:(e,t)=>{let[r]=t,n={dy:e,y:r};return{x:()=>B.runKernel(sm,n)}}},VB={kernelName:ju,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t,n=L(Rn(Ot(At(r))),2/Math.sqrt(Math.PI));return{x:()=>L(e,n)}}},UB={kernelName:li,outputsToSave:[!0],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(e,r)}}},GB={kernelName:Xo,inputsToSave:["input"],gradFunc:(e,t)=>{let[r]=t;return{input:()=>G(e,r.shape)}}},jB={kernelName:Zo,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(e,Rn(r))}}},HB={kernelName:ui,gradFunc:e=>({x:()=>at(e)})},qB={kernelName:di,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t,a=bt(r.shape,n.shape);return{a:()=>{let s=pe(e,me(n,"float32")),i=Zt(r.shape,a);return i.length>0?G(ke(s,i),r.shape):s},b:()=>{let s=L(e,me(r,"float32")),i=Zt(n.shape,a);i.length>0&&(s=G(ke(s,i),n.shape));let o=At(n);return Ot(pe(s,me(o,"float32")))}}}},KB={kernelName:pi,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,r)=>{let{varianceEpsilon:n}=r,[a,s,i,o]=t,l=o==null?Se(1):o,u=Zt(s.shape,a.shape),d=[];if(s.rank===1){for(let m=0;m<a.shape.length-1;++m)d.push(a.shape[m]);d.push(1)}let h=ce(a,s),p=L(e,l),c=tA(le(i,Se(n))),f=L(L(L(c,c),c),Se(-.5));return{x:()=>s.rank===1?G(L(L(e,Vn(G(c,[1,1,1,s.shape[0]]),d)),l),a.shape):G(L(L(e,c),l),a.shape),mean:()=>{let m=L(L(c,Se(-1)),p);return s.rank===1&&(m=ke(m,u)),G(m,s.shape)},variance:()=>{let m=L(L(f,h),p);return s.rank===1&&(m=ke(m,u)),G(m,s.shape)},scale:()=>{let m=L(h,c),g=L(e,m);return s.rank===1&&(g=ke(g,u)),G(g,s.shape)},offset:()=>{let m=e;return s.rank===1&&(m=ke(m,u)),G(m,s.shape)}}}},XB={kernelName:Jo,inputsToSave:["x","indices"],gradFunc:(e,t,r)=>{let[n,a]=t,{axis:s}=r,i=Gn(s,n.shape)[0];return{x:()=>{let o=n.shape,l=a.size,u=o.slice(0,i),d=u.length,h=o.slice(s,o.length).slice(1),p=h.length,c=Q3(0,d),f=Q3(d+1,d+1+p),m=ev([u,[l],h]),g=G(e,m),y=G(a,[l]),A=ev([[d],c,f]),x=tt(g,A),b=x7(x,y,n.shape[i]),v=q2(A);return b=tt(b,v),b},indices:()=>a}}};function Q3(e,t){let r=[];for(let n=e;n<t;++n)r.push(n);return r}function ev(e){let t=[];for(let r=0;r<e.length;++r)for(let n=0;n<e[r].length;++n)t.push(e[r][n]);return t}var ZB={kernelName:hi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t;return{a:()=>at(r),b:()=>at(n)}}},YB={kernelName:ci,gradFunc:e=>({x:()=>me(e,"float32")})},JB={kernelName:qu,gradFunc:e=>({x:()=>at(e)})},QB={kernelName:Ku,gradFunc:e=>({x:()=>at(e)})},eW={kernelName:Xu,gradFunc:e=>({x:()=>at(e)})},tW={kernelName:fi,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{alpha:a}=r,s=fn(n,0);return{x:()=>Wr(s,e,L(e,a))}}},rW={kernelName:Zu,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>pe(e,le(r,1))}}},nW={kernelName:mi,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>pe(e,me(r,"float32"))}}},aW={kernelName:Fw,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,r)=>{let[n]=t,{axis:a}=r;return{logits:()=>{let s=Rn(n);return ce(e,L(ke(e,a,!0),s))}}}};function sW(e,t,r,n=5,a=1,s=1,i=.5){let o={x:e,y:t,dy:r},l={depthRadius:n,bias:a,alpha:s,beta:i};return B.runKernel(um,o,l)}var iW=W({localResponseNormalizationBackprop_:sW}),oW={kernelName:rh,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,r)=>{let[n,a]=t,{depthRadius:s,bias:i,alpha:o,beta:l}=r;return{x:()=>iW(n,a,e,s,i,o,l)}}};function e4(e,t,r,n){return t.rank<r.rank&&(t=G(t,Fo(t.shape,n))),e.rank<r.rank&&(e=G(e,Fo(e.shape,n))),{x:()=>L(e,me(En(r,t),e.dtype))}}var tv={kernelName:gi,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,r)=>{let n=r,{reductionIndices:a}=n,s=t[0],i=t[1],o=Gn(a,s.shape),l=e4(e,i,s,o);return{x:()=>l.x()}}},lW={kernelName:yi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t;return{a:()=>L(e,me(El(r,n),"float32")),b:()=>L(e,me(G2(r,n),"float32"))}}};function uW(e,t,r,n,a,s,i){let o=F(e,"dy","maxPool3dGrad"),l=F(t,"input","maxPool3dGrad"),u=F(r,"output","maxPool3dGrad"),d=o,h=l,p=u,c=!1;l.rank===4&&(c=!0,d=G(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),h=G(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),p=G(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]])),P(d.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${d.rank}.`),P(h.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${h.rank}.`),P(p.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${p.rank}.`),Gr("maxPool3dGrad",s,i);let f={dy:d,input:h,output:p},m={filterSize:n,strides:a,pad:s,dimRoundingMode:i},g=B.runKernel(pm,f,m);return c?G(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}var dW=W({maxPool3dGrad_:uW}),pW={kernelName:nh,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,r)=>{let[n,a]=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=r;return{x:()=>dW(e,n,a,s,i,o,l)}}};function hW(e,t,r,n,a,s,i){let o=F(e,"dy","maxPoolGrad"),l=F(t,"input","maxPoolGrad"),u=F(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}.`),Gr("maxPoolGrad",s,i);let d={dy:o,input:l,output:u},h={filterSize:n,strides:a,pad:s,dimRoundingMode:i};return B.runKernel(dm,d,h)}var cW=W({maxPoolGrad_:hW}),fW={kernelName:Ai,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,r)=>{let[n,a]=t,{filterSize:s,strides:i,pad:o}=r;return{x:()=>cW(e,n,a,s,i,o)}}},mW={kernelName:xi,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{axis:a}=r,s=Gn(a,n.shape),i=s7(n.shape,s)[1],o=Tt(i);return{x:()=>{let l=n.shape.slice();s.forEach(d=>{l[d]=1});let u=G(e,l);return pe(L(u,hn(n.shape,"float32")),o)}}}},gW={kernelName:bi,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,r)=>{let n=r,{axis:a}=n,[s,i]=t,o=Gn(a,s.shape),l=e4(e,i,s,o);return{x:()=>l.x()}}},yW={kernelName:vi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t;return{a:()=>L(e,me(Rl(r,n),"float32")),b:()=>L(e,me(fn(r,n),"float32"))}}},AW={kernelName:wi,inputsToSave:["x"],gradFunc:(e,t,r)=>{let n=t[0],{paddings:a}=r,s=a.map(i=>i[0]);return{x:()=>Pe(e,s,n.shape)}}},xW={kernelName:Ju,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t,a=bt(r.shape,n.shape);return{a:()=>{let s=Zt(r.shape,a);return s.length>0?G(ke(e,s),r.shape):e},b:()=>{let s=L(e,Ot(bh(pe(r,n)))),i=Zt(n.shape,a);return i.length>0?G(ke(s,i),n.shape):s}}}},bW={kernelName:ki,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t,a=bt(r.shape,n.shape);return{a:()=>{let s=L(e,me(n,"float32")),i=Zt(r.shape,a);return i.length>0?G(ke(s,i),r.shape):s},b:()=>{let s=L(e,me(r,"float32")),i=Zt(n.shape,a);return i.length>0?G(ke(s,i),n.shape):s}}}},vW={kernelName:al,gradFunc:e=>({x:()=>Ot(e)})},wW={kernelName:ul,inputsToSave:["indices"],gradFunc:(e,t)=>{let r=t[0];return{indices:()=>Pt(r.shape,"float32")}}},kW={kernelName:ll,gradFunc:e=>({x:()=>at(e)})},IW={kernelName:dl,saveAllInputs:!0,gradFunc:(e,t,r)=>{let{axis:n}=r;return rn(e,n).map(a=>()=>a)}},rv={kernelName:Ii,inputsToSave:["x"],gradFunc:(e,t,r)=>{let n=t[0],{paddings:a}=r,s=a.map(i=>i[0]);return{x:()=>Pe(e,s,n.shape)}}},SW={kernelName:Si,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{let[r,n,a]=t,s=r,i=n,o=bt(s.shape,i.shape);return{a:()=>{let l=me(i,"float32"),u=L(e,L(l,Ls(s,ce(l,Se(1))))),d=Zt(s.shape,o);return d.length>0&&(u=ke(u,d)),G(u,s.shape)},b:()=>{let l=fn(s,0),u=Wr(l,Mn(s),at(s)),d=L(e,L(a,u)),h=Zt(i.shape,o);return h.length>0&&(d=ke(d,h)),G(d,i.shape)}}}},TW={kernelName:Ti,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{let[r,n]=t,a=fn(r,0);return{x:()=>Wr(a,e,L(e,n)),alpha:()=>{let s=Wr(a,at(e),L(e,r)),i=Zt(n.shape,e.shape);return i.length>0&&(s=ke(s,i)),G(s,n.shape)}}}};function NW(e,t,r){let n=e.shape.slice();n[r]=1;let a=G(t,n),s=If(e,r,!0,!1),i=If(e,r,!0,!0),o=L(s,i);return L(a,o)}function CW(e,t,r){let n=e.shape.length,a=n-r.length,s=N.getAxesPermutation(r,n),i=e;s!=null&&(i=tt(e,s));let o=i.shape.slice(),l=o.splice(n-r.length,r.length).reduce((h,p)=>h*p,1);o.push(l);let u=i.reshape(o),d=NW(u,t,a);if(d=d.reshape(i.shape),s!=null){let h=N.getUndoAxesPermutation(s);d=tt(d,h)}return d}var EW={kernelName:Ni,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{axis:a}=r,s=[];return a==null?s=n.shape.map((i,o)=>o):typeof a=="number"?s=[a]:s=a,{x:()=>CW(n,e,s)}}},RW={kernelName:ii,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t,a=bt(r.shape,n.shape);return{a:()=>{let s=pe(e,me(n,"float32")),i=Zt(r.shape,a);return i.length>0?G(ke(s,i),r.shape):s},b:()=>{let s=L(e,me(r,"float32")),i=Zt(n.shape,a);i.length>0&&(s=G(ke(s,i),n.shape));let o=At(n);return Ot(pe(s,me(o,"float32")))}}}},MW={kernelName:td,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>pe(e,Ot(At(r)))}}},FW={kernelName:Ri,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t,n=L(Rl(r,6),wh(r));return{x:()=>L(e,me(n,"float32"))}}},$W={kernelName:Ci,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(e,me(wh(r),"float32"))}}},PW={kernelName:pl,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>G(e,r.shape)}}},_W={kernelName:Ei,inputsToSave:["images"],gradFunc:(e,t,r)=>{let[n]=t,a={dy:e,images:n};return{images:()=>B.runKernel(mm,a,r)}}},zW={kernelName:rd,inputsToSave:["images"],gradFunc:(e,t,r)=>{let[n]=t,a={dy:e,images:n};return{images:()=>B.runKernel(fm,a,r)}}},OW={kernelName:hl,gradFunc:(e,t,r)=>{let{dims:n}=r,a=Gn(n,e.shape);return{x:()=>$n(e,a)}}},DW={kernelName:cl,gradFunc:e=>({x:()=>at(e)})},LW={kernelName:Mi,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>Ot(pe(e,L(Ls(r,1.5),2)))}}},BW={kernelName:ml,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(Cm(r),e.dtype))}}},WW={kernelName:nd,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>{let n=fn(r,Se(0)),a=Se(z7),s=Se(O7),i=L(e,s),o=L(L(e,a),Rn(me(r,"float32")));return Wr(n,i,o)}}}},VW={kernelName:$i,outputsToSave:[!0],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(e,L(r,ce(Se(1),r)))}}},UW={kernelName:ad,gradFunc:e=>({x:()=>at(e)})},GW={kernelName:Fi,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(km(me(r,"float32")),e)}}},jW={kernelName:yl,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(W2(me(r,"float32")),e)}}},HW={kernelName:gl,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{begin:a,size:s}=r,i=n.shape,[o,l]=vk(n,a,s),u=[];for(let d=0;d<e.rank;d++)u.push([o[d],i[d]-o[d]-l[d]]);return{x:()=>Hn(e,u)}}},qW={kernelName:zi,outputsToSave:[!0],gradFunc:(e,t,r)=>{let[n]=t,{dim:a}=r,s=!0,i=L(e,n);return{logits:()=>ce(i,L(ke(i,[a],s),n))}}},KW={kernelName:sd,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(e,Nr(r))}}},nv={kernelName:Al,gradFunc:(e,t,r)=>{let{blockShape:n,paddings:a}=r;return{x:()=>wm(e,n,a)}}},av={kernelName:xl,gradFunc:(e,t,r)=>{let{axis:n}=r;return{x:()=>kt(e,n)}}},XW={kernelName:Pi,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>pe(e,L(Er(me(r,"float32")),2))}}},ZW={kernelName:od,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(e,L(me(r,"float32"),2))}}},YW={kernelName:Oi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t,a=Se(2);return{a:()=>L(e,L(a,ce(r,n))),b:()=>L(e,L(a,ce(n,r)))}}},JW={kernelName:Wi,gradFunc:e=>({x:()=>at(e)})},QW={kernelName:Di,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[r,n]=t,a=bt(r.shape,n.shape);return{a:()=>{let s=e,i=Zt(r.shape,a);return i.length>0&&(s=ke(s,i)),G(s,r.shape)},b:()=>{let s=e,i=Zt(n.shape,a);return i.length>0&&(s=ke(s,i)),G(Ot(s),n.shape)}}}},eV={kernelName:_i,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,a=n.shape.slice(),{axis:s}=r;Gn(s,n.shape).forEach(l=>{a[l]=1});let i=G(e,a),o=L(i,hn(n.shape,"float32"));return{x:()=>o}}},tV={kernelName:vl,inputsToSave:["x"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>pe(e,At(km(r)))}}},rV={kernelName:Li,outputsToSave:[!0],gradFunc:(e,t)=>{let[r]=t;return{x:()=>L(ce(Se(1),At(r)),e)}}},nV={kernelName:es,inputsToSave:["x"],gradFunc:(e,t,r)=>{let[n]=t,{reps:a}=r;return{x:()=>{let s=at(n);if(n.rank===1)for(let i=0;i<a[0];++i)s=le(s,Pe(e,[i*n.shape[0]],[n.shape[0]]));else if(n.rank===2)for(let i=0;i<a[0];++i)for(let o=0;o<a[1];++o)s=le(s,Pe(e,[i*n.shape[0],o*n.shape[1]],[n.shape[0],n.shape[1]]));else if(n.rank===3)for(let i=0;i<a[0];++i)for(let o=0;o<a[1];++o)for(let l=0;l<a[2];++l)s=le(s,Pe(e,[i*n.shape[0],o*n.shape[1],l*n.shape[2]],[n.shape[0],n.shape[1],n.shape[2]]));else if(n.rank===4)for(let i=0;i<a[0];++i)for(let o=0;o<a[1];++o)for(let l=0;l<a[2];++l)for(let u=0;u<a[3];++u)s=le(s,Pe(e,[i*n.shape[0],o*n.shape[1],l*n.shape[2],u*n.shape[3]],[n.shape[0],n.shape[1],n.shape[2],n.shape[3]]));else throw new Error(`Gradient for tile operation is not implemented for rank-${n.rank} tensors yet.`);return s}}}},aV={kernelName:Bi,gradFunc:(e,t,r)=>{let n=r,{perm:a}=n,s=q2(a);return{x:()=>tt(e,s)}}},sV={kernelName:Il,gradFunc:(e,t,r)=>{let n=r,{axis:a}=n;return{value:()=>lr(e,a)}}},iV={kernelName:dh,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{let[r]=t;return{x:()=>oV(e,r)}}};function oV(e,t){let r=ts(t,at(t)),n=ku(e,r),a=El(t,Se(0,"int32")),s=n.rank-a.rank;for(let o=0;o<s;++o)a=qt(a,o+1);a=fa(a,hn(n.shape,"bool"));let i=at(n);return Wr(a,n,i)}var lV={kernelName:Sl,gradFunc:e=>({x:()=>at(e)})},uV=[Q7,iB,oB,lB,uB,dB,pB,hB,cB,fB,mB,gB,xB,wB,kB,IB,SB,TB,NB,CB,EB,RB,FB,MB,_B,zB,OB,DB,LB,BB,RW,WB,VB,UB,GB,jB,qB,HB,KB,XB,ZB,YB,JB,QB,eW,tW,rW,nW,aW,oW,tv,tv,lW,pW,fW,mW,gW,yW,AW,xW,bW,vW,wW,kW,IW,rv,rv,SW,TW,EW,MW,FW,$W,PW,_W,zW,OW,DW,LW,BW,WW,VW,UW,GW,jW,HW,qW,KW,nv,nv,av,av,XW,YW,ZW,JW,QW,eV,tV,rV,nV,aV,sV,iV,lV];for(let e of uV)$w(e);var t4={};Le(t4,{maxNorm:()=>dV,minMaxNorm:()=>cV,nonNeg:()=>hV,unitNorm:()=>pV});function NA(e,t){return K(()=>Er(ke(L(e,e),t,!0)))}var Ch=class extends ue.Serializable{getConfig(){return{}}},CA=class extends Ch{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 K(()=>{let t=NA(e,this.axis),r=cn(t,0,this.maxValue);return L(e,pe(r,le(ar(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};CA.className="MaxNorm";ue.registerClass(CA);var EA=class extends Ch{constructor(e){super(),this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return K(()=>pe(e,le(ar(),NA(e,this.axis))))}getConfig(){return{axis:this.axis}}};EA.className="UnitNorm";ue.registerClass(EA);var RA=class extends Ch{apply(e){return _a(e)}};RA.className="NonNeg";ue.registerClass(RA);var MA=class extends Ch{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 K(()=>{let t=NA(e,this.axis),r=le(L(this.rate,cn(t,this.minValue,this.maxValue)),L(1-this.rate,t));return L(e,pe(r,le(ar(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};MA.className="MinMaxNorm";ue.registerClass(MA);var sv={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function ir(e){return gA(e)}function iv(e,t={}){return Ih(e,ue.SerializationMap.getMap().classNameMap,t,"constraint")}function or(e){if(e==null)return null;if(typeof e=="string"){let t={className:e in sv?sv[e]:e,config:{}};return iv(t)}else return e instanceof Ch?e:iv(e)}function dV(e){return new CA(e)}function pV(e){return new EA(e)}function hV(){return new RA}function cV(e){return new MA(e)}var r4={};Le(r4,{constant:()=>gV,glorotNormal:()=>kV,glorotUniform:()=>wV,heNormal:()=>IV,heUniform:()=>SV,identity:()=>bV,leCunNormal:()=>TV,leCunUniform:()=>NV,ones:()=>mV,orthogonal:()=>CV,randomNormal:()=>AV,randomUniform:()=>yV,truncatedNormal:()=>xV,varianceScaling:()=>vV,zeros:()=>fV});function fV(){return new xA}function mV(){return new Zm}function gV(e){return new bA(e)}function yV(e){return new vA(e)}function AV(e){return new wA(e)}function xV(e){return new kA(e)}function bV(e){return new IA(e)}function vV(e){return new nn(e)}function wV(e){return new Ym(e)}function kV(e){return new Jm(e)}function IV(e){return new Qm(e)}function SV(e){return new e0(e)}function TV(e){return new t0(e)}function NV(e){return new r0(e)}function CV(e){return new SA(e)}var n4={};Le(n4,{Layer:()=>st,RNN:()=>as,RNNCell:()=>Mh,activation:()=>QU,add:()=>lG,alphaDropout:()=>jG,average:()=>uG,averagePooling1d:()=>Bx,averagePooling2d:()=>Wx,averagePooling3d:()=>Vx,avgPool1d:()=>AG,avgPool2d:()=>bG,avgPool3d:()=>wG,avgPooling1d:()=>xG,avgPooling2d:()=>vG,avgPooling3d:()=>kG,batchNormalization:()=>mG,bidirectional:()=>OG,concatenate:()=>dG,conv1d:()=>GU,conv2d:()=>jU,conv2dTranspose:()=>HU,conv3d:()=>qU,conv3dTranspose:()=>KU,convLstm2d:()=>$G,convLstm2dCell:()=>PG,cropping2D:()=>ZU,dense:()=>eG,depthwiseConv2d:()=>JU,dot:()=>fG,dropout:()=>tG,elu:()=>DU,embedding:()=>oG,flatten:()=>nG,gaussianDropout:()=>GG,gaussianNoise:()=>UG,globalAveragePooling1d:()=>IG,globalAveragePooling2d:()=>SG,globalMaxPool1d:()=>LG,globalMaxPool2d:()=>BG,globalMaxPooling1d:()=>J4,globalMaxPooling2d:()=>Q4,gru:()=>NG,gruCell:()=>CG,input:()=>v4,inputLayer:()=>OU,layerNormalization:()=>gG,leakyReLU:()=>BU,lstm:()=>EG,lstmCell:()=>RG,masking:()=>HG,maxPool1d:()=>WG,maxPool2d:()=>VG,maxPooling1d:()=>e6,maxPooling2d:()=>t6,maxPooling3d:()=>TG,maximum:()=>pG,minimum:()=>hG,multiply:()=>cG,permute:()=>iG,prelu:()=>WU,reLU:()=>LU,repeatVector:()=>aG,reshape:()=>sG,rnn:()=>_G,separableConv2d:()=>XU,simpleRNN:()=>MG,simpleRNNCell:()=>FG,softmax:()=>VU,spatialDropout1d:()=>rG,stackedRNNCells:()=>zG,thresholdedReLU:()=>UU,timeDistributed:()=>DG,upSampling2d:()=>YU,zeroPadding2d:()=>yG});async function Is(e){if(e==null)return;let t=[],r=[],n=[];for(let a in e){let s=e[a];if(typeof s!="number"){let i=s;t.push(i.data()),r.push(a),n.push(i)}}if(t.length>0){let a=await Promise.all(t);for(let s=0;s<a.length;++s)e[r[s]]=a[s][0];re(n)}}function a4(e){if(e!=null)for(let t in e){let r=e[t];typeof r!="number"&&r.dispose()}}var EV=125,Nu=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){}},s4=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)}},RV=class extends Nu{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 n in t){let a=t[n];if(typeof a=="number")this.totals.hasOwnProperty(n)||(this.totals[n]=0),this.totals[n]=this.totals[n]+a*r;else{let s;n in this.totals?s=this.totals[n]:this.totals[n]=0;let i=K(()=>le(this.totals[n],L(a,r)));this.totals[n]=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:K(()=>{let n=L(pe(1,this.seen),this.totals[r]);t[r]=n,this.totals[r].dispose(),fr(t[r])}))}},i4=class extends Nu{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 a in this.history){let s=this.history[a];for(let i=0;i<s.length;++i)if(typeof s[i]!="number"){let o=s[i];e.push(o.data()),t.push(a),r.push(i)}}let n=await Promise.all(e);for(let a=0;a<n.length;++a)this.history[t[a]][r[a]].dispose(),this.history[t[a]][r[a]]=n[a][0]}},o4=class extends Nu{constructor(e,t){if(super(),this.currentEpoch=0,this.nowFunc=e.nowFunc,this.nextFrameFunc=e.nextFrameFunc||fA,this.yieldEvery=t||"auto",this.yieldEvery==="auto"&&(this.yieldEvery=EV),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=NL(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 n=[];this.yield!=null&&(await Is(r),n.push(this.yield(e,t,r))),n.push(this.nextFrameFunc()),await Promise.all(n)}async onEpochBegin(e,t){this.currentEpoch=e,this.epochBegin!=null&&(await Is(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){let r=[];this.epochEnd!=null&&(await Is(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 Is(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){let r=[];this.batchEnd!=null&&(await Is(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 Is(e),await this.trainBegin(e))}async onTrainEnd(e){this.trainEnd!=null&&(await Is(e),await this.trainEnd(e))}};function l4(e,t){return e==null&&(e={}),e instanceof Nu?[e]:Array.isArray(e)&&e[0]instanceof Nu?e:It(e).map(r=>new o4(r,t))}var Ia=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}`),Ia.checkForDuplicate(t),Ia.constructors[e]==null&&(Ia.constructors[e]=[]),Ia.constructors[e].push(t)}static checkForDuplicate(e){for(let t in Ia.constructors)Ia.constructors[+t].forEach(r=>{if(r===e)throw new q("Duplicate callback constructor.")})}static clear(){Ia.constructors={}}static createCallbacks(e){let t=[];for(let r in Ia.constructors){let n=+r;e>=n&&t.push(...Ia.constructors[n])}return t.map(r=>new r)}},FA=Ia;FA.constructors={};function u4(e,t,r,n,a,s,i,o,l){let u=new i4,d=[new RV,...FA.createCallbacks(t)];e!=null&&d.push(...e),d.push(u);let h=new s4(d);return h.setParams({epochs:r,initialEpoch:n,samples:a,steps:s,batchSize:i,verbose:t,doValidation:o,metrics:l}),{callbackList:h,history:u}}function ha(e,t={},r=!1){return Ih(e,ue.SerializationMap.getMap().classNameMap,t,"layer",r)}function Ef(e,t){return K(()=>{e.dtype!=="float32"&&(e=me(e,"float32"));let r=ke(Th(e),t,!0),n=dd(r.shape,ar()),a=Er(ts(r,n));return pe(e,a)})}function $l(e,t){return K(()=>Wt(Th(ce(t,e)),-1))}function a0(e,t){return K(()=>Wt(rr(ce(t,e)),-1))}function yd(e,t){return K(()=>{let r=ce(e,t),n=cn(rr(e),ar(),Number.MAX_VALUE),a=rr(pe(r,n));return L(100,Wt(a,-1))})}function MV(e,t){return K(()=>{let r=cn(t,ar(),Number.MAX_VALUE),n=Mn(le(1,r)),a=cn(e,ar(),Number.MAX_VALUE),s=Mn(le(1,a));return Wt(Th(ce(n,s)),-1)})}function FV(e,t){return K(()=>{let r=ts(0,ce(1,L(e,t)));return Wt(Th(r),-1)})}function $V(e,t){return K(()=>{let r=ts(0,ce(1,L(e,t)));return Wt(r,-1)})}function PV(e,t){return K(()=>{let r=ke(L(e,t),-1),n=gr(L(ce(1,e),t),-1);return ts(0,le(1,ce(n,r)))})}function _V(e,t){return K(()=>{let r=Math.log(2),n=ce(t,e),a=ce(le(n,pd(L(-2,n))),r);return Wt(a,-1)})}function Vp(e,t,r=!1){return K(()=>{if(r)t=fd(t);else{let n=ke(t,t.shape.length-1,!0);t=pe(t,n)}return t=cn(t,ar(),1-ar()),Ot(ke(L(me(e,"float32"),Mn(t)),t.shape.length-1))})}function Rf(e,t,r=!1){return K(()=>{let n=me(bh(LL(e)),"int32");t=cn(t,ar(),1-ar());let a=t.shape,s=G(Lp(n,a[a.length-1]),a);return Vp(s,t,r)})}function zV(e,t){if(!w.arraysEqual(e.shape,t.shape))throw new q(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return K(()=>{let r=_a(t),n=Ot(rr(t));return le(ce(r,L(t,e)),Tm(Rn(n)))})}function s0(e,t){return K(()=>{let r;return r=cn(t,ar(),1-ar()),r=Mn(pe(r,ce(1,r))),Wt(zV(e,r),-1)})}function OV(e,t){return K(()=>{let r=cn(e,ar(),1),n=cn(t,ar(),1);return ke(L(e,Mn(pe(r,n))),-1)})}function DV(e,t){return K(()=>{let r=Mn(le(ar(),t));return Wt(ce(t,L(e,r)),-1)})}function $A(e,t){return K(()=>{let r=Ef(e,-1),n=Ef(t,-1),a=L(r,n);return Ot(ke(a,-1))})}var Mf={meanSquaredError:$l,meanAbsoluteError:a0,meanAbsolutePercentageError:yd,meanSquaredLogarithmicError:MV,squaredHinge:FV,hinge:$V,categoricalHinge:PV,logcosh:_V,categoricalCrossentropy:Vp,sparseCategoricalCrossentropy:Rf,binaryCrossentropy:s0,kullbackLeiblerDivergence:OV,poisson:DV,cosineProximity:$A};function ry(e){if(typeof e=="string"){if(e in Mf)return Mf[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 q(t)}else return e}function PA(e,t){return K(()=>{let r=L(.5,Fn(t)),n=Km(fn(t,r),e.dtype);return Wt(En(e,n),-1)})}function _A(e,t){return K(()=>Km(En(Cn(e,-1),Cn(t,-1)),"float32"))}function d4(e,t){return K(()=>me(ke(fa(En(e,1),En(t,1))),"float32"))}function LV(e,t){return K(()=>me(ke(fa(En(e,1),En(t,0))),"float32"))}function BV(e,t){return K(()=>me(ke(fa(En(e,0),En(t,1))),"float32"))}function p4(e,t){return K(()=>{let r=d4(e,t),n=BV(e,t),a=le(r,n);return me(Wr(fn(a,0),pe(r,a),0),"float32")})}function WV(e,t){return K(()=>{let r=d4(e,t),n=LV(e,t),a=le(r,n);return me(Wr(fn(a,0),pe(r,a),0),"float32")})}function h4(e,t){return s0(e,t)}function c4(e,t){return e.rank===t.rank&&(e=rt(e,[e.rank-1])),t=Cn(t,-1),t.dtype!==e.dtype&&(t=me(t,e.dtype)),me(En(e,t),"float32")}var VV=$l,UV=$l,GV=a0,jV=a0,HV=yd,qV=yd,zA=Vp,KV=$A,f4=Rf,Ff={binaryAccuracy:PA,categoricalAccuracy:_A,precision:p4,categoricalCrossentropy:zA,sparseCategoricalCrossentropy:f4,mse:VV,MSE:UV,mae:GV,MAE:jV,mape:HV,MAPE:qV,cosine:KV};function XV(e){if(typeof e=="string"&&e in Ff)return Ff[e];if(typeof e!="string"&&e!=null)return e;throw new q(`Unknown metric ${e}`)}function qc(e){if(Ta(e!==null,`Unknown LossOrMetricFn ${e}`),typeof e=="string")return e;{let t;for(let r of Object.keys(Mf))if(Mf[r]===e){t=r;break}if(t!==void 0)return t;for(let r of Object.keys(Ff))if(Ff[r]===e){t=r;break}return t!==void 0?t:e.name}}function ZV(e){let t={Adagrad:()=>go.adagrad(.01),Adadelta:()=>go.adadelta(1,.95,ar()),Adam:()=>go.adam(.001,.9,.999,ar()),Adamax:()=>go.adamax(.002,.9,.999,ar(),0),RMSProp:()=>go.rmsprop(.001,.9,0,ar()),SGD:()=>go.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 q(`Unknown Optimizer ${e}`)}var ov=1*1024*1024;function lv(e,t,r=!1){if(e==null||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype||!Cy(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(r){let n=JSON.stringify(e);n.length>ov&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${n.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= ${ov}.`)}}function Cy(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"||!Cy(e[r]))return!1;return!0}else if(Array.isArray(e)){for(let t of e)if(!Cy(t))return!1;return!0}else return!1;else{let t=typeof e;return t==="string"||t==="number"||t==="boolean"}}function YV(e,t,r,n=console.log){let a=QV(e),s=["Layer (type)","Input Shape","Output shape","Param #"];a?(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(d=>Math.floor(t*d)));let i;if(!a){s.push("Receives inputs"),i=[];for(let d in e.nodesByDepth)i.push(...e.nodesByDepth[d])}n("_".repeat(t)),$f(s,r,n),n("=".repeat(t));let o=e.layers;for(let d=0;d<o.length;++d)a?eU(o[d],r,n):tU(o[d],r,i,n),n((d===o.length-1?"=":"_").repeat(t));e.checkTrainableWeightsConsistency();let l=JV(e),u=Tf(e.nonTrainableWeights);n(`Total params: ${l+u}`),n(`Trainable params: ${l}`),n(`Non-trainable params: ${u}`),n("_".repeat(t))}function JV(e){let t;return e.collectedTrainableWeights!=null?t=Tf(e.collectedTrainableWeights):t=Tf(e.trainableWeights),t}function QV(e){let t=!0,r=[],n=[];for(let a in e.nodesByDepth)r.push(e.nodesByDepth[a]);for(let a of r){if(a.length>1||a.length===1&&a[0].inboundLayers.length>1){t=!1;break}n.push(...a)}if(t)for(let a of e.layers){let s=!1;for(let i of a.inboundNodes)if(n.indexOf(i)!==-1)if(s){t=!1;break}else s=!0;if(!t)break}return t}function $f(e,t,r=console.log){let n="";for(let a=0;a<e.length;++a)a>0&&(n=n.slice(0,n.length-1)+" "),n+=e[a],n=n.slice(0,t[a]),n+=" ".repeat(t[a]-n.length);r(n)}function eU(e,t,r){let n,a;try{a=e.inboundNodes.map(l=>JSON.stringify(l.inputShapes)).join(",")}catch(l){a="multiple"}try{n=JSON.stringify(e.outputShape)}catch(l){n="multiple"}let s=e.name,i=e.getClassName(),o=[`${s} (${i})`,a,n,e.countParams().toString()];$f(o,t,r)}function tU(e,t,r,n){let a,s;try{s=e.inboundNodes.map(h=>JSON.stringify(h.inputShapes)).join(",")}catch(h){s="multiple"}try{a=JSON.stringify(e.outputShape)}catch(h){a="multiple"}let i=[];for(let h of e.inboundNodes)if(!(r!=null&&r.length>0&&r.indexOf(h)===-1))for(let p=0;p<h.inboundLayers.length;++p){let c=h.inboundLayers[p].name,f=h.nodeIndices[p],m=h.tensorIndices[p];i.push(`${c}[${f}][${m}]`)}let o=e.name,l=e.getClassName(),u=i.length===0?"":i[0],d=[`${o} (${l})`,s,a,e.countParams().toString(),u];$f(d,t,n);for(let h=1;h<i.length;++h)$f(["","","","",i[h]],t,n)}function m4(e,t,r){return(e==="inboundNodes"||e==="outputLayers"||e==="inputLayers")&&t===0&&typeof r=="string"}function Up(e,t){if(e===null)return null;if(typeof e=="string")return bo(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){let r=[],n=e.length;for(let a=0;a<n;++a){let s=e[a];m4(t,a,s)?r.push(s):r.push(Up(s,t))}return r}else{let r={};for(let n of Object.keys(e)){let a=e[n];if(n==="name"&&typeof a=="string")r[n]=a;else{let s=bo(n);r[s]=Up(a,s)}}return r}}function Ey(e,t){if(e==null)return null;if(typeof e=="string")return ja(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){let r=[],n=e.length;for(let a=0;a<n;++a){let s=e[a];m4(t,a,s)?r.push(s):r.push(Ey(s,t))}return r}else{let r={};for(let n of Object.keys(e)){let a=e[n],s=ja(n);(n==="name"||n==="className")&&typeof a=="string"?r[s]=a:r[s]=Ey(a,n)}return r}}var OA="0.0.0",Sa=class extends st{constructor(e){if(super({}),this.containerNodes=new Set,this.name=e.name,this.name==null){let y=this.getClassName().toLowerCase();this.name=qm(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],Es(this.inputs).length!==this.inputs.length)throw new q(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(y=>y.name)}`);Es(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;Ta(x===0,"input layer has >1 nodes"),Ta(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 gd))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={},n={},a={},s={},i=[],o=(y,A,x,b,v,S)=>{(b==null||v==null||S==null)&&(b=y.sourceLayer,v=y.nodeIndex,S=y.tensorIndex);let T=b.inboundNodes[v];if(x.indexOf(T)!==-1)throw new la(`The tensor ${y.name} at layer "${b.name}" is part of a cycle.`);if(A.indexOf(T)!==-1)return;this.containerNodes.add(Sa.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 _=T.inputTensors[R],M=T.inboundLayers[R],I=T.nodeIndices[R],z=T.tensorIndices[R];o(_,A,x,M,I,z)}for(A.push(T);x.indexOf(T)>=0;)x.splice(x.indexOf(T),1);i.push(T)},l=[],u=[];for(let y of this.outputs)o(y,l,u);let d=i.slice().reverse();for(let y of d){r[y.id]=y,y.id in t||(t[y.id]=0);let A=t[y.id],x=n[y.outboundLayer.id]==null?0:n[y.outboundLayer.id];A=Math.max(A,x),n[y.outboundLayer.id]=A,a[y.outboundLayer.id]=y.outboundLayer,t[y.id]=A;for(let b=0;b<y.inboundLayers.length;b++){let v=y.inboundLayers[b],S=y.nodeIndices[b],T=v.inboundNodes[S],E=t[T.id]==null?0:t[T.id];t[T.id]=Math.max(A+1,E),r[T.id]=T}}let h={};for(let y in t){let A=t[y];A in h||(h[A]=[]),h[A].push(r[y])}let p={};for(let y in n){let A=n[y];A in p||(p[A]=[]),p[A].push(a[y])}let c=Object.keys(p).map(y=>parseInt(y,10)).sort(Gc);this.layers=[];for(let y of c){let A=p[y];A.sort((x,b)=>{let v=s[x.id],S=s[b.id];return v<S?-1:v>S?1:0});for(let x of A)x instanceof Sa&&this.internalContainerRefs.push(x),this.layers.push(x)}this.layersByDepth=p,c=Object.keys(h).map(y=>parseInt(y,10)).sort(Gc);let f=this.inputs.slice(),m=[];for(let y of c)for(let A of h[y]){let x=A.outboundLayer;if(x!=null){for(let b of A.inputTensors)if(f.indexOf(b)===-1)throw new la(`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=h;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 la(`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 n0({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 q("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={},n=0;for(let s of this.layers)for(let i of s.weights){if(r[i.originalName]!=null)throw new q(`Duplicate weight name: ${i.originalName}`);r[i.originalName]=i,n++}let a=[];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)a.push([r[i],e[s]]);else if(t)throw new q(`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 q(`${s.length} of ${n} weights are not set: ${s}`)}TA(a)}updatedConfig(){let e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${OA}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){let r=Ey(this.updatedConfig());return t?JSON.stringify(r):r}call(e,t){return K(()=>{e=It(e);let r=new ko;for(let n=0;n<this.inputs.length;++n)r.add(this.inputs[n],e[n]);return vp(this.outputs,r,t)})}computeMask(e,t){return K(()=>{e=It(e);let r;return t==null?r=Po(null,e.length):r=It(t),this.runInternalGraph(e,r)[1]})}computeOutputShape(e){let t=Sf(e);if(t.length!==this.inputLayers.length)throw new q(`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],u=o.name+"_0_0";r[u]=l}let n=Object.keys(this.nodesByDepth).map(i=>parseInt(i,10)).sort(Gc);if(n.length>1)for(let i of n){let o=this.nodesByDepth[i];for(let l of o){let u=l.outboundLayer;if(this.inputLayers.map(f=>f.id).indexOf(u.id)!==-1)continue;let d=[];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];d.push(x)}let h=u.computeOutputShape(en(d)),p=Sf(h),c=u.inboundNodes.indexOf(l);for(let f=0;f<p.length;f++){let m=`${u.name}_${c}_${f}`;r[m]=p[f]}}}let a=[],s=[];for(let i=0;i<this.outputLayers.length;i++){let o=this.outputLayers[i],l=this.outputLayersNodeIndices[i],u=this.outputLayersTensorIndices[i],d=`${o.name}_${l}_${u}`;s.push(d)}for(let i=0;i<s.length;i++){let o=s[i];Ta(o in r),a.push(r[o])}return en(a)}runInternalGraph(e,t){t==null&&(t=Po(null,e.length));let r={};for(let o=0;o<this.inputs.length;++o){let l=this.inputs[o],u=e[o],d=t[o];r[l.id]=[u,d]}let n=Object.keys(this.nodesByDepth).map(o=>parseInt(o,10)).sort(Gc);for(let o of n){let l=this.nodesByDepth[o];for(let u of l){let d=u.outboundLayer,h=u.inputTensors,p=u.outputTensors,c=new Array;for(let f of h)f.id in r&&c.push(r[f.id]);if(c.length===h.length){let f={},m,g,y,A;if(u.callArgs!=null&&(f=u.callArgs),c.length===1){let[x,b]=c[0];f.mask==null&&(f.mask=b),y=It(d.call(x,f)),A=It(d.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(d.call(m,f)),A=It(d.computeMask(m,g));if(d.activityRegularizer)throw new Ve("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let x=0;x<p.length;++x){let b=p[x],v=y[x],S=A[x];r[b.id]=[v,S]}}}}let a=[],s=[],i=[];for(let o of this.outputs){Ta(o.id in r,`Could not compute output ${o.name} : ${o.id}`);let[l,u]=r[o.id];i.push(l.shape),a.push(l),s.push(u)}return[a,s,i]}buildNodeConversionMap(e){let t={},r;for(let n of this.layers){r=n instanceof Sa?1:0;for(let a=0;a<n.inboundNodes.length;a++){let s=Sa.nodeKey(n,a);this.containerNodes.has(s)&&(t[s]=r,r+=1)}}return t}getLayer(e,t){if(t!=null){if(this.layers.length<=t)throw new q(`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 q("Provide either a layer name or layer index");for(let r of this.layers)if(r.name===e)return r;throw new q(`No such layer: ${e}`)}calculateLosses(){return K(()=>{let e=[];for(let t of this.layers)for(let r=0;r<t.inboundNodes.length;++r){let n=Sa.nodeKey(t,r);this.containerNodes.has(n)&&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 d=0;d<s.inboundNodes.length;d++){let h=s.inboundNodes[d],p=Sa.nodeKey(s,d),c={};if(this.containerNodes.has(p)){if(h.callArgs)try{JSON.stringify(h.callArgs),c=h.callArgs}catch(f){console.warn(`Layer ${s.name} was passed non-serializable keyword arguments: ${h.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),c={}}if(h.inboundLayers.length>0){let f=[];for(let m=0;m<h.inboundLayers.length;m++){let g=h.inboundLayers[m],y=h.nodeIndices[m],A=h.tensorIndices[m],x=Sa.nodeKey(g,y),b=t[x];b==null&&(b=0),f.push([g.name,b,A,c])}l.push(f)}}}let u={};u.name=s.name,u.className=i,u.config=o,u.inboundNodes=l,r.push(u)}e.layers=r;let n=[];for(let s=0;s<this.inputLayers.length;s++){let i=this.inputLayers[s],o=this.inputLayersNodeIndices[s],l=Sa.nodeKey(i,o);if(!this.containerNodes.has(l))continue;let u=t[l];u==null&&(u=0);let d=this.inputLayersTensorIndices[s];n.push([i.name,u,d])}e.inputLayers=n;let a=[];for(let s=0;s<this.outputLayers.length;s++){let i=this.outputLayers[s],o=this.outputLayersNodeIndices[s],l=Sa.nodeKey(i,o);if(!this.containerNodes.has(l))continue;let u=t[l];u==null&&(u=0);let d=this.outputLayersTensorIndices[s];a.push([i.name,u,d])}return e.outputLayers=a,e}static fromConfig(e,t,r={},n=!1){let a={},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],S=x[2];if(A=x[3]==null?{}:x[3],!(b in a)){i(m,g);return}let T=a[b];if(T.inboundNodes.length<=v){i(m,g);return}let E=T.inboundNodes[v];y.push(E.outputTensors[S])}y.length>0&&m.apply(en(y),A)}function l(m){let g=m.name,y=ha(m,t.customObjects!=null?t.customObjects:{});y.setFastWeightInitDuringBuild(n),a[g]=y,m.inboundNodes.forEach(A=>{if(!(A instanceof Array))throw new q(`Corrupted configuration, expected array for nodeData: ${A}`);i(y,A)})}let u=t.name,d=t.layers;for(let m of d)l(m);for(;!TL(s);)for(let m of d){let g=a[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 h=[],p=[],c=t.inputLayers;for(let m of c){let g=m[0],y=m[1],A=m[2];Ta(g in a);let x=a[g].inboundNodes[y].outputTensors;h.push(x[A])}let f=t.outputLayers;for(let m of f){let g=m[0],y=m[1],A=m[2];Ta(g in a);let x=a[g].inboundNodes[y].outputTensors;p.push(x[A])}return new e({inputs:h,outputs:p,name:u})}get stateful(){if(this._stateful)throw new q("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(){K(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}};function rU(e,t,r){let n=t.length;if(e==null||Array.isArray(e)&&e.length===0)return t.map(a=>null);if(n===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!==n)throw new Error(`Provided ${r} is an array of ${e.length} element(s), but the model has ${n} 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 a=[];return t.forEach(s=>{s in e?a.push(e[s]):a.push(null)}),a}else throw new Error(`The model has multiple (${n}) outputs, so ${r} must be either an array with ${n} elements or an object with ${t} keys. Provided ${r} not understood: ${JSON.stringify(e)}`)}function g4(e,t){return rU(e,t,"classWeight")}async function y4(e,t,r,n){if(t!=null||n!=null)throw new Error("Support sampleWeight is not implemented yet");if(r!=null){let a=K(()=>{if(e.shape.length===1)return Br(e);if(e.shape.length===2){if(e.shape[1]>1)return Cn(e,1);if(e.shape[1]===1)return G(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 a.data());re(a);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 nU(e,t){return L(e,t)}var aU=32;function A4(e,t){let r,n,a=t;r=a.xs,n=a.ys,w.assert(r!=null&&n!=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=uv("input",e.inputNames,r),i=uv("output",e.outputNames,n),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 uv(e,t,r){if(r instanceof nt)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 n=[];for(let a of t){if(r[a]==null)throw new q(`The feature data generated by the dataset lacks the required ${e} key '${a}'.`);n.push(r[a])}return n}}function sU(e){if(e.length===3)throw new Ve("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}async function iU(e,t,r){let n=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(!n||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 a=r.validationData!=null,s,i;if(a)if(dv(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=sU(r.validationData);s=g.xs,i=g.ys}let o=e.makeTrainFunction(),l=e.getDedupedMetricsNames(),u;a?u=l.slice().concat(l.map(g=>"val_"+g)):u=l.slice();let d=l4(r.callbacks,r.yieldEvery),h=r.verbose==null?1:r.verbose,{callbackList:p,history:c}=u4(d,h,r.epochs,null,null,oU(t,r),null,a,u);p.setModel(e),e.history=c,await p.onTrainBegin(),e.stopTraining_=!1;let f=r.initialEpoch==null?0:r.initialEpoch,m=await t.iterator();for(;f<r.epochs;){let g={};await p.onEpochBegin(f);let y=0,A=0;for(n||(m=await t.iterator());!n||y<r.batchesPerEpoch;){let x=await m.next();if(n&&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}=A4(e,x.value),S={};S.batch=A,S.size=b[0].shape[0],await p.onBatchBegin(A,S);let T=[];if(r.classWeight!=null){let _=g4(r.classWeight,e.outputNames);for(let M=0;M<_.length;++M)T.push(await y4(v[M],null,_[M]))}let E=b.concat(v).concat(T),R=o(E);re(E);for(let _=0;_<l.length;++_){let M=l[_],I=R[_];S[M]=I,fr(I)}await p.onBatchEnd(A,S),a4(S),A++,y++}if(n?y>=r.batchesPerEpoch:x.done){if(a){let b;dv(r.validationData)?b=It(await e.evaluateDataset(r.validationData,{batches:r.validationBatches})):b=It(e.evaluate(s,i,{batchSize:r.validationBatchSize==null?aU: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 p.onEpochEnd(f,g),f++,e.stopTraining_)break}return await p.onTrainEnd(),await e.history.syncData(),e.history}finally{e.isTraining=!1}}function oU(e,t){let r=null;return t.batchesPerEpoch!=null?r=t.batchesPerEpoch:Number.isFinite(e.size)&&(r=e.size),r}function dv(e){return typeof e.iterator=="function"}function lU(e){return typeof e.next=="function"}async function uU(e,t,r){r=r||{};let n=r.batches!=null,a=e.testFunction,s=[];if(r.verbose>0)throw new Ve("Verbose mode is not implemented yet.");w.assert(!n||r.batches>0&&Number.isInteger(r.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(r.batches)}`);let i=lU(t)?t:await t.iterator(),o=0,l=0;for(;!n||l<r.batches;){let u=await i.next();if(s=K(()=>{if(u.value){let{xs:d,ys:h}=A4(e,u.value),p=d.concat(h),c=K(()=>a(p));if(re(p),l===0)for(let m=0;m<c.length;++m)s.push(Se(0));let f=p[0].shape[0];for(let m=0;m<c.length;++m){let g=c[m],y=s[m];s[m]=K(()=>le(s[m],L(f,g))),l>0&&re(y)}re(c),o+=f,++l}return s}),u.done){n&&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 u=0;u<s.length;++u){let d=s[u];s[u]=pe(s[u],o),re(d)}return en(s)}function Ry(e){w.assert(e>0&&Number.isInteger(e),()=>`batchSize is required to be a positive integer, but got ${e}`)}function wp(e,t,r){return e==null?[null]:Array.isArray(e)?e.map(n=>No(n,t,r-t)):No(e,t,r-t)}function DA(e,t){return K(()=>e==null?null:Array.isArray(e)?e.map(r=>DA(r,t)):K7(e,t.dtype==="int32"?t:me(t,"int32")))}function My(e,t){let r=[],n=0,a=null;for(;n<e;)a=n+t,a>=e&&(a=e),r.push([n,a]),n=a;return r}async function dU(e,t,r,n,a,s,i,o,l,u,d,h,p,c,f){a==null&&(a=32),s==null&&(s=1),d==null&&(d=!0),p==null&&(p=0);let m=!1;if(l!=null&&u!=null&&(m=!0),f!=null&&(m=!0,c==null))throw new q("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");let g=e.checkNumSamples(r,a,c,"steps_per_epoch"),y;g!=null&&(y=ma(0,g)),i==null&&(i=1);let{callbackList:A,history:x}=u4(o,i,s,p,g,c,a,m,h);A.setModel(e),e.history=x,await A.onTrainBegin(),e.stopTraining_=!1;for(let b=p;b<s;++b){await A.onEpochBegin(b);let v={};if(c!=null)throw new Ve("stepsPerEpoch mode is not implemented yet.");{if(d==="batch")throw new Ve("batch shuffling is not implemneted yet");d&&w.shuffle(y);let S=St(y),T=My(g,a);for(let E=0;E<T.length;++E){let R={};if(await A.onBatchBegin(E,R),K(()=>{let _=T[E][0],M=T[E][1],I=No(S,_,M-_);R.batch=E,R.size=M-_;let z=DA(r,I),O=t(z);for(let j=0;j<n.length;++j){let X=n[j],D=O[j];R[X]=D,fr(D)}if(E===T.length-1&&m){let j=e.testLoop(l,u,a);for(let X=0;X<n.length;++X){let D=n[X],Q=j[X];fr(Q),v["val_"+D]=Q}}}),await A.onBatchEnd(E,R),a4(R),e.stopTraining_)break}S.dispose()}if(await A.onEpochEnd(b,v),e.stopTraining_)break}return await A.onTrainEnd(),await e.history.syncData(),e.history}async function pU(e,t,r,n={}){if(e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;let a,s,i,o,l,u,d,h,p;try{let c=n.batchSize==null?32:n.batchSize;Ry(c);let f=!1,m=await e.standardizeUserData(t,r,n.sampleWeight,n.classWeight,f,c);a=m[0],s=m[1],p=m[2];let g=!1,y;if(n.validationData!=null&&n.validationData.length>0){if(g=!0,n.validationData.length===2)l=n.validationData[0],u=n.validationData[1];else throw n.validationData.length===3?new Ve("validationData including sample weights is not supported yet."):new q(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${n.validationData} is invalid.`);let E=!0,R=await e.standardizeUserData(l,u,null,null,E,c);d=R[0],h=R[1],y=d.concat(h)}else if(n.validationSplit!=null&&n.validationSplit>0&&n.validationSplit<1){g=!0;let E=Math.floor(a[0].shape[0]*(1-n.validationSplit)),R=a[0].shape[0];d=wp(a,E,R),i=a,a=wp(a,0,E),h=wp(s,E,R),o=s,s=wp(s,0,E),y=d.concat(h)}else n.validationSteps!=null&&(g=!0);let A=a.concat(s).concat(p);e.checkTrainableWeightsConsistency();let x=e.makeTrainFunction(),b=e.getDedupedMetricsNames(),v,S;g?(e.makeTestFunction(),v=e.testFunction,S=b.slice().concat(b.map(E=>"val_"+E))):(v=null,y=[],S=b.slice());let T=l4(n.callbacks,n.yieldEvery);return await dU(e,x,A,b,c,n.epochs,n.verbose,T,v,y,n.shuffle,S,n.initialEpoch,null,null)}finally{e.isTraining=!1,oa(a,t),oa(s,r),oa(i,t),oa(o,r),oa(d,l),oa(h,u),p!=null&&re(p)}}function x4(e){let t=[];e instanceof nt&&(e=[e]);for(let r=0;r<e.length;++r){let n=e[r];if(n.rank===1)t.push(Sh(n,1));else{if(n.rank===0)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");t.push(n)}}return t}function oa(e,t){if(e==null)return;let r=[];if(t instanceof nt)r.push(t.id);else if(Array.isArray(t))t.forEach(a=>r.push(a.id));else if(t!=null)for(let a in t){let s=t[a];r.push(s.id)}let n=[];if(e instanceof nt)r.indexOf(e.id)===-1&&n.push(e);else if(Array.isArray(e))e.forEach(a=>{r.indexOf(a.id)===-1&&n.push(a)});else if(e!=null)for(let a in e){let s=e[a];r.indexOf(s.id)===-1&&n.push(s)}n.forEach(a=>{a.isDisposed||a.dispose()})}function hU(e){return e instanceof nt}function Fy(e){return Array.isArray(e)}function pv(e){return!hU(e)&&!Fy(e)}function hv(e,t,r,n=!0,a=""){if(t==null||t.length===0){if(e!=null){let i=!1;if(Fy(e)&&e.length>0)i=!0;else if(pv(e)){for(let o in e)if(e.hasOwnProperty(o)){i=!0;break}}else i=!0;if(i)throw new q(`Error when checking model ${a} expected no data, but got ${e}`)}return[]}if(e==null)return t.map(i=>null);let s;if(pv(e)){e=e,s=[];for(let i of t){if(e[i]==null)throw new q(`No data provided for "${i}". Need data for each key in: ${t}`);s.push(e[i])}}else if(Fy(e)){if(e=e,e.length!==t.length)throw new q(`Error when checking model ${a}: 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 q(`The model ${a} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);s=[e]}if(s=x4(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 q(`Error when checking ${a}: 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&&!n)continue;let u=o.shape[l],d=r[i][l];if(d!=null&&d>=0&&u!==d)throw new q(`${a} 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 ${a} 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 cU(e,t,r){let n=Es(e.map(s=>s.shape[0]));n.sort();let a=Es(t.map(s=>s.shape[0]));if(a.sort(),n.length>1)throw new q(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map(s=>s.shape))}`);if(a.length>1)throw new q(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map(s=>s.shape))}`);if(n.length>0&&a.length>0&&!w.arraysEqual(n,a))throw new q(`Input Tensors should have the same number of samples as target Tensors. Found ${n[0]} input sample(s) and ${a[0]} target sample(s).`)}function fU(e,t,r){let n=[$l,s0,Vp];for(let a=0;a<e.length;++a){let s=e[a],i=t[a],o=r[a];if(i!=null){if(i===Vp&&s.shape[s.shape.length-1]===1)throw new q(`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(n.indexOf(i)!==-1){let l=s.shape.slice(1),u=o.slice(1);for(let d=0;d<l.length;++d){let h=l[d],p=u[d];if(p!=null&&h!==p)throw new q(`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 cv(e,t,r,n=!0,a=""){let s;if(Array.isArray(e)){if(e.length!==t.length)throw new q(`Error when checking model ${a}: 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 q(`The model expects ${t.length} ${a} 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 q(`Error when checking ${a}: 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&&!n)continue;let u=o.shape[l],d=r[i][l];if(d!=null&&d!==u)throw new q(`Error when checking ${a}: expected ${t[i]} to have shape ${JSON.stringify(r[i])} but got array with shape ${JSON.stringify(o.shape)}.`)}}}function mU(e,t){if(e==null||Array.isArray(e)&&e.length===0)return t.map(n=>[]);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(n=>r);{let n=[];for(let a of t){let s=r.hasOwnProperty(a)?r[a]:[];Array.isArray(s)||(s=[s]),n.push(s)}return n}}var gU="layers-model",Xa=class extends Sa{constructor(e){super(e),this.isTraining=!1}summary(e,t,r=console.log){if(!this.built)throw new q("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).");YV(this,e,t,r)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=ZV(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof ns))throw new q("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 q(`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(ry(e.loss[s]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new q(`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=>ry(s))}else{let s=ry(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=[],To("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 n=mU(e.metrics,this.outputNames),a=(s,i,o)=>{this.outputNames.length>1&&(i=this.outputNames[s]+"_"+i),this.metricsNames.push(i),this.metricsTensors.push([o,s])};To("metric",()=>{for(let s=0;s<this.outputs.length;++s){if(r.indexOf(s)!==-1)continue;let i=n[s];(o=>{let l="",u,d,h;for(let p of o){if(typeof p=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(p)!==-1){let f=this.internalOutputShapes[s];f[f.length-1]===1||this.lossFunctions[s]===s0?["accuracy","acc"].indexOf(p)!==-1?d=PA:["crossentropy","ce"].indexOf(p)!==-1&&(d=h4):this.lossFunctions[s]===Rf?["accuracy","acc"].indexOf(p)!==-1?d=c4:["crossentropy","ce"].indexOf(p)!==-1&&(d=f4):["accuracy","acc"].indexOf(p)!==-1?d=_A:["crossentropy","ce"].indexOf(p)!==-1&&(d=zA);let m;["accuracy","acc"].indexOf(p)!==-1?m="acc":["crossentropy","ce"].indexOf(p)!==-1&&(m="ce"),h=d,u=l+m}else h=XV(p),u=l+qc(p);let c;To(u,()=>{c=h}),a(s,u,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 n=r.batchSize==null?32:r.batchSize;Ry(n);let a=!0,s=this.standardizeUserDataXY(e,t,a,n);try{let i=s[0].concat(s[1]);this.makeTestFunction();let o=this.testFunction,l=this.testLoop(o,i,n,r.verbose,r.steps);return en(l)}finally{oa(s[0],e),oa(s[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),uU(this,e,t)}checkNumSamples(e,t,r,n="steps"){let a;if(r!=null){if(a=null,t!=null)throw new q(`If ${n} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else if(e!=null)Array.isArray(e)?a=e[0].shape[0]:a=e.shape[0];else throw new q(`Either the input data should have a defined shape, or ${n} shoud be specified.`);return a}execute(e,t){if(Array.isArray(t)&&t.length===0)throw new q("`outputs` is an empty Array, which is not allowed.");let r=Array.isArray(t),n=r?t:[t],a=this.retrieveSymbolicTensors(n),s=new ko;if(e instanceof nt&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new q(`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 q(`No value is provided for the model's input ${o.name}`);s.add(o,l)}let i=vp(a,s);return r?i:i[0]}retrieveSymbolicTensors(e){let t=Po(null,e.length),r=e.length;for(let n of this.layers){let a=Array.isArray(n.output)?n.output:[n.output],s=a.map(i=>i.name);for(let i=0;i<e.length;++i){let o=s.indexOf(e[i]);if(o!==-1&&(t[i]=a[o],r--),r===0)break}if(r===0)break}if(r>0){let n=[];throw t.forEach((a,s)=>{a==null&&n.push(e[s])}),new q(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(n)}`)}return t}predictLoop(e,t=32,r=!1){return K(()=>{let n=this.checkNumSamples(e);if(r)throw new Ve("Verbose predictLoop() is not implemented yet.");let a=My(n,t),s=this.outputs.map(i=>[]);for(let i=0;i<a.length;++i)K(()=>{let o=a[i][0],l=a[i][1],u=wp(e,o,l),d=[];if(Array.isArray(u))for(let p=0;p<u.length;++p)d.push({key:this.inputs[p],value:u[p]});else d.push({key:this.inputs[0],value:u});let h=new ko(d);return vp(this.outputs,h)}).forEach((o,l)=>s[l].push(o));return en(s.map(i=>kt(i,0)))})}predict(e,t={}){let r=x4(e);cv(r,this.inputNames,this.feedInputShapes,!1);try{let n=t.batchSize==null?32:t.batchSize;return Ry(n),this.predictLoop(r,n)}finally{oa(r,e)}}predictOnBatch(e){cv(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,n){if(this.optimizer_==null)throw new la("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");let a=[];for(let s=0;s<this.feedOutputShapes.length;++s){let i=this.feedOutputShapes[s];this.feedLossFns[s]===Rf?a.push(i.slice(0,i.length-1).concat([1])):a.push(i)}if(e=hv(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=hv(t,this.feedOutputNames,a,!1,"target"),cU(e,t,null),fU(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&n!=null&&n>0&&e[0].shape[0]%n!==0)throw new q(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${n}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,r,n,a=!0,s){let[i,o]=this.standardizeUserDataXY(e,t,a,s);if(r!=null)throw new Error("sample weight is not supported yet.");let l=null;if(n!=null){let u=g4(n,this.outputNames);l=[];for(let d=0;d<u.length;++d)l.push(await y4(o[d],null,u[d]))}return[i,o,l]}testLoop(e,t,r,n=0,a){return K(()=>{let s=this.checkNumSamples(t,r,a,"steps"),i=[];if(n>0)throw new Ve("Verbose mode is not implemented yet.");if(a!=null)throw new Ve("steps mode in testLoop() is not implemented yet");{let o=My(s,r),l=St(ma(0,s));for(let u=0;u<o.length;++u){let d=o[u][0],h=o[u][1],p=No(l,d,h-d),c=DA(t,p),f=e(c);if(u===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]=le(i[m],L(h-d,g))}}for(let u=0;u<i.length;++u)i[u]=pe(i[u],s)}return i})}getDedupedMetricsNames(){let e=this.metricsNames,t=[];for(let r=0;r<e.length;++r){let n=e[r],a=n;H3(e,n)>1&&(a+=`_${H3(e.slice(0,r),n)}`),t.push(a)}return t}makeTrainFunction(){return e=>{let t=[],r=e.slice(0,this.inputs.length),n=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),a=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+this.outputs.length*2),s=[],i=()=>{let u=[];for(let c=0;c<this.inputs.length;++c)u.push({key:this.inputs[c],value:r[c]});let d=new ko(u),h=vp(this.outputs,d,{training:!0}),p;for(let c=0;c<this.lossFunctions.length;++c){let f=this.lossFunctions[c](n[c],h[c]);a[c]!=null&&(f=nU(f,a[c]));let m=Wt(f);t.push(m),c===0?p=f:p=le(p,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(n[g],h[g]))}fr(f),s.push(f)}return p=Wt(p),this.calculateLosses().forEach(c=>{p=le(p,c)}),p},o=this.collectedTrainableWeights.map(u=>u.read()),l=!0;return[this.optimizer_.minimize(i,l,o)].concat(s)}}makeTestFunction(){this.testFunction=e=>K(()=>{let t=[],r,n=e.slice(0,this.inputs.length),a=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:n[l]});let i=new ko(s),o=vp(this.outputs,i);for(let l=0;l<this.lossFunctions.length;++l){let u=this.lossFunctions[l],d=Wt(u(a[l],o[l]));l===0?r=d:r=le(r,d),t.push(r)}for(let l=0;l<this.metricsTensors.length;++l){let u=this.metricsTensors[l][0],d=this.metricsTensors[l][1],h=Wt(u(a[d],o[d]));t.push(h)}return t})}async fit(e,t,r={}){return pU(this,e,t,r)}async fitDataset(e,t){return iU(this,e,t)}async trainOnBatch(e,t){let r=await this.standardizeUserData(e,t),n=r[0],a=r[1],s=this.makeTrainFunction()(n.concat(a)),i=[];for(let o of s){let l=await o.data();i.push(l[0])}return re(s),oa(r[0],e),oa(r[1],t),en(i)}getNamedWeights(e){let t=[],r=e!=null&&e.trainableOnly,n=r?this.trainableWeights:this.weights,a=this.getWeights(r);for(let s=0;s<n.length;++s)r&&!n[s].trainable||t.push({name:n[s].originalName,tensor:a[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=vf().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-vf().numTensors}return e}getLossIdentifiers(){let e;if(typeof this.loss=="string")e=ja(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=>ja(t))}else{let t=Object.keys(this.loss);e={};let r=this.loss;for(let n of t)if(typeof r[n]=="string")e[n]=ja(r[n]);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[ja(qc(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>ja(qc(e)));{let e={};for(let t in this.metrics)e[t]=ja(qc(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=Up(e.optimizer_config),r=ha(t),n;if(typeof e.loss=="string")n=bo(e.loss);else if(Array.isArray(e.loss))n=e.loss.map(s=>bo(s));else if(e.loss!=null){n={};for(let s in e.loss)n[s]=bo(e.loss[s])}let a;if(Array.isArray(e.metrics))a=e.metrics.map(s=>bo(s));else if(e.metrics!=null){a={};for(let s in e.metrics)a[s]=bo(e.metrics[s])}this.compile({loss:n,metrics:a,optimizer:r})}async save(e,t){if(typeof e=="string"){let i=Tr.getSaveHandlers(e);if(i.length===0)throw new q(`Cannot find any save handlers for URL '${e}'`);if(i.length>1)throw new q(`Found more than one (${i.length}) save handlers for URL '${e}'`);e=i[0]}if(e.save==null)throw new q("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");let r=await Tr.encodeWeights(this.getNamedWeights(t)),n=!1,a=null,s={modelTopology:this.toJSON(a,n),format:gU,generatedBy:`TensorFlow.js tfjs-layers v${OA}`,convertedBy:null};if((t==null?!1:t.includeOptimizer)&&this.optimizer!=null){s.trainingConfig=this.getTrainingConfig();let i="optimizer",{data:o,specs:l}=await Tr.encodeWeights(await this.optimizer.getWeights(),i);r.specs.push(...l),r.data=Tr.concatenateArrayBuffers([r.data,o])}return this.userDefinedMetadata!=null&&(lv(this.userDefinedMetadata,this.name,!0),s.userDefinedMetadata=this.userDefinedMetadata),s.weightData=r.data,s.weightSpecs=r.specs,e.save(s)}setUserDefinedMetadata(e){lv(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}};Xa.className="Model";ue.registerClass(Xa);var b4=class extends Xa{};b4.className="Functional";ue.registerClass(b4);async function yU(e,t){"modelTopology"in e||(e={modelTopology:e}),e=e;let r=e.modelTopology;r.model_config!=null&&(r=r.model_config);let n=Up(r),a=ha(n,t);if(e.weightsManifest!=null){let s=await Tr.loadWeights(e.weightsManifest,e.pathPrefix,a.weights.map(o=>o.originalName)),i={};for(let o of a.weights)i[o.originalName]=s[o.originalName];a.loadWeights(i),re(s)}return a}async function AU(e,t){if(t==null&&(t={}),typeof e=="string"){let r=Tr.getLoadHandlers(e,t);if(r.length===0)r.push(Tr.browserHTTPRequest(e,t));else if(r.length>1)throw new q(`Found more than one (${r.length}) load handlers for URL '${e}'`);e=r[0]}return xU(e,void 0,t)}async function xU(e,t,r){if(r==null&&(r={}),e.load==null)throw new q("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let n=await e.load(),a=n.modelTopology;a.model_config!=null&&(a=a.model_config);let s=r.strict==null?!0:r.strict,i=n.weightData!=null&&n.weightSpecs!=null&&s,o=ha(Up(a),t,i),l=n.trainingConfig;if(l!=null&&o.loadTrainingConfig(l),n.userDefinedMetadata!=null&&o.setUserDefinedMetadata(n.userDefinedMetadata),n.weightData!=null){if(n.weightSpecs==null)throw new q("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");let{modelWeights:u,optimizerWeights:d}=bU(n.weightData,n.weightSpecs);o.loadWeights(u,s),o.optimizer!=null&&d.length>0&&await o.optimizer.setWeights(d),re(u),re(d.map(h=>h.tensor))}return o}function bU(e,t){let r=Tr.decodeWeights(e,t),n={},a=[];return t.forEach(s=>{s.group==="optimizer"?a.push({name:s.name,tensor:r[s.name]}):n[s.name]=r[s.name]}),{modelWeights:n,optimizerWeights:a}}var $y=class extends Xa{constructor(e){if(super({inputs:[],outputs:[]}),e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:qm("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 q(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){let t=e instanceof $y||e instanceof Xa,r;if(t){if(r=e,r.outputs.length!==1)throw new q("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 q("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 q("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");let n=J7({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(n)}if(t)this.outputs=r.outputs,this.inputs=r.inputs;else{if(e.inboundNodes.length!==1)throw new q(`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 q("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=Y7(this.outputs[0])}this.inboundNodes=[],new n0({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Po(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(n=>n.shape),outputShapes:this.outputs[0].shape})}else{let n=e.apply(this.outputs[0]);if(Array.isArray(n))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=[n],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(ft(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 Xa({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 la("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 la("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 la("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 la("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={},n=!1){let a,s={};if(t instanceof Array){if(t[0].className==null||t[0].className==="Merge")throw new q("Legacy serialization format not supported yet.");a=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."),a=t.layers,delete t.layers,s=t;let i=new e(s);if(!(i instanceof $y))throw new Ve(`Sequential.fromConfig called on non-Sequential input: ${i}`);for(let o of a){let l=ha(o,void 0,n);n&&l.setFastWeightInitDuringBuild(!0),i.add(l)}return i}set stopTraining(e){if(this.model==null)throw new q("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 q("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}}},i0=$y;i0.className="Sequential";ue.registerClass(i0);function vU(e){return new Xa(e)}function wU(e){return new i0(e)}function kU(e,t){return t==null&&(t={}),AU(e,t)}function v4(e){return J7(e)}function IU(e,t){FA.registerCallbackConstructor(e,t)}var on=class extends ue.Serializable{getConfig(){return{}}},w4=class extends on{apply(e,t=1){return WL(e,t)}};w4.className="elu";ue.registerClass(w4);var k4=class extends on{apply(e){return rA(e)}};k4.className="selu";ue.registerClass(k4);var I4=class extends on{apply(e){return _a(e)}};I4.className="relu";ue.registerClass(I4);var S4=class extends on{apply(e){return K(()=>vh(6,_a(e)))}};S4.className="relu6";ue.registerClass(S4);var T4=class extends on{apply(e){return e}};T4.className="linear";ue.registerClass(T4);var N4=class extends on{apply(e){return Nr(e)}};N4.className="sigmoid";ue.registerClass(N4);var C4=class extends on{apply(e){return UL(e)}};C4.className="hardSigmoid";ue.registerClass(C4);var E4=class extends on{apply(e){return pd(e)}};E4.className="softplus";ue.registerClass(E4);var R4=class extends on{apply(e){return VL(e)}};R4.className="softsign";ue.registerClass(R4);var M4=class extends on{apply(e){return vu(e)}};M4.className="tanh";ue.registerClass(M4);var LA=class extends on{apply(e,t=-1){return fd(e,t)}};LA.className="softmax";ue.registerClass(LA);var F4=class extends on{apply(e,t=-1){return j2(e,t)}};F4.className="logSoftmax";ue.registerClass(F4);var $4=class extends on{apply(e,t=1){return K(()=>L(Nr(L(e,t)),e))}};$4.className="swish";ue.registerClass($4);var P4=class extends on{apply(e){return K(()=>L(e,vu(pd(e))))}};P4.className="mish";ue.registerClass(P4);function Vs(e){return e.getClassName()}function ny(e,t={}){return Ih(e,ue.SerializationMap.getMap().classNameMap,t,"activation")}function Us(e){if(e==null){let t={};return t.className="linear",t.config={},ny(t)}if(typeof e=="string"){let t={};return t.className=e,t.config={},ny(t)}else return e instanceof on?e:ny(e)}function BA(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 _4=class extends ue.Serializable{},Eh=class extends _4{constructor(e){super(),BA(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 K(()=>{let t=Pt([1]);return this.hasL1&&(t=le(t,ke(L(this.l1,rr(e))))),this.hasL2&&(t=le(t,ke(L(this.l2,Th(e))))),G(t,[])})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}};Eh.className="L1L2";ue.registerClass(Eh);function SU(e){return BA(e),new Eh({l1:e!=null?e.l1:null,l2:0})}function TU(e){return BA(e),new Eh({l2:e!=null?e.l2:null,l1:0})}var fv={l1l2:"L1L2"};function xt(e){return gA(e)}function mv(e,t={}){return Ih(e,ue.SerializationMap.getMap().classNameMap,t,"regularizer")}function Rt(e){if(e==null)return null;if(typeof e=="string"){let t={className:e in fv?fv[e]:e,config:{}};return mv(t)}else return e instanceof _4?e:mv(e)}var WA=class extends st{constructor(e){super(e==null?{}:e),this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=je(e);let r=_a(e);return this.maxValue!=null&&(r=cn(r,0,this.maxValue)),r}computeOutputShape(e){return e}getConfig(){let e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}};WA.className="ReLU";ue.registerClass(WA);var VA=class extends st{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=je(e);return Sm(r,this.alpha)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};VA.className="LeakyReLU";ue.registerClass(VA);var UA=class extends st{constructor(e){if(super(e==null?{}:e),this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=Et(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=Rt(e.alphaRegularizer),this.alphaConstraint=or(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 q(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=ft(e);let t=e.slice(1);if(this.sharedAxes!=null)for(let n of this.sharedAxes)t[n-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);let r={};if(this.sharedAxes!=null)for(let n=1;n<e.length;++n)r[n]=e[n];this.inputSpec=[new Kt({ndim:e.length,axes:r})],this.built=!0}call(e,t){return e=je(e),Fm(e,this.alpha.read())}getConfig(){let e={alphaInitializer:_t(this.alphaInitializer),alphaRegularizer:xt(this.alphaRegularizer),alphaConstraint:ir(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}};UA.className="PReLU";ue.registerClass(UA);var GA=class extends st{constructor(e){if(super(e==null?{}:e),this.DEFAULT_ALPHA=1,e==null&&(e={}),e.alpha!=null&&e.alpha!==this.DEFAULT_ALPHA)throw new Ve(`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=je(e);return xh(r)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};GA.className="ELU";ue.registerClass(GA);var jA=class extends st{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=je(e);return L(r,me(fn(r,this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){let e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}};jA.className="ThresholdedReLU";ue.registerClass(jA);var HA=class extends st{constructor(e){super(e==null?{}:e),this.DEFAULT_AXIS=1,e==null&&(e={}),this.softmax=new LA().apply,this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis}call(e,t){let r=je(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}};HA.className="Softmax";ue.registerClass(HA);function yu(e,t,r){if(typeof e=="number")return Po(e,t);if(e.length!==t)throw new q(`The ${r} argument must be an integer or tuple of ${t} integers. Received: ${e.length} elements.`);for(let n=0;n<t;++n){let a=e[n];if(!OL(a))throw new q(`The ${r} argument must be an integer or tuple of ${t} integers. Received: ${JSON.stringify(e)} including a non-integer number ${a}`)}return e}function ca(e,t,r,n,a=1){if(e==null)return e;let s=t+(t-1)*(a-1),i;return r==="same"?i=e:i=e-s+1,Math.floor((i+n-1)/n)}function Na(e,t,r,n){if(e==null)return null;if(n==="valid")e=e*t+Ws([r-t,0]);else if(n==="same")e=e*t;else throw new q(`Unsupport padding mode: ${n}.`);return e}function qA(e,t){return K(()=>(Gt(t),t==="channelsFirst"?tt(e,[0,2,3,1]):e))}function z4(e,t){return K(()=>(Gt(t),t==="channelsFirst"?tt(e,[0,2,3,4,1]):e))}function NU(e,t,r,n=1,a="valid",s,i=1){return K(()=>{if(s==null&&(s=ga()),Gt(s),e.shape.length!==3)throw new q(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(t.shape.length!==3)throw new q(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(r!=null&&r.shape.length!==1)throw new q(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(s==="channelsFirst"&&(e=tt(e,[0,2,1])),a==="causal")throw new Ve("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let o=O2(e,t,n,a==="same"?"same":"valid","NWC",i);return r!=null&&(o=xa(o,r)),o})}function gv(e,t,r,n=[1,1],a="valid",s,i,o=null){return K(()=>{if(s==null&&(s=ga()),Gt(s),e.rank!==3&&e.rank!==4)throw new q(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(t.rank!==3&&t.rank!==4)throw new q(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=qA(e,s);if(a==="causal")throw new Ve("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=Bs.conv2d({x:l,filter:t,strides:n,pad:a==="same"?"same":"valid",dilations:i,dataFormat:"NHWC",bias:r,activation:o}),s==="channelsFirst"&&(l=tt(l,[0,3,1,2])),l})}function CU(e,t,r,n=[1,1,1],a="valid",s,i){return K(()=>{if(s==null&&(s=ga()),Gt(s),e.rank!==4&&e.rank!==5)throw new q(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(t.rank!==4&&t.rank!==5)throw new q(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let o=z4(e,s);if(a==="causal")throw new Ve("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=B2(o,t,n,a==="same"?"same":"valid","NDHWC",i),r!=null&&(o=xa(o,r)),s==="channelsFirst"&&(o=tt(o,[0,4,1,2,3])),o})}var KA=class extends st{constructor(e,t){if(super(t),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",KA.verifyArgs(t),this.rank=e,mr(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new Ve(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=yu(t.kernelSize,e,"kernelSize"),this.strides=yu(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,On(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,Gt(this.dataFormat),this.activation=Us(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=Et(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=or(t.biasConstraint),this.biasRegularizer=Rt(t.biasRegularizer),this.activityRegularizer=Rt(t.activityRegularizer),this.dilationRate=yu(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new q(`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 q(`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 q(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if(Ta("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!yA(e.kernelSize,"number",1,3))throw new q(`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:Vs(this.activation),useBias:this.useBias,biasInitializer:_t(this.biasInitializer),biasRegularizer:xt(this.biasRegularizer),activityRegularizer:xt(this.activityRegularizer),biasConstraint:ir(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}},Rh=class extends KA{constructor(e,t){super(e,t),this.kernel=null,Rh.verifyArgs(t),this.filters=t.filters,mr(this.filters,"filters"),this.kernelInitializer=Et(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=or(t.kernelConstraint),this.kernelRegularizer=Rt(t.kernelRegularizer)}build(e){e=ft(e);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new q(`The channel dimension of the input should be defined. Found ${e[t]}`);let r=e[t],n=this.kernelSize.concat([r,this.filters]);this.kernel=this.addWeight("kernel",n,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 K(()=>{e=je(e);let r,n=this.bias==null?null:this.bias.read(),a=V7(this.activation.getClassName());if(a!=null&&this.rank===2)r=gv(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate,a);else{if(this.rank===1)r=NU(e,this.kernel.read(),n,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)r=gv(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)r=CU(e,this.kernel.read(),n,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new Ve("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(r=this.activation.apply(r))}return r})}computeOutputShape(e){e=ft(e);let t=[],r=this.dataFormat==="channelsLast"?e.slice(1,e.length-1):e.slice(2);for(let a=0;a<r.length;++a){let s=ca(r[a],this.kernelSize[a],this.padding,this.strides[a],typeof this.dilationRate=="number"?this.dilationRate:this.dilationRate[a]);t.push(s)}let n=[e[0]];return this.dataFormat==="channelsLast"?(n=n.concat(t),n.push(this.filters)):(n.push(this.filters),n=n.concat(t)),n}getConfig(){let e={filters:this.filters,kernelInitializer:_t(this.kernelInitializer),kernelRegularizer:xt(this.kernelRegularizer),kernelConstraint:ir(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 q(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}},O4=class extends Rh{constructor(e){super(2,e),O4.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!yA(e.kernelSize,"number",1,2))throw new q(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}},o0=O4;o0.className="Conv2D";ue.registerClass(o0);var D4=class extends Rh{constructor(e){super(3,e),D4.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 q(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}},l0=D4;l0.className="Conv3D";ue.registerClass(l0);var XA=class extends o0{constructor(e){if(super(e),this.inputSpec=[new Kt({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new q(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=ft(e),e.length!==4)throw new q("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 q("The channel dimension of the inputs should be defined. Found `None`.");let r=e[t],n=this.kernelSize.concat([this.filters,r]);this.kernel=this.addWeight("kernel",n,"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 Kt({ndim:4,axes:{[t]:r}})],this.built=!0}call(e,t){return K(()=>{let r=je(e);if(r.shape.length!==4)throw new q(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${r.shape.length}`);let n=r.shape,a=n[0],s,i;this.dataFormat==="channelsFirst"?(s=2,i=3):(s=1,i=2);let o=n[s],l=n[i],u=this.kernelSize[0],d=this.kernelSize[1],h=this.strides[0],p=this.strides[1],c=Na(o,h,u,this.padding),f=Na(l,p,d,this.padding),m=[a,c,f,this.filters];this.dataFormat!=="channelsLast"&&(r=tt(r,[0,2,3,1]));let g=L2(r,this.kernel.read(),m,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(g=tt(g,[0,3,1,2])),this.bias!=null&&(g=xa(g,this.bias.read(),this.dataFormat)),this.activation!=null&&(g=this.activation.apply(g)),g})}computeOutputShape(e){e=ft(e);let t=e.slice(),r,n,a;this.dataFormat==="channelsFirst"?(r=1,n=2,a=3):(r=3,n=1,a=2);let s=this.kernelSize[0],i=this.kernelSize[1],o=this.strides[0],l=this.strides[1];return t[r]=this.filters,t[n]=Na(t[n],o,s,this.padding),t[a]=Na(t[a],l,i,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};XA.className="Conv2DTranspose";ue.registerClass(XA);var ZA=class extends l0{constructor(e){if(super(e),this.inputSpec=[new Kt({ndim:5})],this.padding!=="same"&&this.padding!=="valid")throw new q(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=ft(e),e.length!==5)throw new q("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 q("The channel dimension of the inputs should be defined. Found `None`.");let r=e[t],n=this.kernelSize.concat([this.filters,r]);this.kernel=this.addWeight("kernel",n,"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 Kt({ndim:5,axes:{[t]:r}})],this.built=!0}call(e,t){return K(()=>{let r=je(e);if(r.shape.length!==5)throw new q(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${r.shape.length}`);let n=r.shape,a=n[0],s,i,o;this.dataFormat==="channelsFirst"?(o=2,s=3,i=4):(o=1,s=2,i=3);let l=n[o],u=n[s],d=n[i],h=this.kernelSize[0],p=this.kernelSize[1],c=this.kernelSize[2],f=this.strides[0],m=this.strides[1],g=this.strides[2],y=Na(l,f,h,this.padding),A=Na(u,m,p,this.padding),x=Na(d,g,c,this.padding),b=[a,y,A,x,this.filters];this.dataFormat!=="channelsLast"&&(r=tt(r,[0,2,3,4,1]));let v=Hk(r,this.kernel.read(),b,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(v=tt(v,[0,4,1,2,3])),this.bias!==null&&(v=xa(v,this.bias.read(),this.dataFormat)),this.activation!==null&&(v=this.activation.apply(v)),v})}computeOutputShape(e){e=ft(e);let t=e.slice(),r,n,a,s;this.dataFormat==="channelsFirst"?(r=1,n=2,a=3,s=4):(r=4,n=1,a=2,s=3);let i=this.kernelSize[0],o=this.kernelSize[1],l=this.kernelSize[2],u=this.strides[0],d=this.strides[1],h=this.strides[2];return t[r]=this.filters,t[n]=Na(t[n],u,i,this.padding),t[a]=Na(t[a],d,o,this.padding),t[s]=Na(t[s],h,l,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};ZA.className="Conv3DTranspose";ue.registerClass(ZA);var L4=class extends Rh{constructor(e,t){if(super(e,t),this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,t.filters==null)throw new q("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new q("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 q(`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=Et(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=Rt(t.depthwiseRegularizer),this.depthwiseConstraint=or(t.depthwiseConstraint),this.pointwiseInitializer=Et(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=Rt(t.pointwiseRegularizer),this.pointwiseConstraint=or(t.pointwiseConstraint)}build(e){if(e=ft(e),e.length<this.rank+2)throw new q(`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 q(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);let r=e[t],n=this.kernelSize.concat([r,this.depthMultiplier]),a=[];for(let i=0;i<this.rank;++i)a.push(1);a.push(r*this.depthMultiplier,this.filters);let s=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",n,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,s,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",a,"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 Kt({ndim:this.rank+2,axes:{[t]:r}})],this.built=!0}call(e,t){return K(()=>{e=je(e);let r;if(this.rank===1)throw new Ve("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=tt(e,[0,2,3,1])),r=c7(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(r=xa(r,this.bias.read(),this.dataFormat)),this.activation!=null&&(r=this.activation.apply(r)),this.dataFormat==="channelsFirst"&&(r=tt(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=_t(this.depthwiseInitializer),e.pointwiseInitializer=_t(this.pointwiseInitializer),e.depthwiseRegularizer=xt(this.depthwiseRegularizer),e.pointwiseRegularizer=xt(this.pointwiseRegularizer),e.depthwiseConstraint=ir(this.depthwiseConstraint),e.pointwiseConstraint=ir(this.pointwiseConstraint),e}};L4.className="SeparableConv";var YA=class extends L4{constructor(e){super(2,e)}};YA.className="SeparableConv2D";ue.registerClass(YA);var B4=class extends Rh{constructor(e){super(1,e),B4.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"&&!yA(e.kernelSize,"number",1,1))throw new q(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}},JA=B4;JA.className="Conv1D";ue.registerClass(JA);var QA=class extends st{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 K(()=>{if(e=je(e),this.dataFormat==="channelsLast"){let r=Hc(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Hc(r,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{let r=Hc(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Hc(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}};QA.className="Cropping2D";ue.registerClass(QA);var ex=class extends st{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,Gt(this.dataFormat),this.interpolation=e.interpolation==null?"nearest":e.interpolation,PL(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 K(()=>{let r=je(e),n=r.shape;if(this.dataFormat==="channelsFirst"){r=tt(r,[0,2,3,1]);let a=this.size[0]*n[2],s=this.size[1]*n[3],i=this.interpolation==="nearest"?Ie.resizeNearestNeighbor(r,[a,s]):Ie.resizeBilinear(r,[a,s]);return tt(i,[0,3,1,2])}else{let a=this.size[0]*n[1],s=this.size[1]*n[2];return this.interpolation==="nearest"?Ie.resizeNearestNeighbor(r,[a,s]):Ie.resizeBilinear(r,[a,s])}})}getConfig(){let e={size:this.size,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};ex.className="UpSampling2D";ue.registerClass(ex);function EU(e,t,r=[1,1],n="valid",a,s){return K(()=>{a==null&&(a=ga()),Gt(a);let i=qA(e,a);if(e.rank!==4)throw new q(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(t.rank!==4)throw new q(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return i=Ah(i,t,r,n==="same"?"same":"valid","NHWC",s),a==="channelsFirst"&&(i=tt(i,[0,3,1,2])),i})}var tx=class extends KA{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=Et(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=or(e.depthwiseConstraint),this.depthwiseRegularizer=Rt(e.depthwiseRegularizer)}build(e){if(e=ft(e),e.length<4)throw new q(`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 q(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);let r=e[t],n=[this.kernelSize[0],this.kernelSize[1],r,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",n,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 K(()=>{e=je(e);let r=EU(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(r=xa(r,this.bias.read(),this.dataFormat)),this.activation!=null&&(r=this.activation.apply(r)),r})}computeOutputShape(e){e=ft(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],r=this.dataFormat==="channelsFirst"?e[3]:e[2],n=this.dataFormat==="channelsFirst"?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,a=ca(t,this.kernelSize[0],this.padding,this.strides[0]),s=ca(r,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[e[0],n,a,s]:[e[0],a,s,n]}getConfig(){let e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=_t(this.depthwiseInitializer),e.depthwiseRegularizer=xt(this.depthwiseRegularizer),e.depthwiseConstraint=ir(this.depthwiseRegularizer),e}};tx.className="DepthwiseConv2D";ue.registerClass(tx);function W4(e,t,r,n){if(Array.isArray(e)){if(t!=null||r!=null)throw new q("When inputs is an array, neither initialState or constants should be provided");n!=null&&(r=e.slice(e.length-n,e.length),e=e.slice(0,e.length-n)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function a(s){return s==null||Array.isArray(s)?s:[s]}return t=a(t),r=a(r),{inputs:e,initialState:t,constants:r}}function V4(e,t,r,n=!1,a,s,i=!1,o=!1){return K(()=>{let l=t.shape.length;if(l<3)throw new q(`Input should be at least 3D, but is ${l}D.`);let u=[1,0].concat(ma(2,l));if(t=tt(t,u),s!=null)throw new Ve("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."),a!=null&&(a=me(me(a,"bool"),"float32"),a.rank===l-1&&(a=qt(a,-1)),a=tt(a,u)),n&&(t=$n(t,0),a!=null&&(a=$n(a,0)));let d=[],h,p=r,c=t.shape[0],f=rn(t),m;a!=null&&(m=rn(a));for(let y=0;y<c;++y){let A=f[y],x=K(()=>e(A,p));if(a==null)h=x[0],p=x[1];else{let b=K(()=>{let v=m[y],S=ce(Fn(v),v),T=le(L(x[0],v),L(p[0],S)),E=p.map((R,_)=>le(L(x[1][_],v),L(R,S)));return{output:T,newStates:E}});h=b.output,p=b.newStates}o&&d.push(h)}let g;return o&&(g=lr(d,1)),[h,g,p]})}var U4=class extends st{constructor(e){super(e);let t;if(e.cell==null)throw new q("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new p0({cells:e.cell}):t=e.cell,t.stateSize==null)throw new q("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 Kt({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 ma(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){Ty(e)&&(e=e[0]),e=e;let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);let r=t[0],n;if(this.returnSequences?n=[e[0],e[1],r]:n=[e[0],r],this.returnState){let a=[];for(let s of t)a.push([e[0],s]);return[n].concat(a)}else return n}computeMask(e,t){return K(()=>{Array.isArray(t)&&(t=t[0]);let r=this.returnSequences?t:null;if(this.returnState){let n=this.states.map(a=>null);return[r].concat(n)}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 Ve("Constants support is not implemented in RNN yet.");Ty(e)&&(e=e[0]),e=e;let t=this.stateful?e[0]:null,r=e.slice(2);this.inputSpec[0]=new Kt({shape:[t,null,...r]});let n=[e[0]].concat(e.slice(2));this.cell.build(n);let a;if(Array.isArray(this.cell.stateSize)?a=this.cell.stateSize:a=[this.cell.stateSize],this.stateSpec!=null){if(!w.arraysEqual(this.stateSpec.map(s=>s.shape[s.shape.length-1]),a))throw new q(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=a.map(s=>new Kt({shape:[null,s]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){K(()=>{if(!this.stateful)throw new Ga("Cannot call resetStates() on an RNN Layer that is not stateful.");let r=this.inputSpec[0].shape[0];if(r==null)throw new q("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(n=>Pt([r,n])):this.states_=[Pt([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(n=>Pt([r,n])):this.states_[0]=Pt([r,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new q(`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 n=0;n<this.states_.length;++n){let a=e[n],s=Array.isArray(this.cell.stateSize)?this.cell.stateSize[n]:this.cell.stateSize,i=[r,s];if(!w.arraysEqual(a.shape,i))throw new q(`State ${n} is incompatible with layer ${this.name}: expected shape=${i}, received shape=${a.shape}`);this.states_[n]=a}}this.states_=this.states_.map(n=>fr(n.clone()))})}apply(e,t){let r=t==null?null:t.initialState,n=t==null?null:t.constants;t==null&&(t={});let a=W4(e,r,n,this.numConstants);e=a.inputs,r=a.initialState,n=a.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 Kt({shape:o.shape}));i=i.concat(this.stateSpec)}if(n!=null&&(t.constants=n,s=s.concat(n),this.numConstants=n.length),s[0]instanceof ua){let o=[e].concat(s),l=this.inputSpec.concat(i),u=this.inputSpec;this.inputSpec=l;let d=super.apply(o,t);return this.inputSpec=u,d}else return super.apply(e,t)}call(e,t){return K(()=>{let r=t==null?null:t.mask,n=t==null?null:t.training,a=t==null?null:t.initialState;e=je(e),a==null&&(this.stateful?a=this.states_:a=this.getInitialState(e));let s=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(a.length!==s)throw new q(`RNN Layer has ${s} state(s) but was passed ${a.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");let i={training:n},o=V4((p,c)=>{let f=this.cell.call([p].concat(c),i);return[f[0],f.slice(1)]},e,a,this.goBackwards,r,null,this.unroll,this.returnSequences),l=o[0],u=o[1],d=o[2];this.stateful&&this.resetStates(d,n);let h=this.returnSequences?u:l;return this.returnState?[h].concat(d):h})}getInitialState(e){return K(()=>{let t=Pt(e.shape);return t=ke(t,[1,2]),t=Sh(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(r=>r>1?Iy(t,[1,r]):t):this.cell.stateSize>1?[Iy(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()===U4.className&&(t.cell={className:this.cell.getClassName(),config:r}),{...r,...e,...t}}static fromConfig(e,t,r={}){let n=t.cell,a=ha(n,r);return new e(Object.assign(t,{cell:a}))}},as=U4;as.className="RNN";ue.registerClass(as);var Mh=class extends st{},u0=class extends Mh{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,mr(this.units,"units"),this.activation=Us(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Et(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Et(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Et(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Rt(e.kernelRegularizer),this.recurrentRegularizer=Rt(e.recurrentRegularizer),this.biasRegularizer=Rt(e.biasRegularizer),this.kernelConstraint=or(e.kernelConstraint),this.recurrentConstraint=or(e.recurrentConstraint),this.biasConstraint=or(e.biasConstraint),this.dropout=Tu([1,Ws([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Tu([1,Ws([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=ft(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 K(()=>{if(e=e,e.length!==2)throw new q(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let r=e[1];e=e[0];let n=t.training==null?!1:t.training;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Gs({ones:()=>Fn(e),rate:this.dropout,training:n,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Gs({ones:()=>Fn(r),rate:this.recurrentDropout,training:n,dropoutFunc:this.dropoutFunc}));let a,s=this.dropoutMask,i=this.recurrentDropoutMask;s!=null?a=Ea(L(e,s),this.kernel.read()):a=Ea(e,this.kernel.read()),this.bias!=null&&(a=xa(a,this.bias.read())),i!=null&&(r=L(r,i));let o=le(a,Ea(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:Vs(this.activation),useBias:this.useBias,kernelInitializer:_t(this.kernelInitializer),recurrentInitializer:_t(this.recurrentInitializer),biasInitializer:_t(this.biasInitializer),kernelRegularizer:xt(this.kernelRegularizer),recurrentRegularizer:xt(this.recurrentRegularizer),biasRegularizer:xt(this.biasRegularizer),activityRegularizer:xt(this.activityRegularizer),kernelConstraint:ir(this.kernelConstraint),recurrentConstraint:ir(this.recurrentConstraint),biasConstraint:ir(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return{...e,...t}}};u0.className="SimpleRNNCell";ue.registerClass(u0);var rx=class extends as{constructor(e){e.cell=new u0(e),super(e)}call(e,t){return K(()=>{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,n=t==null?null:t.training,a=t==null?null:t.initialState;return super.call(e,{mask:r,training:n,initialState:a})})}static fromConfig(e,t){return new e(t)}};rx.className="SimpleRNN";ue.registerClass(rx);var d0=class extends Mh{constructor(e){if(super(e),this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.resetAfter)throw new q("GRUCell does not support reset_after parameter set to true.");this.units=e.units,mr(this.units,"units"),this.activation=Us(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Us(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Et(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Et(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Et(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Rt(e.kernelRegularizer),this.recurrentRegularizer=Rt(e.recurrentRegularizer),this.biasRegularizer=Rt(e.biasRegularizer),this.kernelConstraint=or(e.kernelConstraint),this.recurrentConstraint=or(e.recurrentConstraint),this.biasConstraint=or(e.biasConstraint),this.dropout=Tu([1,Ws([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Tu([1,Ws([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=ft(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 K(()=>{if(e=e,e.length!==2)throw new q(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);let r=t.training==null?!1:t.training,n=e[1];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Gs({ones:()=>Fn(e),rate:this.dropout,training:r,count:3,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Gs({ones:()=>Fn(n),rate:this.recurrentDropout,training:r,count:3,dropoutFunc:this.dropoutFunc}));let a=this.dropoutMask,s=this.recurrentDropoutMask,i,o,l;0<this.dropout&&this.dropout<1&&(e=L(e,a[0]));let u=Ea(e,this.kernel.read());this.useBias&&(u=xa(u,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(n=L(n,s[0]));let d=this.recurrentKernel.read(),[h,p]=Xt(d,[2*this.units,this.units],d.rank-1),c=Ea(n,h),[f,m,g]=Xt(u,3,u.rank-1),[y,A]=Xt(c,2,c.rank-1);i=this.recurrentActivation.apply(le(f,y)),o=this.recurrentActivation.apply(le(m,A));let x=Ea(L(o,n),p);l=this.activation.apply(le(g,x));let b=le(L(i,n),L(le(1,Ot(i)),l));return[b,b]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:Vs(this.activation),recurrentActivation:Vs(this.recurrentActivation),useBias:this.useBias,kernelInitializer:_t(this.kernelInitializer),recurrentInitializer:_t(this.recurrentInitializer),biasInitializer:_t(this.biasInitializer),kernelRegularizer:xt(this.kernelRegularizer),recurrentRegularizer:xt(this.recurrentRegularizer),biasRegularizer:xt(this.biasRegularizer),activityRegularizer:xt(this.activityRegularizer),kernelConstraint:ir(this.kernelConstraint),recurrentConstraint:ir(this.recurrentConstraint),biasConstraint:ir(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return{...e,...t}}};d0.className="GRUCell";ue.registerClass(d0);var nx=class extends as{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 d0(e),super(e)}call(e,t){return K(()=>{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,n=t==null?null:t.training,a=t==null?null:t.initialState;return super.call(e,{mask:r,training:n,initialState:a})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};nx.className="GRU";ue.registerClass(nx);var Fh=class extends Mh{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,mr(this.units,"units"),this.activation=Us(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Us(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Et(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Et(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Et(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=Rt(e.kernelRegularizer),this.recurrentRegularizer=Rt(e.recurrentRegularizer),this.biasRegularizer=Rt(e.biasRegularizer),this.kernelConstraint=or(e.kernelConstraint),this.recurrentConstraint=or(e.recurrentConstraint),this.biasConstraint=or(e.biasConstraint),this.dropout=Tu([1,Ws([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Tu([1,Ws([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=ft(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 n;if(this.useBias){if(this.unitForgetBias){let a=this.biasInitializer,s=this.units;n=new(t=class extends Kn{apply(i,o){let l=a.apply([s]),u=new Zm().apply([s]),d=a.apply([s*2]);return K3(K3(l,u),d)}},t.className="CustomInit",t)}else n=this.biasInitializer;this.bias=this.addWeight("bias",[this.units*4],null,n,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return K(()=>{let r=t.training==null?!1:t.training;if(e=e,e.length!==3)throw new q(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let n=e[1],a=e[2];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Gs({ones:()=>Fn(e),rate:this.dropout,training:r,count:4,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Gs({ones:()=>Fn(n),rate:this.recurrentDropout,training:r,count:4,dropoutFunc:this.dropoutFunc}));let s=this.dropoutMask,i=this.recurrentDropoutMask,o,l,u,d;0<this.dropout&&this.dropout<1&&(e=L(e,s[0]));let h=Ea(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(n=L(n,i[0])),h=le(h,Ea(n,this.recurrentKernel.read())),this.useBias&&(h=xa(h,this.bias.read()));let[p,c,f,m]=Xt(h,4,h.rank-1);o=this.recurrentActivation.apply(p),l=this.recurrentActivation.apply(c),u=le(L(l,a),L(o,this.activation.apply(f))),d=this.recurrentActivation.apply(m);let g=L(d,this.activation.apply(u));return[g,g,u]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:Vs(this.activation),recurrentActivation:Vs(this.recurrentActivation),useBias:this.useBias,kernelInitializer:_t(this.kernelInitializer),recurrentInitializer:_t(this.recurrentInitializer),biasInitializer:_t(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:xt(this.kernelRegularizer),recurrentRegularizer:xt(this.recurrentRegularizer),biasRegularizer:xt(this.biasRegularizer),activityRegularizer:xt(this.activityRegularizer),kernelConstraint:ir(this.kernelConstraint),recurrentConstraint:ir(this.recurrentConstraint),biasConstraint:ir(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return{...e,...t}}};Fh.className="LSTMCell";ue.registerClass(Fh);var ax=class extends as{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 Fh(e),super(e)}call(e,t){return K(()=>{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,n=t==null?null:t.training,a=t==null?null:t.initialState;return super.call(e,{mask:r,training:n,initialState:a})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};ax.className="LSTM";ue.registerClass(ax);var p0=class extends Mh{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 K(()=>{e=e;let r=e.slice(1),n=[];for(let i of this.cells.slice().reverse())Array.isArray(i.stateSize)?n.push(r.splice(0,i.stateSize.length)):n.push(r.splice(0,1));n.reverse();let a=[],s;for(let i=0;i<this.cells.length;++i){let o=this.cells[i];r=n[i],i===0?s=[e[0]].concat(r):s=[s[0]].concat(r),s=o.call(s,t),a.push(s.slice(1))}r=[];for(let i of a.slice().reverse())r.push(...i);return[s[0]].concat(r)})}build(e){Ty(e)&&(e=e[0]),e=e;let t;this.cells.forEach((r,n)=>{To(`RNNCell_${n}`,()=>{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=n=>({className:n.getClassName(),config:n.getConfig()}),r={cells:this.cells.map(t)};return{...e,...r}}static fromConfig(e,t,r={}){let n=[];for(let a of t.cells)n.push(ha(a,r));return new e({cells:n})}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 Ny(e)}setWeights(e){let t=[];for(let r of this.cells){let n=r.weights.length,a=e.splice(n);for(let s=0;s<r.weights.length;++s)t.push([r.weights[s],a[s]])}TA(t)}};p0.className="StackedRNNCells";ue.registerClass(p0);function Gs(e){let{ones:t,rate:r,training:n=!1,count:a=1,dropoutFunc:s}=e,i=()=>s!=null?s(t(),r):X7(t(),r),o=()=>Nh(i,t,n);return!a||a<=1?fr(o().clone()):Array(a).fill(void 0).map(o).map(l=>fr(l.clone()))}var G4=class extends as{constructor(e){if(e.unroll)throw new Ve("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new Ve("It is not possible at the moment to stack convolutional cells.");super(e),this.inputSpec=[new Kt({ndim:5})]}call(e,t){return K(()=>{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 q("ConvRNN2D cell does not support constants");let r=t==null?null:t.mask,n=t==null?null:t.training,a=t==null?null:t.initialState;return super.call(e,{mask:r,training:n,initialState:a})})}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 K(()=>{let{stateSize:t}=this.cell,r=e.shape,n=this.computeSingleOutputShape(r),a=[n[0],...n.slice(2)],s=Pt(a);return Array.isArray(t)?Array(t.length).fill(s):[s]})}resetStates(e,t=!1){K(()=>{if(!this.stateful)throw new Ga("Cannot call resetStates() on an RNN Layer that is not stateful.");let r=this.inputSpec[0].shape,n=this.computeSingleOutputShape(r),a=[n[0],...n.slice(2)];if(r[0]==null)throw new q("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(()=>Pt(a)):this.states_=[Pt(a)];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(()=>Pt(a)):this.states_[0]=Pt(a);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new q(`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=a;if(!w.arraysEqual(i.shape,o))throw new q(`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=>fr(s.clone()))})}computeSingleOutputShape(e){let{dataFormat:t,filters:r,kernelSize:n,padding:a,strides:s,dilationRate:i}=this.cell,o=t==="channelsFirst",l=e[o?3:2],u=e[o?4:3],d=ca(l,n[0],a,s[0],i[0]),h=ca(u,n[1],a,s[1],i[1]);return[...e.slice(0,2),...o?[r,d,h]:[d,h,r]]}};G4.className="ConvRNN2D";var h0=class extends Fh{constructor(e){let{filters:t,kernelSize:r,strides:n,padding:a,dataFormat:s,dilationRate:i}=e;super({...e,units:t}),this.filters=t,mr(this.filters,"filters"),this.kernelSize=yu(r,2,"kernelSize"),this.kernelSize.forEach(o=>mr(o,"kernelSize")),this.strides=yu(n||1,2,"strides"),this.strides.forEach(o=>mr(o,"strides")),this.padding=a||"valid",On(this.padding),this.dataFormat=s||"channelsLast",Gt(this.dataFormat),this.dilationRate=yu(i||1,2,"dilationRate"),this.dilationRate.forEach(o=>mr(o,"dilationRate"))}build(e){var t;e=ft(e);let r=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[r]==null)throw new q(`The channel dimension of the input should be defined. Found ${e[r]}`);let n=e[r],a=4,s=this.kernelSize.concat([n,this.filters*a]);this.kernel=this.addWeight("kernel",s,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);let i=this.kernelSize.concat([this.filters,this.filters*a]);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,u=this.filters;o=new(t=class extends Kn{apply(d,h){let p=l.apply([u]),c=hn([u]),f=l.apply([u*2]);return AA([p,c,f])}},t.className="CustomInit",t)}else o=this.biasInitializer;this.bias=this.addWeight("bias",[this.filters*a],null,o,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return K(()=>{if(e.length!==3)throw new q(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let r=t.training||!1,n=e[0],a=e[1],s=e[2],i=4;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=Gs({ones:()=>Fn(n),rate:this.dropout,training:r,count:i,dropoutFunc:this.dropoutFunc}));let o=this.dropoutMask,l=(V,ee,J)=>!ee||!ee[J]?V:L(ee[J],V),u=l(n,o,0),d=l(n,o,1),h=l(n,o,2),p=l(n,o,3);0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=Gs({ones:()=>Fn(a),rate:this.recurrentDropout,training:r,count:i,dropoutFunc:this.dropoutFunc}));let c=this.recurrentDropoutMask,f=l(a,c,0),m=l(a,c,1),g=l(a,c,2),y=l(a,c,3),A=3,[x,b,v,S]=Xt(this.kernel.read(),i,A),[T,E,R,_]=this.useBias?Xt(this.bias.read(),i):[null,null,null,null];u=this.inputConv(u,x,T,this.padding),d=this.inputConv(d,b,E,this.padding),h=this.inputConv(h,v,R,this.padding),p=this.inputConv(p,S,_,this.padding);let[M,I,z,O]=Xt(this.recurrentKernel.read(),i,A);f=this.recurrentConv(f,M),m=this.recurrentConv(m,I),g=this.recurrentConv(g,z),y=this.recurrentConv(y,O);let j=this.recurrentActivation.apply(le(u,f)),X=this.recurrentActivation.apply(le(d,m)),D=le(L(X,s),L(j,this.activation.apply(le(h,g)))),Q=L(this.recurrentActivation.apply(le(p,y)),this.activation.apply(D));return[Q,Q,D]})}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,n){let a=Os(e,t,this.strides,n||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return r?xa(a,r,this.dataFormat):a}recurrentConv(e,t){return Os(e,t,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}};h0.className="ConvLSTM2DCell";ue.registerClass(h0);var sx=class extends G4{constructor(e){let t=new h0(e);super({...e,cell:t})}static fromConfig(e,t){return new e(t)}};sx.className="ConvLSTM2D";ue.registerClass(sx);var c0=class extends st{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 n=0;n<this.noiseShape.length;++n)r.push(this.noiseShape[n]==null?t[n]:this.noiseShape[n]);return r}call(e,t){return K(()=>{this.invokeCallHook(e,t);let r=je(e);if(0<this.rate&&this.rate<1){let n=t.training==null?!1:t.training,a=this.getNoiseShape(r);return Nh(()=>X7(r,this.rate,a,this.seed),()=>r,n)}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()}};c0.className="Dropout";ue.registerClass(c0);var ix=class extends c0{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){let t=e.shape;return[t[0],1,t[2]]}};ix.className="SpatialDropout1D";ue.registerClass(ix);var ox=class extends st{constructor(e){if(super(e),this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.batchInputShape==null&&e.inputShape==null&&e.inputDim!=null){let t=null;e.batchSize!=null&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,mr(this.units,"units"),this.activation=Us(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=Et(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=Et(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=or(e.kernelConstraint),this.biasConstraint=or(e.biasConstraint),this.kernelRegularizer=Rt(e.kernelRegularizer),this.biasRegularizer=Rt(e.biasRegularizer),this.activityRegularizer=Rt(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=ft(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=ft(e);let t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return K(()=>{this.invokeCallHook(e,t);let r=je(e),n=V7(this.activation.getClassName()),a;return n!=null?a=Ea(r,this.kernel.read(),n,this.bias?this.bias.read():null):(a=Ea(r,this.kernel.read()),this.bias!=null&&(a=xa(a,this.bias.read())),this.activation!=null&&(a=this.activation.apply(a))),a})}getConfig(){let e={units:this.units,activation:Vs(this.activation),useBias:this.useBias,kernelInitializer:_t(this.kernelInitializer),biasInitializer:_t(this.biasInitializer),kernelRegularizer:xt(this.kernelRegularizer),biasRegularizer:xt(this.biasRegularizer),activityRegularizer:xt(this.activityRegularizer),kernelConstraint:ir(this.kernelConstraint),biasConstraint:ir(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}};ox.className="Dense";ue.registerClass(ox);var lx=class extends st{constructor(e){e=e||{},super(e),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=ft(e);for(let t of e.slice(1))if(t==null)throw new q(`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],Rs(e,1)]}call(e,t){return K(()=>{this.invokeCallHook(e,t);let r=je(e);if(this.dataFormat==="channelsFirst"&&r.rank>1){let n=[0];for(let a=2;a<r.rank;++a)n.push(a);n.push(1),r=tt(r,n)}return BL(r)})}getConfig(){let e={};this.dataFormat!=null&&(e.dataFormat=this.dataFormat);let t=super.getConfig();return Object.assign(e,t),e}};lx.className="Flatten";ue.registerClass(lx);var ux=class extends st{constructor(e){super(e),this.supportsMasking=!0,this.activation=Us(e.activation)}call(e,t){return K(()=>{this.invokeCallHook(e,t);let r=je(e);return this.activation.apply(r)})}getConfig(){let e={activation:Vs(this.activation)},t=super.getConfig();return Object.assign(e,t),e}};ux.className="Activation";ue.registerClass(ux);var dx=class extends st{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 K(()=>(e=je(e),DL(e,this.n)))}getConfig(){let e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}};dx.className="RepeatVector";ue.registerClass(dx);var px=class extends st{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.",n=t.slice(),a=1,s=null;for(let o=0;o<n.length;++o){let l=n[o];if(this.isUnknown(l))if(s===null)s=o;else throw new q("Can only specifiy one unknown dimension.");else a*=l}let i=Rs(e);if(s!==null){if(a===0||i%a!==0)throw new q(r);n[s]=i/a}else if(i!==a)throw new q(r);return n}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 K(()=>{this.invokeCallHook(e,t);let r=je(e),n=r.shape,a=n.slice(0,1).concat(this.fixUnknownDimension(n.slice(1),this.targetShape));return G(r,a)})}getConfig(){let e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}};px.className="Reshape";ue.registerClass(px);var hx=class extends st{constructor(e){if(super(e),e.dims==null)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);let t=ma(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 Kt({ndim:this.dims.length+1})]}computeOutputShape(e){e=ft(e);let t=e.slice();return this.dims.forEach((r,n)=>{t[n+1]=e[r]}),t}call(e,t){return tt(je(e),this.dimsIncludingBatch)}getConfig(){let e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}};hx.className="Permute";ue.registerClass(hx);var cx=class extends st{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=je(e),n=-1;return wf(Iu(r,this.maskValue),n)}call(e,t){return K(()=>{this.invokeCallHook(e,t);let r=je(e),n=-1,a=!0,s=wf(Iu(r,this.maskValue),n,a);return L(r,me(s,r.dtype))})}};cx.className="Masking";ue.registerClass(cx);var fx=class extends st{constructor(e){if(super(e),this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",e.batchInputShape==null&&e.inputShape==null){let t=null;e.batchSize!=null&&(t=e.batchSize),e.inputLength==null?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(It(e.inputLength))}this.inputDim=e.inputDim,mr(this.inputDim,"inputDim"),this.outputDim=e.outputDim,mr(this.outputDim,"outputDim"),this.embeddingsInitializer=Et(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=Rt(e.embeddingsRegularizer),this.activityRegularizer=Rt(e.activityRegularizer),this.embeddingsConstraint=or(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 K(()=>this.maskZero?(e=je(e),Iu(e,at(e))):null)}computeOutputShape(e){if(e=ft(e),this.inputLength==null)return[...e,this.outputDim];let t=It(this.inputLength);if(t.length!==e.length-1)throw new q(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let r=0;for(let n=0;n<t.length;++n){let a=t[n],s=e[n+1];if(a!=null&&s!=null&&a!==s)throw new q(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);a==null&&(t[r]=s),r++}}return[e[0],...t,this.outputDim]}call(e,t){return K(()=>{this.invokeCallHook(e,t);let r=je(e);r.dtype!=="int32"&&(r=Km(r,"int32"));let n=K7(this.embeddings.read(),G(r,[r.size]));return G(n,ft(this.computeOutputShape(r.shape)))})}getConfig(){let e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:_t(this.embeddingsInitializer),embeddingsRegularizer:xt(this.embeddingsRegularizer),activityRegularizer:xt(this.activityRegularizer),embeddingsConstraint:ir(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}};fx.className="Embedding";ue.registerClass(fx);var Pl=class extends st{constructor(e){super(e||{}),this.supportsMasking=!0}mergeFunction(e){throw new Ve}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 n=0;n<t.length;++n){let a=e[e.length-t.length+n],s=t[n];if(a==null||s==null||a<0||s<0)r.push(null);else if(a===1)r.push(s);else if(s===1)r.push(a);else{if(a!==s)throw new q("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));r.push(a)}}return r}build(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[ft(e)]),e=e,e.length<2)throw new q(`A merge layer should be called on an Array of at least 2 inputs. Got ${e.length} input(s).`);let t=[];for(let a of e)a!=null&&a[0]!==null&&t.push(a[0]);if(t=Es(t),t.length>1)throw new q(`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 a=1;a<e.length;++a){let s=e[a]==null?null:e[a].slice(1);r=this.computeElementwiseOpOutputShape(r,s)}let n=e.map(a=>a.length);e.indexOf(null)===-1&&Es(n).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return K(()=>{if(e=e,this.reshapeRequired){let r=[],n=e.map(a=>a.rank);if(n.indexOf(null)===-1){let a=Ws(n);for(let s of e){let i=s.rank;for(let o=0;o<a-i;++o)s=Sh(s,1);r.push(s)}return this.mergeFunction(r)}else{let a=!1;for(let o of e){let l=o.rank;if(l==null){let u=o.shape,d=u[0],h=u.slice(1).concat([d]),p=G(o,[d].concat(Rs(u.slice(1))));p=tt(p,[1,0]),p=G(p,h),r.push(p),a=!0}else if(l>1){let u=ma(1,l).concat([0]);r.push(tt(o,u)),a=!0}else r.push(o)}let s=this.mergeFunction(r),i=s.rank;if(a){if(i==null){let o=s.shape,l=o.length,u=o[l-1],d=[u].concat(o.slice(0,o.length-1));s=G(tt(G(s,[-1,u]),[1,0]),d)}else if(i>1){let o=[i-1].concat(ma(0,i-1));s=tt(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 n=1;n<e.length;++n){let a=e[n]==null?null:e[n].slice(1);t=this.computeElementwiseOpOutputShape(t,a)}let r=[];for(let n of e)n!=null&&n[0]!==null&&r.push(n[0]);return r=Es(r),r.length===1?t=r.concat(t):t=[null].concat(t),t}computeMask(e,t){return K(()=>{if(t==null)return null;if(!Array.isArray(t))throw new q("`mask` should be an Array");if(!Array.isArray(e))throw new q("`inputs` should be an Array");if(t.length!==e.length)throw new q(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every(n=>n==null))return null;t=t.map(n=>n==null?n:qt(n,0));let r=t[0];for(let n=1;n<t.length-1;++n)r=fa(r,t[n]);return r})}},mx=class extends Pl{constructor(e){super(e)}mergeFunction(e){return K(()=>{let t=e[0].clone();for(let r=1;r<e.length;++r)t=le(t,e[r]);return t})}};mx.className="Add";ue.registerClass(mx);var gx=class extends Pl{constructor(e){super(e)}mergeFunction(e){return K(()=>{let t=e[0].clone();for(let r=1;r<e.length;++r)t=L(t,e[r]);return t})}};gx.className="Multiply";ue.registerClass(gx);var yx=class extends Pl{constructor(e){super(e)}mergeFunction(e){return K(()=>{let t=e[0].clone();for(let r=1;r<e.length;++r)t=le(t,e[r]);return L(1/e.length,t)})}};yx.className="Average";ue.registerClass(yx);var Ax=class extends Pl{constructor(e){super(e)}mergeFunction(e){return K(()=>{let t=e[0];for(let r=1;r<e.length;++r)t=ts(t,e[r]);return t})}};Ax.className="Maximum";ue.registerClass(Ax);var xx=class extends Pl{constructor(e){super(e)}mergeFunction(e){return K(()=>{let t=e[0];for(let r=1;r<e.length;++r)t=vh(t,e[r]);return t})}};xx.className="Minimum";ue.registerClass(xx);var bx=class extends Pl{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 q("A `Concatenate` layer should be called on a list of at least 2 inputs");e=e;let t=!0;for(let n of e)if(n!=null){t=!1;break}if(t)return;let r=[];for(let n=0;n<e.length;++n){let a=e[n].slice();a.splice(this.axis,1);let s=!1;for(let i of r)if(w.arraysEqual(i,a)){s=!0;break}s||r.push(a)}if(r.length>1)throw new q("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return K(()=>AA(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new q("A `Concatenate` layer should be called on a list of inputs.");let t=e,r=t[0].slice(),n=this.axis<0?r.length+this.axis:this.axis;for(let a of t.slice(1)){if(r[n]==null||a[n]==null){r[n]=null;break}r[n]+=a[n]}return r}computeMask(e,t){if(t==null)return null;if(!Array.isArray(t))throw new q("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new q("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new q(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return K(()=>{let r=!0;if(t.forEach(s=>{if(s!=null){r=!1;return}}),r)return null;let n=[];for(let s=0;s<e.length;++s)t[s]==null?n.push(me(Fn(e[s]),"bool")):t[s].rank<e[s].rank?n.push(qt(t[s],-1)):n.push(t[s]);let a=kt(n,this.axis);return $2(a,-1,!1)})}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};bx.className="Concatenate";ue.registerClass(bx);function mp(e,t){for(;e<0;)e+=t;return e}function RU(e,t,r){if(e.shape.length>3||t.shape.length>3)throw new Ve("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 Ve("batchDot is not implemented for complex64-type Tensors yet.");let n=e.shape.length,a=t.shape.length;r==null&&(r=[n-1,a-2]);let s=r;return K(()=>{let i;if(n>a){i=n-a;let l=[];for(let u=0;u<i;++u)l.push(1);t=G(t,t.shape.concat(l))}else if(a>n){i=a-n;let l=[];for(let u=0;u<i;++u)l.push(1);e=G(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(tt(e,[1,0]),t),s[1]);else{let l=s[0]!==e.shape.length-1,u=s[1]===t.shape.length-1;o=Je(e,t,l,u)}if(i>0){let l;n>a?l=n+a-3:l=n-1;let u=[];for(let d=l;d<l+i;++d)u.push(d);o=rt(o,u)}return o.shape.length===1&&(o=qt(o,1)),o})}var vx=class extends Pl{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 Ve("Dot layer does not support tensors of 4D or higher rank yet.");let n=this.interpretAxes(t,r);if(t[n[0]]!==r[n[1]])throw new q(`Dimension incompatibility: ${t[n[0]]} !== ${r[n[1]]}`)}mergeFunction(e){if(e.length!==2)throw new q(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t=e[0],r=e[1],n;return Array.isArray(this.axes)?n=this.axes.map((a,s)=>mp(a,e[s].shape.length)):n=[mp(this.axes,t.shape.length),mp(this.axes,r.shape.length)],this.normalize&&(t=Ef(t,n[0]),r=Ef(r,n[1])),RU(t,r,n)}interpretAxes(e,t){let r;return Array.isArray(this.axes)?r=this.axes:r=[mp(this.axes,e.length),mp(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 Ve("Dot layer does not support tensors of 4D or higher rank yet.");let n=this.interpretAxes(t,r);t.splice(n[0],1),r.splice(n[1],1),r.splice(0,1);let a=t.concat(r);return a.length===1&&a.push(1),a}computeMask(e,t){return null}getConfig(){let e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}};vx.className="Dot";ue.registerClass(vx);var wx=class extends st{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 K(()=>{this.invokeCallHook(e,t);let r=je(e);return Nh(()=>le(Xm(r.shape,0,this.stddev),r),()=>r,t.training||!1)})}};wx.className="GaussianNoise";ue.registerClass(wx);var kx=class extends st{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 K(()=>{this.invokeCallHook(e,t);let r=je(e);return this.rate>0&&this.rate<1?Nh(()=>{let n=Math.sqrt(this.rate/(1-this.rate));return L(r,Xm(r.shape,1,n))},()=>r,t.training||!1):r})}};kx.className="GaussianDropout";ue.registerClass(kx);var Ix=class extends st{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||je(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 K(()=>{if(this.rate<1&&this.rate>0){let r=this._getNoiseShape(e);return Nh(()=>{let n=je(e),a=1.6732632423543772,s=1.0507009873554805,i=-a*s,o=El(cd(r),this.rate);o=Km(o,"float32");let l=((1-this.rate)*(1+this.rate*i**2))**-.5,u=-l*i*this.rate,d=le(L(n,o),L(le(o,-1),i));return le(L(d,l),u)},()=>je(e),t.training||!1)}return e})}};Ix.className="AlphaDropout";ue.registerClass(Ix);function Gp(e,t,r,n,a,s=.001){let i;if(e.rank===2)i=Ok(e,t,r,n,a,s);else if(e.rank===3)i=Dk(e,t,r,n,a,s);else if(e.rank===4)i=Lk(e,t,r,n,a,s);else throw new Ve(`batchNormalization is not implemented for array of rank ${e.rank} yet`);return i}function MU(e,t,r,n,a=.001){return K(()=>{let s=Rm(e,n),i=s.mean,o=s.variance;return[Gp(e,i,o,r,t,a),i,o]})}function FU(e,t,r,n,a=.001){return K(()=>{let s=Rm(e,n),i=s.mean,o=s.variance,l=[];for(let c of ma(0,e.rank))n.indexOf(c)!==-1?l.push(1):l.push(e.shape[c]);let u=G(i,l),d=G(o,l),h=t==null?null:G(t,l),p=r==null?null:G(r,l);return[Gp(e,u,d,p,h,a),i,o]})}function $U(e,t,r,n,a=.001){return w.arraysEqual(n.slice().sort(),ma(0,e.rank-1))?MU(e,t,r,n,a):FU(e,t,r,n,a)}var Sx=class extends st{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=Et(e.betaInitializer||"zeros"),this.gammaInitializer=Et(e.gammaInitializer||"ones"),this.movingMeanInitializer=Et(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=Et(e.movingVarianceInitializer||"ones"),this.betaConstraint=or(e.betaConstraint),this.gammaConstraint=or(e.gammaConstraint),this.betaRegularizer=Rt(e.betaRegularizer),this.gammaRegularizer=Rt(e.gammaRegularizer)}build(e){e=ft(e);let t=this.axis>=0?this.axis:this.axis+e.length,r=e[t];if(r==null)throw new q(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new Kt({ndim:e.length,axes:{[t]:r}})];let n=[r];this.scale&&(this.gamma=this.addWeight("gamma",n,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",n,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",n,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",n,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return K(()=>{let r=t.training==null?!1:t.training,n=je(e),a=n.shape,s=a.length,i=ma(0,s),o=this.axis>=0?this.axis:this.axis+s;i.splice(o,1);let l=Po(1,s);l[o]=a[o];let u=i.slice();u.sort();let d=!w.arraysEqual(u,ma(0,s).slice(0,s-1)),h=()=>{if(d){let g=G(this.movingMean.read(),l),y=G(this.movingVariance.read(),l),A=this.center?G(this.beta.read(),l):null,x=this.scale?G(this.gamma.read(),l):null;return Gp(n,g,y,A,x,this.epsilon)}else return Gp(n,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 h();let[p,c,f]=$U(n,this.gamma.read(),this.beta.read(),i,this.epsilon),m=(g,y,A)=>{K(()=>{let x=1-A,b=g.read(),v=L(ce(b,y),x);g.write(ce(b,v))})};return m(this.movingMean,c,this.momentum),m(this.movingVariance,f,this.momentum),p})}getConfig(){let e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:_t(this.betaInitializer),gammaInitializer:_t(this.gammaInitializer),movingMeanInitializer:_t(this.movingMeanInitializer),movingVarianceInitializer:_t(this.movingVarianceInitializer),betaRegularizer:xt(this.betaRegularizer),gammaRegularizer:xt(this.gammaRegularizer),betaConstraint:ir(this.betaConstraint),gammaConstraint:ir(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}};Sx.className="BatchNormalization";ue.registerClass(Sx);var Tx=class extends st{constructor(e){if(e==null&&(e={}),super(e),this.axis=e.axis==null?-1:e.axis,typeof this.axis=="number"){if(!Number.isInteger(this.axis))throw new Error(`Expected axis to be an integer, but received ${this.axis}`)}else if(Array.isArray(this.axis)){for(let t of this.axis)if(!Number.isInteger(t))throw new Error(`Expected axis to be an array of integers, but received ${JSON.stringify(this.axis)}`)}else throw new Error(`Expected axis to be an integer or an array of integers, but received ${JSON.stringify(this.axis)}`);this.epsilon=e.epsilon==null?.001:e.epsilon,this.center=e.center==null?!0:e.center,this.scale=e.scale==null?!0:e.scale,this.betaInitializer=Et(e.betaInitializer||"zeros"),this.gammaInitializer=Et(e.gammaInitializer||"ones"),this.betaRegularizer=Rt(e.betaRegularizer),this.gammaRegularizer=Rt(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=ft(e);let t=e.length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let a=0;a<this.axis.length;++a)this.axis[a]<0&&(this.axis[a]+=t);for(let a of this.axis)if(a<0||a>=t)throw new Error(`Invalid axis: ${a}`);if(this.axis.length!==Es(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);let r=this.axis.map(a=>e[a]),n=!0;this.scale?this.gamma=this.addWeight("gamma",r,"float32",this.gammaInitializer,this.gammaRegularizer,n):this.gamma=null,this.center?this.beta=this.addWeight("beta",r,"float32",this.betaInitializer,this.betaRegularizer,n):this.beta=null,this.built=!0}call(e,t){let r=je(e),n=r.shape,a=n.length;return K(()=>{let{mean:s,variance:i}=Rm(r,this.axis,!0),o=Po(1,a);for(let c of this.axis)o[c]=n[c];let l=c=>c!=null&&c.shape.length!==a?G(c,o):c,u=l(this.gamma.read()),d=l(this.beta.read()),h=[],p=[];for(let c=0;c<a;++c)this.axis.indexOf(c)!==-1?(h.push(n[c]),p.push(1)):(h.push(1),p.push(n[c]));return s=Vn(s,h),i=Vn(i,h),u=Vn(u,p),d=Vn(d,p),Gp(r,s,i,d,u,this.epsilon)})}getConfig(){let e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:_t(this.betaInitializer),gammaInitializer:_t(this.gammaInitializer),betaRegularizer:xt(this.betaRegularizer),gammaRegularizer:xt(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}};Tx.className="LayerNormalization";ue.registerClass(Tx);function PU(e,t,r){return K(()=>{if(e.rank!==4)throw new q(`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 q("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(r==null&&(r=ga()),r!=="channelsLast"&&r!=="channelsFirst")throw new q(`Unknown data format: ${r}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let n;return r==="channelsFirst"?n=[[0,0],[0,0],t[0],t[1]]:n=[[0,0],t[0],t[1],[0,0]],Hn(e,n)})}var Nx=class extends st{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?ga():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 q(`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 q(`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 q(`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 Kt({ndim:4})]}computeOutputShape(e){e=ft(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 K(()=>PU(je(e),this.padding,this.dataFormat))}getConfig(){let e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};Nx.className="ZeroPadding2D";ue.registerClass(Nx);function f0(e,t,r,n,a,s){return K(()=>{Gt(a),G7(s),On(n),r==null&&(r=[1,1]),n==null&&(n="valid"),a==null&&(a=ga()),s==null&&(s="max"),e=qA(e,a);let i,o=n==="same"?"same":"valid";return s==="max"?i=Em(e,t,r,o):i=vm(e,t,r,o),a==="channelsFirst"&&(i=tt(i,[0,3,1,2])),i})}function j4(e,t,r,n,a,s){return K(()=>{Gt(a),G7(s),On(n),r==null&&(r=[1,1,1]),n==null&&(n="valid"),a==null&&(a=ga()),s==null&&(s="max"),e=z4(e,a);let i,o=n==="same"?"same":"valid";return s==="max"?i=X2(e,t,r,o):i=_2(e,t,r,o),a==="channelsFirst"&&(i=tt(i,[0,4,1,2,3])),i})}var H4=class extends st{constructor(e){if(e.poolSize==null&&(e.poolSize=2),super(e),typeof e.poolSize=="number")this.poolSize=[e.poolSize];else if(Array.isArray(e.poolSize)&&e.poolSize.length===1&&typeof e.poolSize[0]=="number")this.poolSize=e.poolSize;else throw new q(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(mr(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 q(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);mr(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,On(this.padding),this.inputSpec=[new Kt({ndim:3})]}computeOutputShape(e){e=ft(e);let t=ca(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return K(()=>{this.invokeCallHook(e,t),e=Sh(je(e),2);let r=this.poolingFunction(je(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return rt(r,[2])})}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}},Cx=class extends H4{constructor(e){super(e)}poolingFunction(e,t,r,n,a){return Gt(a),On(n),f0(e,t,r,n,a,"max")}};Cx.className="MaxPooling1D";ue.registerClass(Cx);var Ex=class extends H4{constructor(e){super(e)}poolingFunction(e,t,r,n,a){return Gt(a),On(n),f0(e,t,r,n,a,"avg")}};Ex.className="AveragePooling1D";ue.registerClass(Ex);var q4=class extends st{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==2)throw new q(`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];mr(this.poolSize,"poolSize"),mr(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Gt(this.dataFormat),On(this.padding),this.inputSpec=[new Kt({ndim:4})]}computeOutputShape(e){e=ft(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],r=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=ca(t,this.poolSize[0],this.padding,this.strides[0]),r=ca(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 K(()=>(this.invokeCallHook(e,t),this.poolingFunction(je(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}},Rx=class extends q4{constructor(e){super(e)}poolingFunction(e,t,r,n,a){return Gt(a),On(n),f0(e,t,r,n,a,"max")}};Rx.className="MaxPooling2D";ue.registerClass(Rx);var Mx=class extends q4{constructor(e){super(e)}poolingFunction(e,t,r,n,a){return Gt(a),On(n),f0(e,t,r,n,a,"avg")}};Mx.className="AveragePooling2D";ue.registerClass(Mx);var K4=class extends st{constructor(e){if(e.poolSize==null&&(e.poolSize=[2,2,2]),super(e),this.poolSize=Array.isArray(e.poolSize)?e.poolSize:[e.poolSize,e.poolSize,e.poolSize],e.strides==null)this.strides=this.poolSize;else if(Array.isArray(e.strides)){if(e.strides.length!==3)throw new q(`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];mr(this.poolSize,"poolSize"),mr(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Gt(this.dataFormat),On(this.padding),this.inputSpec=[new Kt({ndim:5})]}computeOutputShape(e){e=ft(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],r=this.dataFormat==="channelsFirst"?e[3]:e[2],n=this.dataFormat==="channelsFirst"?e[4]:e[3];return t=ca(t,this.poolSize[0],this.padding,this.strides[0]),r=ca(r,this.poolSize[1],this.padding,this.strides[1]),n=ca(n,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,r,n]:[e[0],t,r,n,e[4]]}call(e,t){return K(()=>(this.invokeCallHook(e,t),this.poolingFunction(je(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}},Fx=class extends K4{constructor(e){super(e)}poolingFunction(e,t,r,n,a){return Gt(a),On(n),j4(e,t,r,n,a,"max")}};Fx.className="MaxPooling3D";ue.registerClass(Fx);var $x=class extends K4{constructor(e){super(e)}poolingFunction(e,t,r,n,a){return Gt(a),On(n),j4(e,t,r,n,a,"avg")}};$x.className="AveragePooling3D";ue.registerClass($x);var X4=class extends st{constructor(e){super(e),this.inputSpec=[new Kt({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Ve}},Px=class extends X4{constructor(e){super(e||{})}call(e,t){return K(()=>{let r=je(e);return Wt(r,1)})}};Px.className="GlobalAveragePooling1D";ue.registerClass(Px);var _x=class extends X4{constructor(e){super(e||{})}call(e,t){return K(()=>{let r=je(e);return gr(r,1)})}};_x.className="GlobalMaxPooling1D";ue.registerClass(_x);var Z4=class extends st{constructor(e){super(e),this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Gt(this.dataFormat),this.inputSpec=[new Kt({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new Ve}getConfig(){let e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},zx=class extends Z4{call(e,t){return K(()=>{let r=je(e);return this.dataFormat==="channelsLast"?Wt(r,[1,2]):Wt(r,[2,3])})}};zx.className="GlobalAveragePooling2D";ue.registerClass(zx);var Ox=class extends Z4{call(e,t){return K(()=>{let r=je(e);return this.dataFormat==="channelsLast"?gr(r,[1,2]):gr(r,[2,3])})}};Ox.className="GlobalMaxPooling2D";ue.registerClass(Ox);var Y4=class extends st{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 n=t.layer,a=ha(n,r);delete t.layer;let s={layer:a};return Object.assign(s,t),new e(s)}},Dx=class extends Y4{constructor(e){super(e),this.supportsMasking=!0}build(e){if(e=ft(e),e.length<3)throw new q(`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=ft(e);let t=[e[0]].concat(e.slice(2)),r=this.layer.computeOutputShape(t),n=e[1];return[r[0],n].concat(r.slice(1))}call(e,t){return K(()=>(e=je(e),V4((r,n)=>[je(this.layer.call(r,t)),[]],e,[],!1,null,null,!1,!0)[1]))}};Dx.className="TimeDistributed";ue.registerClass(Dx);function _U(e){Fl($L,"BidirectionalMergeMode",e)}var zU="concat",Lx=class extends Y4{constructor(e){super(e);let t=e.layer.getConfig(),r={};r.className=e.layer.getClassName(),r.config=t,this.forwardLayer=ha(r),t.goBackwards=t.goBackwards!==!0;let n={};if(n.className=e.layer.getClassName(),n.config=t,this.backwardLayer=ha(n),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?zU:e.mergeMode,_U(this.mergeMode),e.weights)throw new Ve("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,n,a;return this.returnState&&(a=t.slice(1)),r=t[0],r=r,this.mergeMode==="concat"?(r[r.length-1]*=2,n=[r]):this.mergeMode==null?n=[r,r.slice()]:n=[r],this.returnState?this.mergeMode==null?n.concat(a).concat(a.slice()):[r].concat(a).concat(a.slice()):en(n)}apply(e,t){let r=t==null?null:t.initialState,n=t==null?null:t.constants;t==null&&(t={});let a=W4(e,r,n,this.numConstants);if(e=a.inputs,r=a.initialState,n=a.constants,Array.isArray(e)&&(r=e.slice(1),e=e[0]),(r==null||r.length===0)&&n==null)return super.apply(e,t);let s=[],i=[];if(r!=null){let l=r.length;if(l%2>0)throw new q("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 u=r.map(d=>new Kt({shape:d.shape}));this.forwardLayer.stateSpec=u.slice(0,l/2),this.backwardLayer.stateSpec=u.slice(l/2),i.push(...u)}if(n!=null)throw new Ve("Support for constants in Bidirectional layers is not implemented yet.");let o=s[0]instanceof ua;for(let l of s)if(l instanceof ua!==o)throw new q("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),u=this.inputSpec.concat(i),d=this.inputSpec;this.inputSpec=u;let h=super.apply(l,t);return this.inputSpec=d,h}else return super.apply(e,t)}call(e,t){return K(()=>{let r=t.initialState,n,a;if(r==null)n=this.forwardLayer.call(e,t),a=this.backwardLayer.call(e,t);else{let o=r.slice(0,r.length/2),l=r.slice(r.length/2);n=this.forwardLayer.call(e,Object.assign(t,{initialState:o})),a=this.backwardLayer.call(e,Object.assign(t,{initialState:l}))}let s;this.returnState&&(Array.isArray(n)&&(s=n.slice(1).concat(a.slice(1))),n=n[0],a=a[0]),this.returnSequences&&(a=$n(a,1));let i;return this.mergeMode==="concat"?i=AA([n,a]):this.mergeMode==="sum"?i=le(n,a):this.mergeMode==="ave"?i=L(.5,le(n,a)):this.mergeMode==="mul"?i=L(n,a):this.mergeMode==null&&(i=[n,a]),this.returnState?this.mergeMode==null?i.concat(s):[i].concat(s):i})}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){To(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),To(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 n=this.forwardLayer.states.map(a=>null);return Array.isArray(r)?r.concat(n).concat(n):[r].concat(n).concat(n)}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=ha(t.layer);if(delete t.layer,t.numConstants!=null)throw new Ve("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");let n=t;return n.layer=r,new e(n)}};Lx.className="Bidirectional";ue.registerClass(Lx);function OU(e){return new gd(e)}function DU(e){return new GA(e)}function LU(e){return new WA(e)}function BU(e){return new VA(e)}function WU(e){return new UA(e)}function VU(e){return new HA(e)}function UU(e){return new jA(e)}function GU(e){return new JA(e)}function jU(e){return new o0(e)}function HU(e){return new XA(e)}function qU(e){return new l0(e)}function KU(e){return new ZA(e)}function XU(e){return new YA(e)}function ZU(e){return new QA(e)}function YU(e){return new ex(e)}function JU(e){return new tx(e)}function QU(e){return new ux(e)}function eG(e){return new ox(e)}function tG(e){return new c0(e)}function rG(e){return new ix(e)}function nG(e){return new lx(e)}function aG(e){return new dx(e)}function sG(e){return new px(e)}function iG(e){return new hx(e)}function oG(e){return new fx(e)}function lG(e){return new mx(e)}function uG(e){return new yx(e)}function dG(e){return new bx(e)}function pG(e){return new Ax(e)}function hG(e){return new xx(e)}function cG(e){return new gx(e)}function fG(e){return new vx(e)}function mG(e){return new Sx(e)}function gG(e){return new Tx(e)}function yG(e){return new Nx(e)}function Bx(e){return new Ex(e)}function AG(e){return Bx(e)}function xG(e){return Bx(e)}function Wx(e){return new Mx(e)}function bG(e){return Wx(e)}function vG(e){return Wx(e)}function Vx(e){return new $x(e)}function wG(e){return Vx(e)}function kG(e){return Vx(e)}function IG(e){return new Px(e)}function SG(e){return new zx(e)}function J4(e){return new _x(e)}function Q4(e){return new Ox(e)}function e6(e){return new Cx(e)}function t6(e){return new Rx(e)}function TG(e){return new Fx(e)}function NG(e){return new nx(e)}function CG(e){return new d0(e)}function EG(e){return new ax(e)}function RG(e){return new Fh(e)}function MG(e){return new rx(e)}function FG(e){return new u0(e)}function $G(e){return new sx(e)}function PG(e){return new h0(e)}function _G(e){return new as(e)}function zG(e){return new p0(e)}function OG(e){return new Lx(e)}function DG(e){return new Dx(e)}var LG=J4,BG=Q4,WG=e6,VG=t6;function UG(e){return new wx(e)}function GG(e){return new kx(e)}function jG(e){return new Ix(e)}function HG(e){return new cx(e)}var r6={};Le(r6,{MAPE:()=>nj,MSE:()=>ij,binaryAccuracy:()=>qG,binaryCrossentropy:()=>KG,categoricalAccuracy:()=>ZG,categoricalCrossentropy:()=>YG,cosineProximity:()=>ej,mape:()=>aj,meanAbsoluteError:()=>tj,meanAbsolutePercentageError:()=>rj,meanSquaredError:()=>sj,mse:()=>oj,precision:()=>JG,recall:()=>QG,sparseCategoricalAccuracy:()=>XG});function qG(e,t){return PA(e,t)}function KG(e,t){return h4(e,t)}function XG(e,t){return c4(e,t)}function ZG(e,t){return _A(e,t)}function YG(e,t){return zA(e,t)}function JG(e,t){return p4(e,t)}function QG(e,t){return WV(e,t)}function ej(e,t){return $A(e,t)}function tj(e,t){return a0(e,t)}function rj(e,t){return yd(e,t)}function nj(e,t){return yd(e,t)}function aj(e,t){return yd(e,t)}function sj(e,t){return $l(e,t)}function ij(e,t){return $l(e,t)}function oj(e,t){return $l(e,t)}var n6={};Le(n6,{modelFromJSON:()=>yU});var a6={};Le(a6,{l1:()=>uj,l1l2:()=>lj,l2:()=>dj});function lj(e){return new Eh(e)}function uj(e){return SU(e)}function dj(e){return TU(e)}var s6=class extends Nu{constructor(){super(...arguments),this.model=null}setModel(e){if(!(e instanceof Xa))throw new Error("model must be a LayersModel, not some other Container");this.model=e}};function Kc(e,t){return e<t}function yv(e,t){return e>t}var i6=class extends s6{constructor(e){if(super(),e==null&&(e={}),e.restoreBestWeights)throw new Ve("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=Kc:this.mode==="max"?this.monitorFunc=yv:this.monitor.indexOf("acc")!==-1?this.monitorFunc=yv:this.monitorFunc=Kc,this.monitorFunc===Kc&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===Kc?1/0:-1/0}async onEpochEnd(e,t){await Is(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 pj(e){return new i6(e)}var hj={earlyStopping:pj},cj=Y();cj.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 o6=(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))(o6||{}),Av;(e=>{let t;(r=>{r[r.LEGACY=0]="LEGACY",r[r.V1=1]="V1",r[r.V2=2]="V2"})(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))})(Av||(Av={}));var Ux={};function fj(e,t){let r={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};Ux[e]=r}function l6(e){return Ux[e]}function mj(e){delete Ux[e]}function k(e,t,r,n,a){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 Dr(t.inputNames[s.inputIndexStart],r,n,a);if(s.type==="tensors")return t.inputNames.slice(o,l).map(h=>Dr(h,r,n,a));let u=Dr(t.inputNames.slice(o)[0],r,n,a),d=u.dataSync();return s.type==="number"?d[0]:w.toNestedArray(u.shape,d)}let i=t.attrParams[e];return i&&i.value}function Dr(e,t,r,n){let[a,s]=dn(e);if(n!=null){let o=n.getHashTableHandleByName(a);if(o!=null)return o}let i=r.currentContextIds.find(o=>!!t[Pf(a,o)]);return i!==void 0?t[Pf(a,i)][s]:void 0}function gj(e,t,r){return t[Pf(e,r.currentContextId)]}function Ca(e,t){let[r,n,a]=dn(e);return[Pf(r,t&&t.currentContextId),n,a]}function Pf(e,t){return t?`${e}-${t}`:e}function dn(e){let t=e.split(":");if(t.length===1)return[e,0,void 0];let r=t[0],n=t.length===3?t[1]:void 0,a=Number(t[t.length-1]);return[r,a,n]}function nf(e,t,r){let n=k("pad",e,t,r);if(n==="explicit"){n=k("explicitPaddings",e,t,r);let a=[[0,0],[0,0],[0,0],[0,0]];for(let s=0;s<4;s++)a[s][0]=n[s*2],a[s][1]=n[s*2+1];return a}return n}function Ha(e){return e.kept?e:Br(e)}var u6={};Le(u6,{json:()=>yj});var yj=[{tfOpName:"Add",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddV2",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"AddN",category:"arithmetic",inputs:[{start:0,end:0,name:"tensors",type:"tensors"}]},{tfOpName:"BiasAdd",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0},{tfName:"data_format",name:"dataFormat",type:"string",notSupported:!0}]},{tfOpName:"Sub",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"RealDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Div",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"DivNoNan",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorDiv",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mul",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Maximum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Minimum",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Pow",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SquaredDifference",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"Mod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"FloorMod",category:"arithmetic",inputs:[{start:0,name:"a",type:"tensor"},{start:1,name:"b",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]}],d6={};Le(d6,{json:()=>Aj});var Aj=[{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}]}],p6={};Le(p6,{json:()=>xj});var xj=[{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"}]},{tfOpName:"TensorListLength",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"}]},{tfOpName:"TensorListResize",category:"control",inputs:[{start:0,name:"tensorListId",type:"tensor"},{start:1,name:"size",type:"number"}]}],h6={};Le(h6,{json:()=>bj});var bj=[{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"}]}],c6={};Le(c6,{json:()=>vj});var vj=[{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"}]}],f6={};Le(f6,{json:()=>wj});var wj=[{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}]}],m6={};Le(m6,{json:()=>kj});var kj=[{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"}]}],g6={};Le(g6,{json:()=>Ij});var Ij=[{tfOpName:"PlaceholderWithDefault",category:"graph",inputs:[{start:0,name:"default",type:"tensor"}],attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Placeholder",category:"graph",attrs:[{tfName:"shape",name:"shape",type:"shape"},{tfName:"dtype",name:"dtype",type:"dtype"}]},{tfOpName:"Const",category:"graph"},{tfOpName:"Identity",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IdentityN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Snapshot",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Rank",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Size",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"Shape",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"ShapeN",category:"graph",inputs:[{start:0,end:0,name:"x",type:"tensors"}]},{tfOpName:"Print",category:"graph",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"data",type:"tensors"}],attrs:[{tfName:"message",name:"message",type:"string"},{tfName:"first_n",name:"firstN",type:"number",notSupported:!0},{tfName:"summarize",name:"summarize",type:"number",defaultValue:3}]},{tfOpName:"NoOp",category:"graph",inputs:[]},{tfOpName:"StopGradient",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"FakeQuantWithMinMaxVars",category:"graph",inputs:[{start:0,name:"x",type:"tensor"}],attrs:[{tfName:"min",name:"min",type:"number"},{tfName:"max",name:"max",type:"number"}]}],y6={};Le(y6,{json:()=>Sj});var Sj=[{tfOpName:"HashTable",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"HashTableV2",category:"hash_table",inputs:[],attrs:[{tfName:"shared_name",name:"sharedName",type:"string"},{tfName:"use_node_name_sharing",name:"useNodeNameSharing",type:"bool"},{tfName:"key_dtype",name:"keyDType",type:"dtype"},{tfName:"value_dtype",name:"valueDType",type:"dtype"}]},{tfOpName:"LookupTableImport",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableImportV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"values",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFind",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableFindV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"},{start:1,name:"keys",type:"tensor"},{start:2,name:"defaultValue",type:"tensor"}],attrs:[{tfName:"Tin",name:"tIn",type:"dtype",notSupported:!0},{tfName:"Tout",name:"tOut",type:"dtype",notSupported:!0}]},{tfOpName:"LookupTableSize",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]},{tfOpName:"LookupTableSizeV2",category:"hash_table",inputs:[{start:0,name:"tableHandle",type:"tensor"}]}],A6={};Le(A6,{json:()=>Tj});var Tj=[{tfOpName:"ResizeBilinear",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"ResizeNearestNeighbor",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"size",type:"number[]"}],attrs:[{tfName:"align_corners",name:"alignCorners",type:"bool"},{tfName:"half_pixel_centers",name:"halfPixelCenters",type:"bool"},{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"CropAndResize",category:"image",inputs:[{start:0,name:"image",type:"tensor"},{start:1,name:"boxes",type:"tensor"},{start:2,name:"boxInd",type:"tensor"},{start:3,name:"cropSize",type:"number[]"}],attrs:[{tfName:"method",name:"method",type:"string"},{tfName:"extrapolation_value",name:"extrapolationValue",type:"number"}]},{tfOpName:"ImageProjectiveTransformV3",category:"image",inputs:[{start:0,name:"images",type:"tensor"},{start:1,name:"transforms",type:"tensor"},{start:2,name:"outputShape",type:"number[]"},{start:3,name:"fillValue",type:"number"}],attrs:[{tfName:"interpolation",name:"interpolation",type:"string"},{tfName:"fill_mode",name:"fillMode",type:"string"}]}],x6={};Le(x6,{json:()=>Nj});var Nj=[{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}]}],b6={};Le(b6,{json:()=>Cj});var Cj=[{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"}]}],v6={};Le(v6,{json:()=>Ej});var Ej=[{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}]}],w6={};Le(w6,{json:()=>Rj});var Rj=[{tfOpName:"Bincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}]},{tfOpName:"DenseBincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}],attrs:[{tfName:"binary_output",name:"binaryOutput",type:"bool"}]},{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Cumprod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]},{tfOpName:"Cumsum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]}],k6={};Le(k6,{json:()=>Mj});var Mj=[{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}]}],I6={};Le(I6,{json:()=>Fj});var Fj=[{tfOpName:"SparseFillEmptyRows",category:"sparse",inputs:[{start:0,name:"indices",type:"tensor"},{start:1,name:"values",type:"tensor"},{start:2,name:"denseShape",type:"tensor"},{start:3,name:"defaultValue",type:"tensor"}]},{tfOpName:"SparseReshape",category:"sparse",inputs:[{start:0,name:"inputIndices",type:"tensor"},{start:1,name:"inputShape",type:"tensor"},{start:2,name:"newShape",type:"tensor"}],attrs:[{tfName:"T",name:"dtype",type:"dtype",notSupported:!0}]},{tfOpName:"SparseSegmentMean",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]},{tfOpName:"SparseSegmentSum",category:"sparse",inputs:[{start:0,name:"data",type:"tensor"},{start:1,name:"indices",type:"tensor"},{start:2,name:"segmentIds",type:"tensor"}]}],S6={};Le(S6,{json:()=>$j});var $j=[{tfOpName:"FFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"IFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"}]},{tfOpName:"RFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]},{tfOpName:"IRFFT",category:"spectral",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"fft_length",type:"number",notSupported:!0}]}],T6={};Le(T6,{json:()=>Pj});var Pj=[{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"}]}],N6={};Le(N6,{json:()=>_j});var _j=[{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:[]}],xv=class{static get Instance(){return this._instance||(this._instance=new this)}constructor(){let e=[u6,d6,p6,h6,c6,f6,m6,g6,y6,A6,x6,b6,v6,w6,k6,I6,S6,T6,N6],t=[].concat(...e.map(r=>r.json));this.opMappers=t.reduce((r,n)=>(r[n.tfOpName]=n,r),{})}transformGraph(e,t={}){let r=e.node,n=[],a=[],s=[],i=r.reduce((f,m)=>(f[m.name]=this.mapNode(m),m.op.startsWith("Placeholder")?n.push(f[m.name]):m.op==="Const"?a.push(f[m.name]):(m.input==null||m.input.length===0)&&s.push(f[m.name]),f),{}),o=[],l=[],u={},d={};t!=null&&(u=this.mapSignatureEntries(t.inputs),d=this.mapSignatureEntries(t.outputs));let h=Object.keys(i);h.forEach(f=>{let m=i[f];m.inputNames.forEach((g,y)=>{let[A,,x]=Ca(g),b=i[A];if(b.outputs!=null){let v=b.outputs.indexOf(x);if(v!==-1){let S=`${A}:${v}`;m.inputNames[y]=S}}m.inputs.push(b),b.children.push(m)})}),Object.keys(d).length===0?h.forEach(f=>{let m=i[f];m.children.length===0&&l.push(m)}):Object.keys(d).forEach(f=>{let[m]=Ca(f),g=i[m];g!=null&&(g.signatureKey=d[f],l.push(g))}),Object.keys(u).length>0?Object.keys(u).forEach(f=>{let[m]=Ca(f),g=i[m];g&&(g.signatureKey=u[f],o.push(g))}):o=n;let p={};e.library!=null&&e.library.function!=null&&(p=e.library.function.reduce((f,m)=>(f[m.signature.name]=this.mapFunction(m),f),{}));let c={nodes:i,inputs:o,outputs:l,weights:a,placeholders:n,signature:t,functions:p};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=l6(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(n=>n.startsWith("^")?n.slice(1):n),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return t.inputs!=null&&(r.inputParams=t.inputs.reduce((n,a)=>(n[a.name]={type:a.type,inputIndexStart:a.start,inputIndexEnd:a.end},n),{})),t.attrs!=null&&(r.attrParams=t.attrs.reduce((n,a)=>{let s=a.type,i;switch(a.type){case"string":i=Py(e.attr,a.tfName,a.defaultValue),i===void 0&&!!a.tfDeprecatedName&&(i=Py(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"string[]":i=Wy(e.attr,a.tfName,a.defaultValue),i===void 0&&!!a.tfDeprecatedName&&(i=Wy(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"number":i=zy(e.attr,a.tfName,a.defaultValue||0),i===void 0&&!!a.tfDeprecatedName&&(i=zy(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"number[]":i=By(e.attr,a.tfName,a.defaultValue),i===void 0&&!!a.tfDeprecatedName&&(i=By(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"bool":i=_y(e.attr,a.tfName,a.defaultValue),i===void 0&&!!a.tfDeprecatedName&&(i=_y(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"bool[]":i=Uy(e.attr,a.tfName,a.defaultValue),i===void 0&&!!a.tfDeprecatedName&&(i=Uy(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"shape":i=Ly(e.attr,a.tfName,a.defaultValue),i===void 0&&!!a.tfDeprecatedName&&(i=Ly(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"shape[]":i=Vy(e.attr,a.tfName,a.defaultValue),i===void 0&&!!a.tfDeprecatedName&&(i=Vy(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"dtype":i=Oy(e.attr,a.tfName,a.defaultValue),i===void 0&&!!a.tfDeprecatedName&&(i=Oy(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"dtype[]":i=Dy(e.attr,a.tfName,a.defaultValue),i===void 0&&!!a.tfDeprecatedName&&(i=Dy(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"func":i=bv(e.attr,a.tfName,a.defaultValue),i===void 0&&!!a.tfDeprecatedName&&(i=bv(e.attr,a.tfDeprecatedName,a.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${a.type} for op: ${e.op}`)}return n[a.name]={value:i,type:s},n},{})),r}mapFunction(e){let t=e.nodeDef,r=[],n=[],a={};t!=null&&(a=t.reduce((u,d)=>(u[d.name]=this.mapNode(d),d.op==="Const"&&n.push(u[d.name]),u),{}));let s=[],i=[];e.signature.inputArg.forEach(u=>{let[d]=Ca(u.name),h={name:d,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:Gx(u.type),type:"dtype"}},children:[]};h.signatureKey=u.name,s.push(h),a[d]=h}),Object.keys(a).forEach(u=>{let d=a[u];d.inputNames.forEach((h,p)=>{let[c,,f]=Ca(h),m=a[c];if(m.outputs!=null){let g=m.outputs.indexOf(f);if(g!==-1){let y=`${c}:${g}`;d.inputNames[p]=y}}d.inputs.push(m),m.children.push(d)})});let o=e.ret;e.signature.outputArg.forEach(u=>{let[d,h]=Ca(o[u.name]),p=a[d];p!=null&&(p.defaultOutput=h,i.push(p))});let l=this.mapArgsToSignature(e);return{nodes:a,inputs:s,outputs:i,weights:n,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 zj(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 C6(e,t){let r=Array.isArray(e)?String.fromCharCode.apply(null,e):zj(e);return t?r:r.toLowerCase()}function Py(e,t,r,n=!1){let a=e[t];return a!=null?C6(a.s,n):r}function _y(e,t,r){let n=e[t];return n?n.b:r}function zy(e,t,r){let n=e[t]||{},a=n.i!=null?n.i:n.f!=null?n.f:r;return typeof a=="number"?a:parseInt(a,10)}function Gx(e){switch(typeof e=="string"&&(e=o6[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 bv(e,t,r){let n=e[t];return n&&n.func?n.func.name:r}function Oy(e,t,r){let n=e[t];return n&&n.type?Gx(n.type):r}function Dy(e,t,r){let n=e[t];return n&&n.list&&n.list.type?n.list.type.map(a=>Gx(a)):r}function E6(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 n=e[t];return n&&n.shape?E6(n.shape):r}function By(e,t,r){let n=e[t];return n?((n.list.f&&n.list.f.length?n.list.f:n.list.i)||[]).map(a=>typeof a=="number"?a:parseInt(a,10)):r}function Wy(e,t,r,n=!1){let a=e[t];return a&&a.list&&a.list.s?a.list.s.map(s=>C6(s,n)):r}function Vy(e,t,r){let n=e[t];return n&&n.list&&n.list.shape?n.list.shape.map(a=>E6(a)):r}function Uy(e,t,r){let n=e[t];return n&&n.list&&n.list.b?n.list.b:r}var Oj=class{constructor(e,t,r){this.node=e,this.tensorMap=t,this.context=r,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(n=>this.getInput(n)),e.rawAttrs!=null&&(this.attrs=Object.keys(e.rawAttrs).reduce((n,a)=>(n[a]=this.getAttr(a),n),{}))}getInput(e){return Dr(e,this.tensorMap,this.context)}getAttr(e,t){let r=this.node.rawAttrs[e];if(r.tensor!=null)return Dr(e,this.tensorMap,this.context);if(r.i!=null||r.f!=null)return zy(this.node.rawAttrs,e,t);if(r.s!=null)return Py(this.node.rawAttrs,e,t);if(r.b!=null)return _y(this.node.rawAttrs,e,t);if(r.shape!=null)return Ly(this.node.rawAttrs,e,t);if(r.type!=null)return Oy(this.node.rawAttrs,e,t);if(r.list!=null){if(r.list.i!=null||r.list.f!=null)return By(this.node.rawAttrs,e,t);if(r.list.s!=null)return Wy(this.node.rawAttrs,e,t);if(r.list.shape!=null)return Vy(this.node.rawAttrs,e,t);if(r.list.b!=null)return Uy(this.node.rawAttrs,e,t);if(r.list.type!=null)return Dy(this.node.rawAttrs,e,t)}return t}},Dj=(e,t,r)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[le(k("a",e,t,r),k("b",e,t,r))];case"AddN":return[bm(k("tensors",e,t,r))];case"FloorMod":case"Mod":return[hd(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[Zk(k("a",e,t,r),k("b",e,t,r))];case"FloorDiv":return[gh(k("a",e,t,r),k("b",e,t,r))];case"Sub":return[ce(k("a",e,t,r),k("b",e,t,r))];case"Minimum":return[vh(k("a",e,t,r),k("b",e,t,r))];case"Maximum":return[ts(k("a",e,t,r),k("b",e,t,r))];case"Pow":return[Ls(k("a",e,t,r),k("b",e,t,r))];case"SquaredDifference":return[oA(k("a",e,t,r),k("b",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Lj=(e,t,r)=>{switch(e.op){case"Abs":case"ComplexAbs":return[rr(k("x",e,t,r))];case"Acos":return[Tk(k("x",e,t,r))];case"Acosh":return[Nk(k("x",e,t,r))];case"Asin":return[Ek(k("x",e,t,r))];case"Asinh":return[Rk(k("x",e,t,r))];case"Atan":return[Mk(k("x",e,t,r))];case"Atan2":return[Fk(k("x",e,t,r),k("y",e,t,r))];case"Atanh":return[$k(k("x",e,t,r))];case"Ceil":return[Wk(k("x",e,t,r))];case"Complex":return[_s(k("real",e,t,r),k("imag",e,t,r))];case"Cos":return[km(k("x",e,t,r))];case"Cosh":return[W2(k("x",e,t,r))];case"Elu":return[xh(k("x",e,t,r))];case"Erf":return[Jk(k("x",e,t,r))];case"Exp":return[Rn(k("x",e,t,r))];case"Expm1":return[Qk(k("x",e,t,r))];case"Floor":return[bh(k("x",e,t,r))];case"Log":return[Mn(k("x",e,t,r))];case"Log1p":return[Tm(k("x",e,t,r))];case"Imag":return[Im(k("x",e,t,r))];case"Neg":return[Ot(k("x",e,t,r))];case"Reciprocal":return[h7(k("x",e,t,r))];case"Real":return[Bp(k("x",e,t,r))];case"Relu":return[_a(k("x",e,t,r))];case"Round":return[eA(k("x",e,t,r))];case"Selu":return[rA(k("x",e,t,r))];case"Sigmoid":return[Nr(k("x",e,t,r))];case"Sin":return[nA(k("x",e,t,r))];case"Sign":return[m7(k("x",e,t,r))];case"Sinh":return[aA(k("x",e,t,r))];case"Softplus":return[pd(k("x",e,t,r))];case"Sqrt":return[Er(k("x",e,t,r))];case"Square":return[At(k("x",e,t,r))];case"Tanh":return[vu(k("x",e,t,r))];case"Tan":return[y7(k("x",e,t,r))];case"ClipByValue":return[cn(k("x",e,t,r),k("clipValueMin",e,t,r),k("clipValueMax",e,t,r))];case"Relu6":return[Q2(k("x",e,t,r))];case"Rsqrt":return[tA(Dr(e.inputNames[0],t,r))];case"Prod":return[Z2(k("x",e,t,r),k("axes",e,t,r))];case"LeakyRelu":return[Sm(k("x",e,t,r),k("alpha",e,t,r))];case"Prelu":return[Fm(k("x",e,t,r),k("alpha",e,t,r))];case"IsNan":return[e7(Dr(e.inputNames[0],t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function Wn(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 n=0;n<e.length;n++){let a=e[n],s=t[n];w.assert(a<0||s<0||a===s,()=>r+` Shapes ${e} and ${t} must match`)}}}function vv(e){return!(typeof e=="number"||e.some(t=>t<0))}function gp(e,t,r){let n=Gy(e,r),a=!vv(n);if(a&&t.length===0)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${n}`);if(a&&t.forEach(s=>{n=Gy(s.shape,n)}),!vv(n))throw new Error(`Non-fully-defined elementShape: ${n}`);return n}function Gy(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 n=0;n<e.length;++n){let a=e[n],s=t[n];if(a>=0&&s>=0&&a!==s)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);r[n]=a>=0?a:s}return r}var Bj=class{constructor(e,t,r,n,a,s,i){this.name=e,this.dtype=t,this.maxSize=r,this.elementShape=n,this.identicalElementShapes=a,this.dynamicSize=s,this.clearAfterRead=i,this.tensors=[],this.closed_=!1,this.idTensor=Se(0),fr(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),Wn(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,fr(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,n)=>this.write(r,t[n]))}gather(e,t){if(!!t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let n=0;n<this.size();n++)e.push(n)}if(e.length===0)return ct([],[0].concat(this.elementShape));let r=this.readMany(e);return Wn(this.elementShape,r[0].shape,"TensorArray shape mismatch: "),lr(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 ct([],[0].concat(this.elementShape));let t=[];for(let n=0;n<this.size();n++)t.push(n);let r=this.readMany(t);return Wn(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,rn(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,n=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 a=r===0?0:t.size/r,s=[];K(()=>{t=G(t,[1,r,a]);for(let o=0;o<e.length;++o){let l=o===0?0:n[o-1],u=[0,l,0],d=[1,e[o],a];s[o]=G(Pe(t,u,d),this.elementShape)}return s});let i=[];for(let o=0;o<e.length;o++)i[o]=o;this.writeMany(i,s)}},Cu=class{constructor(e,t,r,n=-1){this.tensors=e,this.elementShape=t,this.elementDtype=r,e!=null&&e.forEach(a=>{if(r!==a.dtype)throw new Error(`Invalid data types; op elements ${r}, but list elements ${a.dtype}`);Wn(t,a.shape,"TensorList shape mismatch: "),fr(a)}),this.idTensor=Se(0),this.maxNumElements=n,fr(this.idTensor)}get id(){return this.idTensor.id}copy(){return new Cu([...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.`);Wn(e,this.elementShape,"TensorList shape mismatch: ");let n=gp(this.elementShape,this.tensors,e);return K(()=>{let a=this.tensors.map(s=>G(s,n));return lr(a,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=gp(this.elementShape,this.tensors,e),n=this.tensors.pop();return Wn(n.shape,e,"TensorList shape mismatch: "),G(n,r)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(Wn(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");fr(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(this.maxNumElements!==-1&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);let t=new Cu([],this.elementShape,this.elementDtype,this.maxNumElements);t.tensors.length=e;for(let r=0;r<Math.min(this.tensors.length,e);++r)t.tensors[r]=this.tensors[r];return t}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.`);Wn(this.tensors[e].shape,t,"TensorList shape mismatch: ");let n=gp(this.elementShape,this.tensors,t);return G(this.tensors[e],n)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||this.maxNumElements!==-1&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);Wn(this.elementShape,t.shape,"TensorList shape mismatch: "),fr(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}`);Wn(this.elementShape,r,"TensorList shape mismatch: "),e=e.slice(0,this.size());let n=gp(this.elementShape,this.tensors,r);return e.length===0?ct([],[0].concat(n)):K(()=>{let a=e.map(s=>G(this.tensors[s],n));return lr(a,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);Wn(this.elementShape,t,"TensorList shape mismatch: ");let r=gp(this.elementShape,this.tensors,t);return this.size()===0?ct([],[0].concat(r)):K(()=>{let n=this.tensors.map(a=>G(a,r));return kt(n,0)})}};function Wj(e,t,r){let n=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==r)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${r}`);let a=e.shape.slice(1);Wn(a,t,"TensorList shape mismatch: ");let s=rn(e);return new Cu(s,t,n)}function Vj(e,t,r){return new Cu([],e,t,r)}function Uj(e,t,r,n){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);let a=Math.max(...t);if(n!=null&&n!==-1&&a>=n)throw new Error(`Max index must be < array size (${a} vs. ${n})`);let s=new Cu([],r,e.dtype,n),i=rn(e,0);return t.forEach((o,l)=>{s.setItem(o,i[l])}),s}function Gj(e,t,r){let n=0,a=t.map(d=>(n+=d,n));if(n!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to
|
|
tensor.shape[0], but sum of lengths is
|
|
${n}, and tensor's shape is: ${e.shape}`);let s=e.shape.slice(1),i=Gy(s,r),o=n===0?0:e.size/n,l=K(()=>{let d=[];e=G(e,[1,n,o]);for(let h=0;h<t.length;++h){let p=h===0?0:a[h-1],c=[0,p,0],f=[1,t[h],o];d[h]=G(Pe(e,c,f),i)}return e.dispose(),d}),u=new Cu([],r,e.dtype,t.length);for(let d=0;d<l.length;d++)u.setItem(d,l[d]);return u}var jj=async(e,t,r)=>{switch(e.op){case"If":case"StatelessIf":{let n=k("thenBranch",e,t,r),a=k("elseBranch",e,t,r),s=k("cond",e,t,r),i=k("args",e,t,r);return(await s.data())[0]?r.functionMap[n].executeFunctionAsync(i,r.tensorArrayMap,r.tensorListMap):r.functionMap[a].executeFunctionAsync(i,r.tensorArrayMap,r.tensorListMap)}case"While":case"StatelessWhile":{let n=k("body",e,t,r),a=k("cond",e,t,r),s=k("args",e,t,r),i=await r.functionMap[a].executeFunctionAsync(s,r.tensorArrayMap,r.tensorListMap),o=s.map(d=>d.id),l=await i[0].data();i.forEach(d=>{!d.kept&&o.indexOf(d.id)===-1&&d.dispose()});let u=s;for(;l[0];){let d=u;u=await r.functionMap[n].executeFunctionAsync(u,r.tensorArrayMap,r.tensorListMap);let h=u.map(c=>c.id);d.forEach(c=>{!c.kept&&o.indexOf(c.id)===-1&&h.indexOf(c.id)===-1&&c.dispose()});let p=await r.functionMap[a].executeFunctionAsync(u,r.tensorArrayMap,r.tensorListMap);l=await p[0].data(),p.forEach(c=>{!c.kept&&o.indexOf(c.id)===-1&&h.indexOf(c.id)===-1&&c.dispose()})}return u}case"LoopCond":{let n=k("pred",e,t,r);return[Ha(n)]}case"Switch":{let n=k("pred",e,t,r),a=k("data",e,t,r);return a.kept||(a=Ha(a)),(await n.data())[0]?[void 0,a]:[a,void 0]}case"Merge":{let n=e.inputNames.find(a=>Dr(a,t,r)!==void 0);if(n){let a=Dr(n,t,r);return[Ha(a)]}return}case"Enter":{let n=k("frameName",e,t,r),a=k("tensor",e,t,r);return r.enterFrame(n),[Ha(a)]}case"Exit":{let n=k("tensor",e,t,r);return r.exitFrame(),[Ha(n)]}case"NextIteration":{let n=k("tensor",e,t,r);return r.nextIteration(),[Ha(n)]}case"TensorArrayV3":{let n=k("size",e,t,r),a=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),u=k("name",e,t,r),d=new Bj(u,a,n,s,l,i,o);return r.addTensorArray(d),[d.idTensor,Se(1)]}case"TensorArrayWriteV3":{let n=k("tensorArrayId",e,t,r),a=k("index",e,t,r),s=k("tensor",e,t,r),i=r.getTensorArray(n.id);return i.write(a,s),[i.idTensor]}case"TensorArrayReadV3":{let n=k("tensorArrayId",e,t,r),a=k("index",e,t,r);return[r.getTensorArray(n.id).read(a)]}case"TensorArrayGatherV3":{let n=k("tensorArrayId",e,t,r),a=k("indices",e,t,r),s=k("dtype",e,t,r);return[r.getTensorArray(n.id).gather(a,s)]}case"TensorArrayScatterV3":{let n=k("tensorArrayId",e,t,r),a=k("indices",e,t,r),s=k("tensor",e,t,r),i=r.getTensorArray(n.id);return i.scatter(a,s),[i.idTensor]}case"TensorArrayConcatV3":{let n=k("tensorArrayId",e,t,r),a=r.getTensorArray(n.id),s=k("dtype",e,t,r);return[a.concat(s)]}case"TensorArraySplitV3":{let n=k("tensorArrayId",e,t,r),a=k("tensor",e,t,r),s=k("lengths",e,t,r),i=r.getTensorArray(n.id);return i.split(s,a),[i.idTensor]}case"TensorArraySizeV3":{let n=k("tensorArrayId",e,t,r),a=r.getTensorArray(n.id);return[Se(a.size(),"int32")]}case"TensorArrayCloseV3":{let n=k("tensorArrayId",e,t,r),a=r.getTensorArray(n.id);return a.clearAndClose(),[a.idTensor]}case"TensorListSetItem":{let n=k("tensorListId",e,t,r),a=k("index",e,t,r),s=k("tensor",e,t,r),i=r.getTensorList(n.id);return i.setItem(a,s),[i.idTensor]}case"TensorListGetItem":{let n=k("tensorListId",e,t,r),a=k("index",e,t,r),s=k("elementShape",e,t,r),i=k("elementDType",e,t,r);return[r.getTensorList(n.id).getItem(a,s,i)]}case"TensorListScatterV2":case"TensorListScatter":{let n=k("indices",e,t,r),a=k("tensor",e,t,r),s=k("elementShape",e,t,r),i=k("numElements",e,t,r),o=Uj(a,n,s,i);return r.addTensorList(o),[o.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let n=k("elementShape",e,t,r),a=k("elementDType",e,t,r),s;e.op==="TensorListReserve"?s="numElements":s="maxNumElements";let i=k(s,e,t,r),o=Vj(n,a,i);return r.addTensorList(o),[o.idTensor]}case"TensorListGather":{let n=k("tensorListId",e,t,r),a=k("indices",e,t,r),s=k("elementShape",e,t,r),i=k("elementDType",e,t,r);return[r.getTensorList(n.id).gather(a,i,s)]}case"TensorListStack":{let n=k("tensorListId",e,t,r),a=k("elementShape",e,t,r),s=k("elementDType",e,t,r),i=k("numElements",e,t,r);return[r.getTensorList(n.id).stack(a,s,i)]}case"TensorListFromTensor":{let n=k("tensor",e,t,r),a=k("elementShape",e,t,r),s=k("elementDType",e,t,r),i=Wj(n,a,s);return r.addTensorList(i),[i.idTensor]}case"TensorListConcat":{let n=k("tensorListId",e,t,r),a=r.getTensorList(n.id),s=k("dtype",e,t,r),i=k("elementShape",e,t,r);return[a.concat(s,i)]}case"TensorListPushBack":{let n=k("tensorListId",e,t,r),a=k("tensor",e,t,r),s=r.getTensorList(n.id);return s.pushBack(a),[s.idTensor]}case"TensorListPopBack":{let n=k("tensorListId",e,t,r),a=k("elementShape",e,t,r),s=k("elementDType",e,t,r);return[r.getTensorList(n.id).popBack(a,s)]}case"TensorListSplit":{let n=k("tensor",e,t,r),a=k("elementShape",e,t,r),s=k("lengths",e,t,r),i=Gj(n,s,a);return r.addTensorList(i),[i.idTensor]}case"TensorListLength":{let n=k("tensorListId",e,t,r),a=r.getTensorList(n.id);return[Se(a.size(),"int32")]}case"TensorListResize":{let n=k("tensorListId",e,t,r),a=k("size",e,t,r),s=r.getTensorList(n.id).resize(a);return r.addTensorList(s),[s.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};function wv(e,t,r){let[n,a]=k("fusedOps",e,t,r),s=n==="biasadd",i=!s,o=a==="prelu",l=n==="fusedbatchnorm",u=k("numArgs",e,t,r);if(s){if(o&&u!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&s&&u!==1)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(l)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");let d=k("strides",e,t,r),h=nf(e,t,r),p=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:d,pad:h,dataFormat:p,dilations:c,biasArg:f,preluArg:m,activationFunc:a,leakyreluAlpha:g}}var Hj=(e,t,r)=>{switch(e.op){case"Conv1D":{let n=k("stride",e,t,r),a=k("pad",e,t,r),s=k("dataFormat",e,t,r).toUpperCase(),i=k("dilation",e,t,r);return[O2(k("x",e,t,r),k("filter",e,t,r),n,a,s,i)]}case"Conv2D":{let n=k("strides",e,t,r),a=nf(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),[n[1],n[2]],a,s,[i[1],i[2]])]}case"_FusedConv2D":{let{stride:n,pad:a,dataFormat:s,dilations:i,biasArg:o,preluArg:l,activationFunc:u,leakyreluAlpha:d}=wv(e,t,r);return[Bs.conv2d({x:k("x",e,t,r),filter:k("filter",e,t,r),strides:[n[1],n[2]],pad:a,dataFormat:s,dilations:[i[1],i[2]],bias:o,activation:u,preluActivationWeights:l,leakyreluAlpha:d})]}case"FusedDepthwiseConv2dNative":{let{stride:n,pad:a,dataFormat:s,dilations:i,biasArg:o,preluArg:l,activationFunc:u,leakyreluAlpha:d}=wv(e,t,r);return[Bs.depthwiseConv2d({x:k("x",e,t,r),filter:k("filter",e,t,r),strides:[n[1],n[2]],pad:a,dataFormat:s,dilations:[i[1],i[2]],bias:o,activation:u,preluActivationWeights:l,leakyreluAlpha:d})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{let n=k("outputShape",e,t,r),a=k("strides",e,t,r),s=nf(e,t,r);return[L2(k("x",e,t,r),k("filter",e,t,r),n,[a[1],a[2]],s)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{let n=k("strides",e,t,r),a=nf(e,t,r),s=k("dilations",e,t,r),i=k("dataFormat",e,t,r).toUpperCase();return[Ah(k("input",e,t,r),k("filter",e,t,r),[n[1],n[2]],a,i,[s[1],s[2]])]}case"Conv3D":{let n=k("strides",e,t,r),a=k("pad",e,t,r),s=k("dataFormat",e,t,r).toUpperCase(),i=k("dilations",e,t,r);return[B2(k("x",e,t,r),k("filter",e,t,r),[n[1],n[2],n[3]],a,s,[i[1],i[2],i[3]])]}case"AvgPool":{let n=k("strides",e,t,r),a=k("pad",e,t,r),s=k("kernelSize",e,t,r);return[vm(k("x",e,t,r),[s[1],s[2]],[n[1],n[2]],a)]}case"MaxPool":{let n=k("strides",e,t,r),a=k("pad",e,t,r),s=k("kernelSize",e,t,r);return[Em(k("x",e,t,r),[s[1],s[2]],[n[1],n[2]],a)]}case"MaxPoolWithArgmax":{let n=k("strides",e,t,r),a=k("pad",e,t,r),s=k("kernelSize",e,t,r),i=k("includeBatchInIndex",e,t,r),{result:o,indexes:l}=l7(k("x",e,t,r),[s[1],s[2]],[n[1],n[2]],a,i);return[o,l]}case"AvgPool3D":{let n=k("strides",e,t,r),a=k("pad",e,t,r),s=k("kernelSize",e,t,r);return[_2(k("x",e,t,r),[s[1],s[2],s[3]],[n[1],n[2],n[3]],a)]}case"MaxPool3D":{let n=k("strides",e,t,r),a=k("pad",e,t,r),s=k("kernelSize",e,t,r);return[X2(k("x",e,t,r),[s[1],s[2],s[3]],[n[1],n[2],n[3]],a)]}case"Dilation2D":{let n=k("strides",e,t,r),a=k("pad",e,t,r),s=k("dilations",e,t,r),i=n[1],o=n[2],l=s[1],u=s[2];return[Xk(k("x",e,t,r),k("filter",e,t,r),[i,o],a,[l,u],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},qj=(e,t,r)=>{switch(e.op){case"Fill":{let n=k("shape",e,t,r),a=k("dtype",e,t,r),s=k("value",e,t,r);return[dd(n,s,a)]}case"LinSpace":{let n=k("start",e,t,r),a=k("stop",e,t,r),s=k("num",e,t,r);return[t7(n,a,s)]}case"Multinomial":{let n=k("logits",e,t,r),a=k("numSamples",e,t,r),s=k("seed",e,t,r);return[d7(n,a,s)]}case"OneHot":{let n=k("indices",e,t,r),a=k("depth",e,t,r),s=k("onValue",e,t,r),i=k("offValue",e,t,r);return[Lp(n,a,s,i)]}case"Ones":return[hn(k("shape",e,t,r),k("dtype",e,t,r))];case"OnesLike":return[Fn(k("x",e,t,r))];case"RandomUniform":return[cd(k("shape",e,t,r),k("minval",e,t,r),k("maxval",e,t,r),k("dtype",e,t,r))];case"Range":{let n=k("start",e,t,r),a=k("stop",e,t,r),s=k("step",e,t,r);return[Su(n,a,s,k("dtype",e,t,r))]}case"TruncatedNormal":{let n=k("shape",e,t,r),a=k("mean",e,t,r),s=k("stdDev",e,t,r),i=k("seed",e,t,r);return[zm(n,a,s,k("dtype",e,t,r),i)]}case"Zeros":return[Pt(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 ay(e,t,r){let n=k("boxes",e,t,r),a=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:n,scores:a,maxOutputSize:s,iouThreshold:i,scoreThreshold:o,softNmsSigma:l}}var Kj=async(e,t,r)=>{switch(e.op){case"NonMaxSuppressionV5":{let{boxes:n,scores:a,maxOutputSize:s,iouThreshold:i,scoreThreshold:o,softNmsSigma:l}=ay(e,t,r),u=await Ie.nonMaxSuppressionWithScoreAsync(n,a,s,i,o,l);return[u.selectedIndices,u.selectedScores]}case"NonMaxSuppressionV4":{let{boxes:n,scores:a,maxOutputSize:s,iouThreshold:i,scoreThreshold:o}=ay(e,t,r),l=k("padToMaxOutputSize",e,t,r),u=await Ie.nonMaxSuppressionPaddedAsync(n,a,s,i,o,l);return[u.selectedIndices,u.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{let{boxes:n,scores:a,maxOutputSize:s,iouThreshold:i,scoreThreshold:o}=ay(e,t,r);return[await Ie.nonMaxSuppressionAsync(n,a,s,i,o)]}case"Where":{let n=me(k("condition",e,t,r),"bool"),a=[await lA(n)];return n.dispose(),a}case"ListDiff":return f7(k("x",e,t,r),k("y",e,t,r));default:throw TypeError(`Node type ${e.op} is not implemented`)}},Xj=(e,t,r)=>{switch(e.op){case"TopKV2":{let n=k("x",e,t,r),a=k("k",e,t,r),s=k("sorted",e,t,r),i=A7(n,a,s);return[i.values,i.indices]}case"Unique":{let n=k("x",e,t,r),a=wy(n);return[a.values,a.indices]}case"UniqueV2":{let n=k("x",e,t,r),a=k("axis",e,t,r),s=wy(n,a);return[s.values,s.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Zj=(e,t,r)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":let n=k("default",e,t,r);return[Dr(e.name,t,r)||n];case"Placeholder":return[Dr(e.name,t,r)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{let u=k("x",e,t,r);return[Ha(u)]}case"IdentityN":return k("x",e,t,r).map(u=>Ha(u));case"Snapshot":let a=k("x",e,t,r);return[Ha(a)];case"Shape":return[St(k("x",e,t,r).shape,"int32")];case"ShapeN":return k("x",e,t,r).map(u=>St(u.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 u=0;u<i.length;u++)console.log(Array.prototype.slice.call(i[u].dataSync()).slice(0,l));return[s];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Yj=class{constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=Se(0),this.tensorMap=new Map,fr(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(n=>n.dispose()),this.tensorMap.clear(),K(()=>{let n=rn(t),a=r.length,s=n.length;w.assert(a===s,()=>`The number of elements doesn't match, keys has ${a} elements, the values has ${s} elements.`);for(let i=0;i<a;i++){let o=r[i],l=n[i];fr(l),this.tensorMap.set(o,l)}return this.handle})}async find(e,t){this.checkKeyAndValueTensor(e,t);let r=await e.data();return K(()=>{let n=[];for(let a=0;a<r.length;a++){let s=r[a],i=this.findWithDefault(s,t);n.push(i)}return lr(n)})}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}`)}},Jj=async(e,t,r,n)=>{switch(e.op){case"HashTable":case"HashTableV2":{let a=k("keyDType",e,t,r),s=k("valueDType",e,t,r),i=new Yj(a,s);return n.addHashTable(e.name,i),[i.handle]}case"LookupTableImport":case"LookupTableImportV2":{let a=k("tableHandle",e,t,r,n),s=k("keys",e,t,r),i=k("values",e,t,r);return[await n.getHashTableById(a.id).import(s,i)]}case"LookupTableFind":case"LookupTableFindV2":{let a=k("tableHandle",e,t,r,n),s=k("keys",e,t,r),i=k("defaultValue",e,t,r);return[await n.getHashTableById(a.id).find(s,i)]}case"LookupTableSize":case"LookupTableSizeV2":{let a=k("tableHandle",e,t,r,n);return[n.getHashTableById(a.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Qj=(e,t,r)=>{switch(e.op){case"ResizeBilinear":{let n=k("images",e,t,r),a=k("size",e,t,r),s=k("alignCorners",e,t,r),i=k("halfPixelCenters",e,t,r);return[Ie.resizeBilinear(n,[a[0],a[1]],s,i)]}case"ResizeNearestNeighbor":{let n=k("images",e,t,r),a=k("size",e,t,r),s=k("alignCorners",e,t,r),i=k("halfPixelCenters",e,t,r);return[Ie.resizeNearestNeighbor(n,[a[0],a[1]],s,i)]}case"CropAndResize":{let n=k("image",e,t,r),a=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(n,a,s,i,o,l)]}case"ImageProjectiveTransformV3":{let n=k("images",e,t,r),a=k("transforms",e,t,r),s=k("outputShape",e,t,r),i=k("fillValue",e,t,r),o=k("interpolation",e,t,r),l=k("fillMode",e,t,r);return[Ie.transform(n,a,o.toLowerCase(),l.toLowerCase(),i,s)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},eH=(e,t,r)=>{switch(e.op){case"Equal":return[En(k("a",e,t,r),k("b",e,t,r))];case"NotEqual":return[Iu(k("a",e,t,r),k("b",e,t,r))];case"Greater":return[fn(k("a",e,t,r),k("b",e,t,r))];case"GreaterEqual":return[El(k("a",e,t,r),k("b",e,t,r))];case"Less":return[G2(k("a",e,t,r),k("b",e,t,r))];case"LessEqual":return[Rl(k("a",e,t,r),k("b",e,t,r))];case"LogicalAnd":return[fa(k("a",e,t,r),k("b",e,t,r))];case"LogicalNot":return[Cm(k("a",e,t,r))];case"LogicalOr":return[K2(k("a",e,t,r),k("b",e,t,r))];case"Select":case"SelectV2":return[Wr(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`)}},tH=(e,t,r)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[Je(k("a",e,t,r),k("b",e,t,r),k("transposeA",e,t,r),k("transposeB",e,t,r))];case"Einsum":return[Yk(k("equation",e,t,r),...k("tensors",e,t,r))];case"Transpose":return[tt(k("x",e,t,r),k("perm",e,t,r))];case"_FusedMatMul":let[n,a]=k("fusedOps",e,t,r),s=n==="biasadd",i=a==="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[u,d]=k("args",e,t,r);return[Bs.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:u,activation:a,preluActivationWeights:d,leakyreluAlpha:l})];default:throw TypeError(`Node type ${e.op} is not implemented`)}},rH=(e,t,r)=>{switch(e.op){case"FusedBatchNorm":case"FusedBatchNormV2":return[wu(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[wu(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[r7(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[fd(k("x",e,t,r))];case"LogSoftmax":return[j2(k("x",e,t,r))];case"SparseToDense":return[dA(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`)}},nH=(e,t,r)=>{switch(e.op){case"Max":{let i=k("axis",e,t,r),o=k("keepDims",e,t,r);return[gr(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[Ds(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[$2(k("x",e,t,r),i,o)]}case"Any":{let i=k("axis",e,t,r),o=k("keepDims",e,t,r);return[wf(k("x",e,t,r),i,o)]}case"ArgMax":{let i=k("axis",e,t,r);return[Cn(k("x",e,t,r),i)]}case"ArgMin":{let i=k("axis",e,t,r);return[Ck(k("x",e,t,r),i)]}case"Prod":{let i=k("axis",e,t,r),o=k("keepDims",e,t,r);return[Z2(k("x",e,t,r),i,o)]}case"Cumprod":{let i=k("axis",e,t,r),o=k("exclusive",e,t,r),l=k("reverse",e,t,r);return[If(k("x",e,t,r),i,o,l)]}case"Cumsum":{let i=k("axis",e,t,r),o=k("exclusive",e,t,r),l=k("reverse",e,t,r);return[V2(k("x",e,t,r),i,o,l)]}case"Bincount":let n=k("x",e,t,r),a=k("weights",e,t,r),s=k("size",e,t,r);return[z2(n,a,s)];case"DenseBincount":{let i=k("x",e,t,r),o=k("weights",e,t,r),l=k("size",e,t,r),u=k("binaryOutput",e,t,r);return[qk(i,o,l,u)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},aH=(e,t,r)=>{switch(e.op){case"ConcatV2":case"Concat":{let n=k("n",e,t,r),a=k("axis",e,t,r),s=k("tensors",e,t,r);return s=s.slice(0,n),[kt(s,a)]}case"Gather":{let n=k("x",e,t,r),a=k("indices",e,t,r);return[ku(n,me(a,"int32"),0)]}case"GatherV2":{let n=k("axis",e,t,r),a=k("batchDims",e,t,r),s=k("x",e,t,r),i=k("indices",e,t,r);return[ku(s,me(i,"int32"),n,a)]}case"Reverse":{let n=k("dims",e,t,r),a=[];for(let i=0;i<n.length;i++)n[i]&&a.push(i);let s=k("x",e,t,r);return[$n(s,a)]}case"ReverseV2":{let n=k("axis",e,t,r),a=k("x",e,t,r);return[$n(a,n)]}case"Slice":{let n=k("begin",e,t,r),a=k("size",e,t,r);return[Pe(k("x",e,t,r),n,a)]}case"StridedSlice":{let n=k("begin",e,t,r),a=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),u=k("newAxisMask",e,t,r),d=k("shrinkAxisMask",e,t,r),h=k("x",e,t,r);return[g7(h,n,a,s,i,o,l,u,d)]}case"Pack":return K(()=>{let n=k("axis",e,t,r),a=k("tensors",e,t,r),s=a[0].shape,i=rt(a[0]).shape,o=a.map(l=>{let u=w.arraysEqual(l.shape,s);if(!u&&!w.arraysEqual(rt(l).shape,i))throw new Error("the input tensors shape does not match");return u?l:G(l,s)});return[lr(o,n)]});case"Unpack":{let n=k("axis",e,t,r),a=k("tensor",e,t,r);return rn(a,n)}case"Tile":{let n=k("reps",e,t,r);return[Vn(k("x",e,t,r),n)]}case"Split":case"SplitV":{let n=k("axis",e,t,r),a=k("numOrSizeSplits",e,t,r),s=k("x",e,t,r);return Xt(s,a,n)}case"ScatterNd":{let n=k("indices",e,t,r),a=k("values",e,t,r),s=k("shape",e,t,r);return[k7(n,a,s)]}case"GatherNd":{let n=k("x",e,t,r),a=k("indices",e,t,r);return[I7(n,a)]}case"SparseToDense":{let n=k("sparseIndices",e,t,r),a=k("outputShape",e,t,r),s=k("sparseValues",e,t,r),i=k("defaultValue",e,t,r);return[dA(n,s,a,s.dtype===i.dtype?i:me(i,s.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},sH=(e,t,r)=>{switch(e.op){case"SparseFillEmptyRows":{let{outputIndices:n,outputValues:a,emptyRowIndicator:s,reverseIndexMap:i}=bp.sparseFillEmptyRows(k("indices",e,t,r),k("values",e,t,r),k("denseShape",e,t,r),k("defaultValue",e,t,r));return[n,a,s,i]}case"SparseReshape":{let{outputIndices:n,outputShape:a}=bp.sparseReshape(k("inputIndices",e,t,r),k("inputShape",e,t,r),k("newShape",e,t,r));return[n,a]}case"SparseSegmentMean":return[bp.sparseSegmentMean(k("data",e,t,r),k("indices",e,t,r),k("segmentIds",e,t,r))];case"SparseSegmentSum":return[bp.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`)}},iH=(e,t,r)=>{switch(e.op){case"FFT":return[Pm(k("x",e,t,r))];case"IFFT":return[Wp(k("x",e,t,r))];case"RFFT":return[_m(k("x",e,t,r))];case"IRFFT":return[iA(k("x",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},oH=(e,t,r)=>{switch(e.op){case"StringNGrams":{let{nGrams:n,nGramsSplits:a}=rf.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[n,a]}case"StringSplit":{let{indices:n,values:a,shape:s}=rf.stringSplit(k("input",e,t,r),k("delimiter",e,t,r),k("skipEmpty",e,t,r));return[n,a,s]}case"StringToHashBucketFast":return[rf.stringToHashBucketFast(k("input",e,t,r),k("numBuckets",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},lH=(e,t,r)=>{switch(e.op){case"Cast":return[me(k("x",e,t,r),k("dtype",e,t,r))];case"ExpandDims":{let n=k("axis",e,t,r);return[qt(k("x",e,t,r),n)]}case"Squeeze":{let n=k("axis",e,t,r);return[rt(k("x",e,t,r),n)]}case"Reshape":return[G(k("x",e,t,r),k("shape",e,t,r))];case"MirrorPad":return[u7(k("x",e,t,r),k("padding",e,t,r),k("mode",e,t,r))];case"PadV2":case"Pad":return[Hn(k("x",e,t,r),k("padding",e,t,r),k("constantValue",e,t,r))];case"SpaceToBatchND":{let n=k("blockShape",e,t,r),a=k("paddings",e,t,r);return[Mm(k("x",e,t,r),n,a)]}case"BatchToSpaceND":{let n=k("blockShape",e,t,r),a=k("crops",e,t,r);return[wm(k("x",e,t,r),n,a)]}case"DepthToSpace":{let n=k("blockSize",e,t,r),a=k("dataFormat",e,t,r).toUpperCase();return[Kk(k("x",e,t,r),n,a)]}case"BroadcastTo":return[Ep(k("x",e,t,r),k("shape",e,t,r))];case"BroadcastArgs":return[Bk(k("s0",e,t,r),k("s1",e,t,r))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function kv(e,t,r,n){let a=((s,i,o)=>{switch(s.category){case"arithmetic":return K(()=>Dj(s,i,o));case"basic_math":return K(()=>Lj(s,i,o));case"control":return jj(s,i,o);case"convolution":return K(()=>Hj(s,i,o));case"creation":return K(()=>qj(s,i,o));case"dynamic":return Kj(s,i,o);case"evaluation":return K(()=>Xj(s,i,o));case"image":return K(()=>Qj(s,i,o));case"graph":return K(()=>Zj(s,i,o));case"logical":return K(()=>eH(s,i,o));case"matrices":return K(()=>tH(s,i,o));case"normalization":return K(()=>rH(s,i,o));case"reduction":return K(()=>nH(s,i,o));case"slice_join":return K(()=>aH(s,i,o));case"sparse":return K(()=>sH(s,i,o));case"spectral":return K(()=>iH(s,i,o));case"string":return K(()=>oH(s,i,o));case"transformation":return K(()=>lH(s,i,o));case"hash_table":return Jj(s,i,o,n);case"custom":let l=l6(s.op);if(l&&l.customExecutor)return l.customExecutor(new Oj(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(a)?a.then(s=>[].concat(s)):[].concat(a)}var Iv=class{constructor(e={},t={},r={},n={}){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=r,this.functionMap=n,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){let e=[];for(let t=0;t<this.contexts.length-1;t++){let 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 Sv(e,t,r,n){let a=new Set,s=[],i=null,o=null,l=new Set,u=Object.keys(e).map(p=>dn(p)[0]),d=[];n!=null&&(d=n.map(p=>dn(p.name)[0]));let h=[...t];for(;h.length>0;){let p=h.pop();if((R6(p)||cH(p)||fH(p))&&i==null&&(i=p,o=i.children.map(c=>c.name).filter(c=>a.has(c))),a.add(p.name),r[p.name]==null&&u.indexOf(p.name)===-1&&d.indexOf(p.name)===-1){if(p.inputs.length===0){s.push(p.name);continue}p.inputs.forEach(c=>{l.has(c.name)||(l.add(c.name),h.push(c))})}}return{inputs:e,outputs:t,usedNodes:a,missingInputs:s,dynamicNode:i,syncInputs:o}}function uH(e,t,r){let{usedNodes:n,inputs:a}=r,s=[],i=Object.keys(a).map(d=>dn(d)[0]).map(d=>e.nodes[d]),o=e.initNodes;i.forEach(d=>{n.has(d.name)&&s.push(d)}),e.weights.forEach(d=>{n.has(d.name)&&s.push(d)}),o!=null&&o.forEach(d=>{n.has(d.name)&&s.push(d)});let l=new Set,u=[];for(;s.length>0;){let d=s.pop();l.add(d.name),t[d.name]||u.push(d),d.children.forEach(h=>{!l.has(h.name)&&n.has(h.name)&&h.inputs.every(p=>l.has(p.name))&&s.push(h)})}return u}var dH=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],pH=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],hH=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"];function R6(e){return dH.indexOf(e.op)>=0}function cH(e){return pH.indexOf(e.op)>=0}function fH(e){return hH.indexOf(e.op)>=0}var jy=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 jy(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(n=>n.id));this._weightIds=[].concat(...t),this._weightMap=e}set resourceManager(e){this._resourceManager=e}get inputs(){return this._inputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get outputs(){return this._outputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get inputNodes(){return this._inputs.map(e=>e.signatureKey||e.name)}get outputNodes(){return this._outputs.map(e=>{let t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t})}get functions(){return Object.keys(this._functions).reduce((e,t)=>(e[t]=this._functions[t].signature,e),{})}getCompilationKey(e,t){let r=e.map(a=>a.name).sort(),n=t.map(a=>a.name).sort();return r.join(this.SEPERATOR)+"--"+n.join(this.SEPERATOR)}compile(e,t){let r=Sv(e,t,this.weightMap,this._initNodes),{missingInputs:n,dynamicNode:a,syncInputs:s}=r;if(a!=null)throw new Error(`This execution contains the node '${a.name}', which has the dynamic op '${a.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${s}]`);if(n.length>0){let i=t.map(l=>l.name),o=Object.keys(e);throw new Error(`Cannot compute the outputs [${i}] from the provided inputs [${o}]. Missing the following inputs: [${n}]`)}return uH(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 n=r.map(d=>this.graph.nodes[dn(d)[0]]),a=t.map(d=>dn(d)[0]),s=a.map(d=>this.graph.nodes[d]);this.resetIntermediateTensors(),s.length===0&&(s=this._outputs);let i=this.getCompilationKey(n,s),o=this.compiledMap.get(i);o==null&&(o=this.compile(e,s),this.compiledMap.set(i,o));let l={},u={};return K(()=>{let d=new Iv(this.weightMap,l,u,this.functionExecutorMap),h={...this.weightMap};Object.keys(e).forEach(f=>{let[m,g]=dn(f),y=[];y[g]=e[f],h[m]=y});let p=this.getFrozenTensorIds(h),c={};for(let f=0;f<o.length;f++){let m=o[f];if(!h[m.name]){let g=kv(m,h,d,this._resourceManager);if(w.isPromise(g))throw new Error(`The execution of the op '${m.op}' returned a promise. Please use model.executeAsync() instead.`);h[m.name]=g,this.checkTensorForDisposal(m.name,m,h,d,p,a,c)}}return this.parent==null&&d.dispose(p),t.map(f=>Dr(f,h,d))})}getFrozenTensorIds(e){let t=[].concat.apply([],Object.keys(e).map(r=>e[r]).map(r=>r.map(n=>n.id)));return new Set(t)}checkTensorForDisposal(e,t,r,n,a,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=gj(o.name,r,n);l!=null&&l.forEach(u=>{if(u&&!u.kept&&!a.has(u.id)){let d=i[u.id];if(d===1){if(!this.keepTensorForDebug)u.dispose();else{let[h,p]=Ca(t.name,n);this.intermediateTensors[h]?this.intermediateTensors[h][p]=u:(this.intermediateTensors[h]=[],this.intermediateTensors[h][p]=u)}delete i[u.id]}else d!=null&&i[u.id]--}})}}))}async executeAsync(e,t){return this._executeAsync(e,t)}disposeIntermediateTensors(){!this.intermediateTensors||(Object.keys(this.intermediateTensors).forEach(e=>this.intermediateTensors[e].forEach(t=>t.dispose())),this.disposeTensorsMap())}disposeTensorsMap(){!this.tensorsMap||Object.keys(this.tensorsMap).forEach(e=>{this.tensorsMap[e].forEach(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,n={},a={}){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(u){console.warn(u.message)}this.resetIntermediateTensors();let s=new Iv(this.weightMap,n,a,this.functionExecutorMap);this.tensorsMap=await this.executeWithControlFlow(e,s,t,r);let i=t.map(u=>Dr(u,this.tensorsMap,s)),o=i.map(u=>u.id),l=Object.keys(e).map(u=>e[u].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 n=e.reduce((a,s,i)=>(a[this.inputs[i].name]=s,a),{});return this._executeAsync(n,this.outputNodes,!0,t,r)}async executeWithControlFlow(e,t,r,n){let a=Object.keys(e),s=a.map(A=>this.graph.nodes[dn(A)[0]]),i=r.map(A=>dn(A)[0]),o=i.map(A=>this.graph.nodes[A]);o.length===0&&(o=this._outputs);let{usedNodes:l,missingInputs:u,dynamicNode:d,syncInputs:h}=Sv(e,o,this.weightMap,this._initNodes),p=[...s,...this.graph.weights,...this._initNodes||[]].map(A=>({node:A,contexts:t.currentContext})),c={...this.weightMap};Object.keys(e).forEach(A=>{let[x,b]=dn(A),v=[];v[b]=e[A],c[x]=v});let f={},m=this.getFrozenTensorIds(c),g={};for(;p.length>0;){let A=this.processStack(s,p,t,c,g,m,i,f,l);await Promise.all(A)}d==null&&!n&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");let y=o.filter(A=>!R6(A)&&!Dr(A.name,c,t)).map(A=>A.name);if(y.length>0){let A="";throw d!=null&&(A=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${h}]`),new Error(`Cannot compute the outputs [${y}] from the provided inputs [${a}]. Consider providing the following inputs: [${u}]. ${A}`)}return c}processStack(e,t,r,n,a,s,i,o,l){let u=[];for(;t.length>0;){let d=t.pop();r.currentContext=d.contexts;let h="";if(d.node.op==="Enter"&&k("isConstant",d.node,n,r)&&([h]=Ca(d.node.name,r)),n[d.node.name]==null){let p=kv(d.node,n,r,this._resourceManager);h||([h]=Ca(d.node.name,r));let c=r.currentContext;w.isPromise(p)?u.push(p.then(f=>(n[h]=f,r.currentContext=c,this.checkTensorForDisposal(h,d.node,n,r,s,i,o),this.processChildNodes(d.node,t,r,n,a,l),f))):(n[h]=p,this.checkTensorForDisposal(h,d.node,n,r,s,i,o),this.processChildNodes(d.node,t,r,n,a,l))}else this.processChildNodes(d.node,t,r,n,a,l)}return u}processChildNodes(e,t,r,n,a,s){e.children.forEach(i=>{let[o]=Ca(i.name,r);a[o]||!s.has(i.name)||(i.op==="Merge"?i.inputNames.some(l=>!!Dr(l,n,r))&&(a[o]=!0,t.push({contexts:r.currentContext,node:i})):i.inputNames.every(l=>!!Dr(l,n,r))&&(a[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],[n]=dn(t),a=this.graph.nodes[n];if(a.attrParams.shape&&a.attrParams.shape.value){let s=a.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['${a.name}'] provided in model.execute(dict) must be [${s}], but was [${r.shape}]`)}a.attrParams.dtype&&a.attrParams.dtype.value&&w.assert(r.dtype===a.attrParams.dtype.value,()=>`The dtype of dict['${a.name}'] provided in model.execute(dict) must be ${a.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 n=this._signature.inputs[r];t[n.name]=e[r]}else t[r]=e[r];return t}checkInputs(e){let t=Object.keys(e).filter(r=>{let[n]=dn(r);return this.graph.nodes[n]==null});if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map(t=>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]=dn(t);if(!this.graph.nodes[r])throw new Error(`The output '${t}' is not found in the graph`)})}},mH=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]}},gH="?tfjs-format=file",yH="model.json",m0=class{constructor(e,t={}){this.modelUrl=e,this.loadOptions=t,this.version="n/a",t==null&&(this.loadOptions={}),this.resourceManager=new mH}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=Tr.browserHTTPRequest(e,this.loadOptions);else{let t=Tr.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(Tr.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 n=Tr.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new jy(xv.Instance.transformGraph(t,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(n),this.executor.resourceManager=this.resourceManager,e.modelInitializer!=null&&e.modelInitializer.node!=null){let a=xv.Instance.transformGraph(e.modelInitializer);this.initializer=new jy(a),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=Tr.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 nt)&&!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,n)=>(t[r]=e[n],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 AH(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}${yH}${gH}`);let r=new m0(e,t);return await r.load(),r}var xH="0.0.0",M6={};Le(M6,{CSVDataset:()=>U6,Dataset:()=>Ad,FileDataSource:()=>Z6,TextLineDataset:()=>V6,URLDataSource:()=>Y6,array:()=>VH,csv:()=>QH,func:()=>eq,generator:()=>tq,microphone:()=>nq,version_data:()=>aq,webcam:()=>rq,zip:()=>UH});var bH=Bo(jf()),vH=Bo(jf());function wH(e,t){return _f(e,t)}function _f(e,t,r=new Map,n=new Set){if(e==null)return null;if(typeof Blob=="function"&&e instanceof Blob)return e.slice();if(n.has(e))throw new Error("Circular references are not supported.");if(r.has(e))return r.get(e);let a=t(e);if(a.recurse&&a.value!==null)throw new Error("A deep map function may not return both a value and recurse=true.");if(a.recurse)if(Eu(e)){let s=Array.isArray(e)?[]:{};n.add(e);for(let i in e){let o=e[i],l=_f(o,t,r,n);s[i]=l}return n.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,a.value),a.value}function kH(e,t=$6){return F6(e,t)}function F6(e,t,r=new Set){let n=e[0];if(r.has(n))throw new Error("Circular references are not supported.");let a=t(e);if(a.recurse&&a.value!==null)throw new Error("A deep zip function may not return both a value and recurse=true.");if(a.recurse)if(Eu(n)){let s=Array.isArray(n)?[]:{};r.add(n);for(let i in n){let o=e.map(u=>u[i]),l=F6(o,t,r);s[i]=l}return r.delete(n),s}else throw new Error(`Can't recurse into non-iterable type: ${n}`);else return a.value}function $6(e){return e===null?null:Eu(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function P6(e,t){let r=new Map;_f(e,t,r);for(let n of Array.from(r.keys())){let a=r.get(n);if(w.isPromise(a)){let s=await a;r.set(n,s)}}return _f(e,t,r)}function Eu(e){let t=!1;if(Y().get("IS_BROWSER"))t=e instanceof TextDecoder;else{let{StringDecoder:r}=Aw();t=e instanceof r}return e!=null&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||typeof e=="object"&&!(e instanceof nt)&&!(e instanceof Promise)&&!t)}function IH(e){return e==null||SH(e)||Array.isArray(e)||typeof e=="object"&&e instanceof nt||w.isTypedArray(e)}function SH(e){return e===null||typeof e!="object"&&typeof e!="function"}function TH(e){return wH(e,NH)}function NH(e){return e instanceof nt?{value:e.clone(),recurse:!1}:Eu(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}var _6=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}},z6=class extends _6{constructor(){super(z6.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 n=0;n<r;n++)t[n]=this.get(this.wrap(this.begin+n));this.data=t,this.capacity=e,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=r}},O6=z6;O6.INITIAL_CAPACITY=32;function D6(e){return new RH(e)}function jx(e){return new MH(e)}function CH(e,t){return new L6(e,t)}function EH(e,t=B6.FAIL){return new BH(e,t)}var Ar=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 DH(this,e)}filter(e){return new zH(this,e)}map(e){return new OH(this,e)}mapAsync(e){return new Tv(this,e)}serialMapAsync(e){return new Tv(this,e).serial()}flatmap(e){return new LH(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 _H(this,e,t)}columnMajorBatch(e,t=!0,r=$6){return this.rowMajorBatch(e,t).map(n=>kH(n,r))}concatenate(e,t){return new L6(D6([this,e]),t)}take(e){return e<0||e==null?this:new PH(this,e)}skip(e){return e<0||e==null?this:new $H(this,e)}prefetch(e){return new W6(this,e)}shuffle(e,t){return new WH(this,e,t)}serial(){return new FH(this)}},RH=class extends Ar{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:TH(e),done:!1}}},MH=class extends Ar{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}}},FH=class extends Ar{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()}},$H=class extends Ar{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()}},PH=class extends Ar{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()}},_H=class extends Ar{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}}},zH=class extends Ar{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)}}},OH=class extends Ar{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=da.getTensorsInContainer(e.value),r=this.transform(e.value),n=da.getTensorsInContainer(r);for(let a of t)da.isTensorInList(a,n)||a.dispose();return{value:r,done:!1}}},DH=class extends Ar{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}}}},Tv=class extends Ar{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=da.getTensorsInContainer(e.value),r=await this.transform(e.value),n=da.getTensorsInContainer(r);for(let a of t)da.isTensorInList(a,n)||a.dispose();return{value:r,done:!1}}},Hx=class extends Ar{constructor(){super(),this.outputQueue=new O6,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}}},LH=class extends Hx{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=da.getTensorsInContainer(e.value),r=this.transform(e.value),n=da.getTensorsInContainer(r);this.outputQueue.pushAll(r);for(let a of t)da.isTensorInList(a,n)||a.dispose();return!0}},L6=class extends Ar{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}},B6=(e=>(e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST",e))(B6||{}),BH=class extends Ar{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 n(s){return s instanceof Ar?{value:s.next().then(i=>(t++,i.done&&r++,i.value)),recurse:!1}:{value:null,recurse:!0}}let a=await P6(this.iterators,n);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:a,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}},W6=class extends Ar{constructor(e,t){super(),this.upstream=e,this.bufferSize=t,this.buffer=new _6(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()}},WH=class extends W6{constructor(e,t,r){super(e,t),this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=vH.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}}},Ad=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 n;return this.size===1/0||this.size==null?n=this.size:t?n=Math.ceil(this.size/e):n=Math.floor(this.size/e),un(async()=>(await r.iterator()).columnMajorBatch(e,t,GH),n)}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,un(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,un(async()=>(await t.iterator()).filter(n=>K(()=>e(n))),r)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){let t=this;return un(async()=>(await t.iterator()).map(r=>K(()=>e(r))),this.size)}mapAsync(e){let t=this;return un(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 un(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,un(async()=>{let n=jx(async()=>({value:await t.iterator(),done:!1}));return CH(n.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,un(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 n=this,a=bH.alea(t||w.now().toString());return un(async()=>{let s=a.int32();return r&&(s+=a.int32()),(await n.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,un(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()}};Ad.MAX_BUFFER_SIZE=1e4;function un(e,t=null){return new class extends Ad{constructor(){super(...arguments),this.size=t}async iterator(){return e()}}}function VH(e){return un(async()=>D6(e),e.length)}function UH(e){if(!Eu(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 un(async()=>{let r=await P6(e,n=>{if(n instanceof Ad)return{value:n.iterator(),recurse:!1};if(Eu(n))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return EH(r,1)},t)}function GH(e){if(e===null)return null;let t=e[0];return IH(t)?{value:jH(e),recurse:!1}:{value:null,recurse:!0}}function jH(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof nt?lr(e):ct(e)}var V6=class extends Ad{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))}},Xc='"',yp=Symbol("out"),Nv=Symbol("field"),Zc=Symbol("quote"),sy=Symbol("quoteafterquote"),Cv=Symbol("quoteinquote"),U6=class extends Ad{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 V6(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((n,a)=>(n[a]=n[a]+1||1,n),{}),r=Object.keys(t).filter(n=>t[n]>1);if(w.assert(r.length===0,()=>"Duplicate column names found: "+r.toString()),this.columnConfigs){for(let n of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(n)===-1)throw new Error('The key "'+n+'" 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={},n={};for(let a=0;a<this.fullColumnNames.length;a++){let s=this.fullColumnNames[a],i=this.columnConfigs?this.columnConfigs[s]:null;if(!(this.configuredColumnsOnly&&!i)){let o=t[a],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 u=Number(o);if(isNaN(u))i&&i.dtype==="bool"?l=this.getBoolean(o):l=o;else if(!i||!i.dtype)l=u;else switch(i.dtype){case"float32":l=u;break;case"int32":l=Math.floor(u);break;case"bool":l=this.getBoolean(o);break;default:l=u}}i&&i.isLabel?n[s]=l:r[s]=l}}return Object.keys(n).length===0?r:{xs:r,ys:n}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){let r=[],n=0,a=e.length,s=yp;for(let i=0;i<a;i++)switch(s){case yp:switch(e.charAt(i)){case Xc:n=i+1,s=Zc;break;case this.delimiter:if(n=i+1,this.delimiter===" "&&this.delimWhitespace)break;r.push(""),s=yp;break;default:s=Nv,n=i;break}break;case Nv:switch(e.charAt(i)){case this.delimiter:r.push(e.substring(n,i)),s=yp,n=i+1;break;default:}break;case Zc:switch(e.charAt(i)){case Xc:s=sy;break;default:}break;case sy:switch(e.charAt(i)){case this.delimiter:r.push(e.substring(n,i-1)),s=yp,n=i+1;break;case Xc:s=Zc;break;default:s=Cv;break}break;case Cv:switch(e.charAt(i)){case Xc:s=Zc;break;default:}break;default:}if(s===sy?r.push(e.substring(n,a-1)):r.push(e.substring(n)),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}},G6=class extends Ar{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_BROWSER"))throw new Error("microphone API is only supported in browser environment.");let t=new G6(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 n=this.flattenQueue(r.freqDataQueue);e=this.getTensorFromAudioDataArray(n,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){let n=this.flattenQueue(r.timeDataQueue);t=this.getTensorFromAudioDataArray(n,[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(n=>{let a=setInterval(()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-1/0&&n({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(a),n({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((n,a)=>r.set(n,a*t)),r}getTensorFromAudioDataArray(e,t){let r=new Float32Array(w.sizeFromShape(t));return r.set(e,r.length-e.length),ct(r,t)}},j6=class extends Ar{constructor(e,t){if(super(),this.webcamVideoElement=e,this.webcamConfig=t,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=St([0],"int32"),this.webcamConfig.centerCrop){let r=this.webcamConfig.resizeWidth*1/this.webcamVideoElement.width,n=this.webcamConfig.resizeHeight*1/this.webcamVideoElement.height,a=(1-r)/2,s=(1-n)/2,i=a+r,o=n+s;this.cropBox=pa([s,a,o,i],[1,4])}else this.cropBox=pa([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(!Y().get("IS_BROWSER"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=document.createElement("video"),!t.resizeWidth||!t.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");e.width=t.resizeWidth,e.height=t.resizeHeight}let r=new j6(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=_n.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 K(()=>{let t=qt(me(e,"float32"),0),r;r=Ie.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");let n=r.shape;return G(r,n.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.")}},H6=class{},q6=class extends Ar{split(e){return new HH(this,e)}},HH=class extends q6{constructor(e,t){super(),this.upstream=e,this.impl=new qH(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},qH=class extends Hx{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}},KH=class extends Ar{decodeUTF8(){return new XH(this)}},XH=class extends q6{constructor(e){super(),this.upstream=e,this.impl=new ZH(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},ZH=class extends Hx{constructor(e){if(super(),this.upstream=e,Y().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{let{StringDecoder:t}=Aw();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}},K6=class extends KH{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 n=new FileReader;n.onload=s=>{let i=n.result;if(i instanceof ArrayBuffer&&(i=new Uint8Array(i)),!(i instanceof Uint8Array))return t(new TypeError("FileReader returned unknown type."));e(i)},n.onabort=s=>t(new Error("Aborted")),n.onerror=s=>t(new Error(s.type));let a=this.file.slice(this.offset,r);n.readAsArrayBuffer(a)}this.offset=r}),done:!1}}};async function YH(e,t={},r){let n,a;typeof e=="string"?n=e:(n=e.url,a=JH(e));let s=await(r||w.fetch)(n,a);if(s.ok){let i=new Uint8Array(await s.arrayBuffer());return new K6(i,t)}else throw new Error(s.statusText)}var JH=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 X6(e){return typeof e=="string"&&e.slice(0,7)==="file://"}var Z6=class extends H6{constructor(e,t={}){super(),this.input=e,this.options=t}async iterator(){if(X6(this.input)&&Y().get("IS_NODE")){let e=u2();this.input=e.readFileSync(this.input.slice(7))}return new K6(this.input,this.options)}},Y6=class extends H6{constructor(e,t={}){super(),this.url=e,this.fileOptions=t}async iterator(){return X6(this.url)?new Z6(this.url,this.fileOptions).iterator():YH(this.url,this.fileOptions)}};function QH(e,t={}){return new U6(new Y6(e),t)}function eq(e){let t=jx(e);return un(async()=>t)}function tq(e){return un(async()=>{let t=await e();return jx(()=>t.next())})}async function rq(e,t){return j6.create(e,t)}async function nq(e){return G6.create(e)}var aq="0.0.0";function Te(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 sq=qn.whereImpl,J6=class extends $u{constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new qp(this,nr())}nextDataId(){return J6.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 n={id:this.nextDataId()};return this.data.set(n,{values:e,dtype:r,refCount:1}),n}makeTensorInfo(e,t,r){let n;if(t==="string"&&r!=null&&r.length>0&&w.isString(r[0])){let a=r.map(s=>w.encodeString(s));n=this.write(a,e,t)}else n=this.write(r,e,t);return{dataId:n,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){let t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){let t=this.data.get(e);t.refCount--}}move(e,t,r,n,a){this.data.set(e,{values:t,dtype:n,refCount:a})}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 n=this.readSync(r.real.dataId),a=this.readSync(r.imag.dataId);return N.mergeRealAndImagArrays(n,a)}return this.data.get(e).values}bufferSync(e){let t=this.readSync(e.dataId),r=t;if(e.dtype==="string")try{r=t.map(n=>w.decodeString(n))}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return We(e.shape,e.dtype,r)}makeOutput(e,t,r){let n=this.write(e,t,r);return nr().makeTensorFromDataId(n,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){Te([e],"where");let t=this.readSync(e.dataId);return sq(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}},qx=J6;qx.nextDataId=0;var g0={};Le(g0,{addImpl:()=>eI,bincountImpl:()=>Xx,bincountReduceImpl:()=>tI,ceilImpl:()=>rI,concatImpl:()=>Zx,equalImpl:()=>nI,expImpl:()=>sI,expm1Impl:()=>oI,floorImpl:()=>lI,gatherNdImpl:()=>uI,gatherV2Impl:()=>dI,greaterEqualImpl:()=>hI,greaterImpl:()=>pI,lessEqualImpl:()=>fI,lessImpl:()=>cI,linSpaceImpl:()=>mI,logImpl:()=>gI,maxImpl:()=>yI,maximumImpl:()=>AI,minimumImpl:()=>xI,multiplyImpl:()=>Yx,negImpl:()=>bI,notEqualImpl:()=>vI,prodImpl:()=>wI,rangeImpl:()=>Qx,rsqrtImpl:()=>kI,sigmoidImpl:()=>qq,simpleAbsImpl:()=>Q6,sliceImpl:()=>Of,sparseFillEmptyRowsImpl:()=>SI,sparseReshapeImpl:()=>TI,sparseSegmentReductionImpl:()=>eb,sqrtImpl:()=>Zq,squaredDifferenceImpl:()=>NI,stridedSliceImpl:()=>CI,stringNGramsImpl:()=>EI,stringSplitImpl:()=>RI,stringToHashBucketFastImpl:()=>MI,subImpl:()=>FI,tileImpl:()=>$I,topKImpl:()=>_I,transposeImpl:()=>Jx,uniqueImpl:()=>zI});function Q6(e){let t=new Float32Array(e.length);for(let r=0;r<e.length;++r)t[r]=Math.abs(e[r]);return t}var iq=e=>{let{x:t}=e.inputs,r=e.backend;Te(t,"abs");let n=new Float32Array(w.sizeFromShape(t.shape)),a=r.data.get(t.dataId).values;return n=Q6(a),r.makeOutput(n,t.shape,t.dtype)},oq={kernelName:Vo,backendName:"cpu",kernelFunc:iq};function Yt(e){return(t,r,n,a,s)=>{let i=N.assertAndGetBroadcastShape(t,r),o=i.length,l=w.computeStrides(i),u=w.sizeFromShape(i),d=w.getTypedArrayFromDType(s,u),h=t.length,p=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<d.length;++y)d[y]=e(n[y%n.length],a[y%a.length]);else for(let y=0;y<d.length;++y){let A=w.indexToLoc(y,o,l),x=A.slice(-h);m.forEach(T=>x[T]=0);let b=w.locToIndex(x,h,c),v=A.slice(-p);g.forEach(T=>v[T]=0);let S=w.locToIndex(v,p,f);d[y]=e(n[b],a[S])}return[d,i]}}function pn(e){let{inputs:t,backend:r}=e,{real:n,imag:a}=t,s=r.data.get(n.dataId).values,i=r.data.get(a.dataId).values,o=r.makeTensorInfo(n.shape,"complex64"),l=r.data.get(o.dataId);return l.complexTensorInfos={real:r.makeTensorInfo(n.shape,"float32",s),imag:r.makeTensorInfo(a.shape,"float32",i)},o}var lq={kernelName:Xp,backendName:"cpu",kernelFunc:pn};function zf(e,t,r="float32"){if(r==="complex64"){let a=zf(e,t,"float32"),s=zf(e,t,"float32");return pn({inputs:{real:a,imag:s},backend:e})}let n=w.makeZerosTypedArray(w.sizeFromShape(t),r);return e.makeTensorInfo(t,r,n)}function $a(e){let{inputs:t,backend:r}=e,{x:n}=t;return r.incRef(n.dataId),{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}var uq={kernelName:ci,backendName:"cpu",kernelFunc:$a};function _o(e){let{inputs:t,backend:r}=e,{input:n}=t,a=r.data.get(n.dataId).complexTensorInfos.real,s=r.data.get(a.dataId).values;return r.makeTensorInfo(a.shape,a.dtype,s)}var dq={kernelName:ah,backendName:"cpu",kernelFunc:_o};function js(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{dtype:s}=n;if(s==="complex64"){if(a.dtype==="complex64")return $a({inputs:{x:a},backend:r});let i=zf(r,a.shape,a.dtype),o=js({inputs:{x:a},backend:r,attrs:{dtype:"float32"}}),l=pn({inputs:{real:o,imag:i},backend:r});return r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(o),l}if(a.dtype==="complex64"){let i=_o({inputs:{input:a},backend:r}),o=js({inputs:{x:i},backend:r,attrs:{dtype:s}});return r.disposeIntermediateTensorInfo(i),o}if(!w.hasEncodingLoss(a.dtype,s)){let i=$a({inputs:{x:a},backend:r});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(s==="int32"){let i=r.data.get(a.dataId).values,o=Int32Array.from(i);return r.makeTensorInfo(a.shape,"int32",o)}if(s==="bool"){let i=r.data.get(a.dataId).values,o=w.toTypedArray([0],a.dtype),[l,u]=Yt((d,h)=>d!==h?1:0)(a.shape,[],i,o,"bool");return r.makeTensorInfo(u,"bool",l)}throw new Error(`Error in Cast: failed to cast ${a.dtype} to ${s}`)}var pq={kernelName:Js,backendName:"cpu",kernelFunc:js};function xr(e,t,r,n){return r==null?({inputs:a,backend:s})=>{let{a:i,b:o}=a,l=s;Te([i,o],e);let u=l.data.get(i.dataId).values,d=l.data.get(o.dataId).values,h=i.dtype==="string"?N.fromUint8ToStringArray(u):u,p=i.dtype==="string"?N.fromUint8ToStringArray(d):d,c=n||i.dtype,[f,m]=t(i.shape,o.shape,h,p,c);return l.makeTensorInfo(m,c,f)}:({inputs:a,backend:s})=>{let{a:i,b:o}=a,l=s;if(i.dtype==="complex64"||o.dtype==="complex64"){let u=js({inputs:{x:i},backend:l,attrs:{dtype:"complex64"}}),d=l.data.get(u.dataId),h=d.complexTensorInfos.real,p=d.complexTensorInfos.imag,c=l.data.get(h.dataId).values,f=l.data.get(p.dataId).values,m=js({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,S,T]=r(i.shape,o.shape,c,f,x,b),E=l.makeTensorInfo(T,"float32",v),R=l.makeTensorInfo(T,"float32",S),_=pn({inputs:{real:E,imag:R},backend:l});return l.disposeIntermediateTensorInfo(u),l.disposeIntermediateTensorInfo(m),l.disposeIntermediateTensorInfo(E),l.disposeIntermediateTensorInfo(R),_}else{let u=l.data.get(i.dataId).values,d=l.data.get(o.dataId).values,h=n||i.dtype,[p,c]=t(i.shape,o.shape,u,d,h);return l.makeTensorInfo(c,h,p)}}}function Kx(e){return(t,r,n,a,s,i)=>{let o=N.assertAndGetBroadcastShape(t,r),l=w.sizeFromShape(o),u=o.length,d=w.computeStrides(o),h=w.getTypedArrayFromDType("float32",l),p=w.getTypedArrayFromDType("float32",l),c=N.getBroadcastDims(t,o),f=N.getBroadcastDims(r,o),m=N.mergeRealAndImagArrays(n,a),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<h.length;v++){let S=v%m.length,T=v%g.length,E=e(m[S*2],m[S*2+1],g[T*2],g[T*2+1]);h[v]=E.real,p[v]=E.imag}else for(let v=0;v<h.length;v++){let S=w.indexToLoc(v,u,d),T=S.slice(-y);c.forEach(I=>T[I]=0);let E=w.locToIndex(T,y,A),R=S.slice(-x);f.forEach(I=>R[I]=0);let _=w.locToIndex(R,x,b),M=e(m[E*2],m[E*2+1],g[_*2],g[_*2+1]);h[v]=M.real,p[v]=M.imag}return[h,p,o]}}var eI=Yt((e,t)=>e+t),hq=Kx((e,t,r,n)=>({real:e+r,imag:t+n})),$h=xr(Ja,eI,hq),cq={kernelName:Ja,backendName:"cpu",kernelFunc:$h};function Xx(e,t,r,n,a){let s=w.sizeFromShape(n),i=w.makeZerosTypedArray(a,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>=a||(s>0?i[l]+=t[o]:i[l]+=1)}return i}function tI(e,t,r,n=!1){let a=e.shape[0],s=e.shape[1],i=We([a,r],t.dtype);for(let o=0;o<a;o++)for(let l=0;l<s;l++){let u=e.get(o,l);if(u<0)throw new Error("Input x must be non-negative!");u>=r||(n?i.set(1,o,u):t.size>0?i.set(i.get(o,u)+t.get(o,l),o,u):i.set(i.get(o,u)+1,o,u))}return i}function Gi(e){return(t,r,n)=>{let a=w.getTypedArrayFromDType(r,t.length);for(let s=0;s<t.length;++s)a[s]=e(t[s],n);return a}}function mt(e,t,r){return({inputs:n,attrs:a,backend:s})=>{let{x:i}=n;if(Te(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,u=w.sizeFromShape(i.shape),d=r||i.dtype,h=w.getArrayFromDType(d,u);for(let p=0;p<u;++p)h[p]=t(l[p],a);return o.makeTensorInfo(i.shape,d,h)}}function xd(e,t,r){return({inputs:n,attrs:a,backend:s})=>{let{x:i}=n;if(Te(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,u=r||i.dtype,d=t(l,u,a);return o.makeTensorInfo(i.shape,u,d)}}var rI=Gi(e=>Math.ceil(e)),fq=xd(Qs,rI),mq={kernelName:Qs,backendName:"cpu",kernelFunc:fq};function Zx(e,t,r,n){let a=w.getArrayFromDType(r,w.sizeFromShape(t));if(n&&r!=="string"){let s=0;e.forEach(i=>{let o=w.sizeFromShape(i.shape);a.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 u=0;u<i.shape[0];++u){let d=u*t[1]+s;for(let h=0;h<i.shape[1];++h)a[d+h]=o[l++]}s+=i.shape[1]})}return a}var nI=Yt((e,t)=>e===t?1:0),aI=xr(Ko,nI,null,"bool"),gq={kernelName:Ko,backendName:"cpu",kernelFunc:aI},sI=Gi(e=>Math.exp(e)),iI=xd(li,sI,"float32"),yq={kernelName:li,backendName:"cpu",kernelFunc:iI},oI=Gi(e=>Math.expm1(e)),Aq=xd(Zo,oI),xq={kernelName:Zo,backendName:"cpu",kernelFunc:Aq},lI=Gi(e=>Math.floor(e)),bq=xd(ui,lI),vq={kernelName:ui,backendName:"cpu",kernelFunc:bq};function uI(e,t,r,n,a,s,i,o,l){let u=We([n,s],r);for(let d=0;d<n;d++){let h=[],p=0;for(let c=0;c<a;c++){let f=e[d*a+c];p+=f*i[c],h.push(f)}if(p<0||p>=l/s)throw new Error(`Invalid indices: ${h} does not index into ${o}`);for(let c=0;c<s;c++)u.values[d*s+c]=t.get(...t.indexToLoc(p*s+c))}return u}function dI(e,t,r){let n=We(r,e.dtype);for(let a=0;a<n.size;++a){let s=n.indexToLoc(a).slice(),i=s[0],o=s[2],l=t.locToIndex([i,o]);s[2]=t.values[l];let u=e.locToIndex(s);0<=u&&u<e.values.length&&(n.values[a]=e.values[u])}return n}var pI=Yt((e,t)=>e>t?1:0),wq=xr(el,pI,null,"bool"),kq={kernelName:el,backendName:"cpu",kernelFunc:wq},hI=Yt((e,t)=>e>=t?1:0),Iq=xr(hi,hI,null,"bool"),Sq={kernelName:hi,backendName:"cpu",kernelFunc:Iq},cI=Yt((e,t)=>e<t?1:0),Tq=xr(tl,cI,null,"bool"),Nq={kernelName:tl,backendName:"cpu",kernelFunc:Tq},fI=Yt((e,t)=>e<=t?1:0),Cq=xr(rl,fI,null,"bool"),Eq={kernelName:rl,backendName:"cpu",kernelFunc:Cq};function mI(e,t,r){let n=(t-e)/(r-1),a=w.makeZerosTypedArray(r,"float32");a[0]=e;for(let s=1;s<a.length;s++)a[s]=a[s-1]+n;return a}var gI=Gi(e=>Math.log(e)),Rq=xd(mi,gI),Mq={kernelName:mi,backendName:"cpu",kernelFunc:Rq};function yI(e,t,r,n){let a=w.getTypedArrayFromDType(n,w.sizeFromShape(r));for(let s=0;s<a.length;++s){let i=s*t,o=e[i];for(let l=0;l<t;++l){let u=e[i+l];(Number.isNaN(u)||u>o)&&(o=u)}a[s]=o}return a}var AI=Yt((e,t)=>Math.max(e,t)),Fq=xr(yi,AI),$q={kernelName:yi,backendName:"cpu",kernelFunc:Fq},xI=Yt((e,t)=>Math.min(e,t)),Pq=xr(vi,xI),_q={kernelName:vi,backendName:"cpu",kernelFunc:Pq},Yx=Yt((e,t)=>e*t),zq=Kx((e,t,r,n)=>({real:e*r-t*n,imag:e*n+t*r})),y0=xr(ki,Yx,zq),Oq={kernelName:ki,backendName:"cpu",kernelFunc:y0};function bI(e,t,r){let n=w.createScalarValue(-1,r);return Yx([],t,n,e,r)}function Dq(e){let{inputs:t,backend:r}=e,{x:n}=t;Te(n,"neg");let a=r.data.get(n.dataId).values,[s,i]=bI(a,n.shape,n.dtype);return r.makeTensorInfo(i,n.dtype,s)}var Lq={kernelName:al,backendName:"cpu",kernelFunc:Dq},vI=Yt((e,t)=>e!==t?1:0),Bq=xr(sl,vI,null,"bool"),Wq={kernelName:sl,backendName:"cpu",kernelFunc:Bq};function Jx(e,t,r,n,a){let s=t.length,i=w.sizeFromShape(t),o=w.computeStrides(t),l=w.computeStrides(a),u=w.getTypedArrayFromDType(r,w.sizeFromShape(a));for(let d=0;d<i;++d){let h=w.indexToLoc(d,s,o),p=new Array(h.length);for(let f=0;f<p.length;f++)p[f]=h[n[f]];let c=w.locToIndex(p,s,l);u[c]=e[d]}return u}function an(e){let{inputs:t,attrs:r,backend:n}=e,{x:a}=t,{perm:s}=r;Te(a,"transpose");let i=a.shape.length,o=new Array(i);for(let d=0;d<o.length;d++)o[d]=a.shape[s[d]];let l=n.data.get(a.dataId).values,u=Jx(l,a.shape,a.dtype,s,o);return{dataId:n.write(u,o,a.dtype),shape:o,dtype:a.dtype}}var Vq={kernelName:Bi,backendName:"cpu",kernelFunc:an};function wI(e,t,r,n){let[a,s]=N.computeOutAndReduceShapes(e,n),i=Cr(t,"int32"),o=w.makeZerosTypedArray(w.sizeFromShape(a),i),l=w.sizeFromShape(s);for(let u=0;u<o.length;++u){let d=u*l,h=1;for(let p=0;p<l;++p)h*=r[d+p];o[u]=h}return{outVals:o,outShape:a,outDtype:i}}function Uq(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n;Te(a,"prod");let o=a.shape.length,l=w.parseAxisParam(s,a.shape),u=N.getAxesPermutation(l,o),d=l,h=a,p=[];u!=null&&(h=an({inputs:{x:a},backend:r,attrs:{perm:u}}),p.push(h),d=N.getInnerMostAxes(d.length,o));let c=r.data.get(h.dataId).values,{outVals:f,outShape:m,outDtype:g}=wI(h.shape,h.dtype,c,d),y=m;return i&&(y=N.expandShapeToKeepDim(m,l)),p.forEach(A=>r.disposeIntermediateTensorInfo(A)),r.makeTensorInfo(y,g,f)}var Gq={kernelName:Ni,backendName:"cpu",kernelFunc:Uq};function Qx(e,t,r,n){let a=e===t,s=e<t&&r<0,i=t<e&&r>1;if(a||s||i)return w.makeZerosTypedArray(0,n);let o=Math.abs(Math.ceil((t-e)/r)),l=w.makeZerosTypedArray(o,n);t<e&&r===1&&(r=-1),l[0]=e;for(let u=1;u<l.length;u++)l[u]=l[u-1]+r;return l}var kI=Gi(e=>1/Math.sqrt(e)),jq=xd(Mi,kI),Hq={kernelName:Mi,backendName:"cpu",kernelFunc:jq},qq=Gi(e=>1/(1+Math.exp(-e))),II=mt($i,e=>1/(1+Math.exp(-e))),Kq={kernelName:$i,backendName:"cpu",kernelFunc:II};function Of(e,t,r,n,a){let s=zt.isSliceContinous(n,t,r),i=w.sizeFromShape(r),o=w.computeStrides(n);if(s){let h=zt.computeFlatOffset(t,o);return a==="string"?e.slice(h,h+i):e.subarray(h,h+i)}let l=a==="string"?N.fromUint8ToStringArray(e):e,u=We(n,a,l),d=We(r,a);for(let h=0;h<d.size;++h){let p=d.indexToLoc(h),c=p.map((f,m)=>f+t[m]);d.set(u.get(...c),...p)}return a==="string"?N.fromStringArrayToUint8(d.values):d.values}function zo(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{begin:s,size:i}=n;Te(a,"slice");let[o,l]=zt.parseSliceParams(a,s,i);zt.assertParamsValid(a,o,l);let u=r.data.get(a.dataId).values,d=Of(u,o,l,a.shape,a.dtype);return r.makeTensorInfo(l,a.dtype,d)}var Xq={kernelName:gl,backendName:"cpu",kernelFunc:zo};function SI(e,t,r,n,a,s,i){let o=t[0],l=s[0],u=new Array(l),d=new Array(o),h=t[1];if(l===0){if(o!==0)throw new Error(N.getSparseFillEmptyRowsIndicesDenseShapeMismatch(o));let g=w.getArrayFromDType(r,0),y=w.getArrayFromDType(a,0);return[g,[0,h],y,u,d]}let p=!0,c=0,f=new Array(l).fill(0);for(let g=0;g<o;++g){let y=e[g*h];if(y<0)throw new Error(N.getSparseFillEmptyRowsNegativeIndexErrorMessage(g,y));if(y>=l)throw new Error(N.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(g,y,l));++f[y],p=p&&y>=c,c=y}let m=!0;for(let g=0;g<l;++g){let y=f[g]===0;u[g]=y,m=m&&!y,f[g]=Math.max(f[g],1),g>0&&(f[g]+=f[g-1])}if(m&&p){let g=e,y=n;for(let A=0;A<o;++A)d[A]=A;return[g,[o,h],y,u,d]}else{let g=f[l-1],y=w.getArrayFromDType(r,g*h),A=w.getArrayFromDType(a,g),x=new Array(l).fill(0);for(let b=0;b<o;++b){let v=e[b*h],S=x[v],T=(v===0?0:f[v-1])+S;x[v]++;for(let E=0;E<h;++E)y[T*h+E]=e[b*h+E];A[T]=n[b],d[b]=T}for(let b=0;b<l;++b)if(x[b]===0){let v=b===0?0:f[b-1];y[v*h+0]=b;for(let S=1;S<h;++S)y[v*h+S]=0;A[v]=i}return[y,[g,h],A,u,d]}}function TI(e,t,r,n,a){let s=w.sizeFromShape(n),i=t[0],o=a.length,l=[],u=1,d=-1;for(let m=0;m<o;++m){let g=a[m];if(g===-1){if(d!==-1)throw new Error(N.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(d,m));d=m,l.push(1)}else{if(g<0)throw new Error(N.getSparseReshapeNegativeOutputDimErrorMessage(m,g));u*=g,l.push(g)}}if(d!==-1){if(u<=0)throw new Error(N.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage());let m=Math.trunc(s/u);if(u*m!==s)throw new Error(N.getSparseReshapeInputOutputMultipleErrorMessage(n,l));l[d]=m}if(w.sizeFromShape(l)!==s)throw new Error(N.getSparseReshapeInputOutputMismatchErrorMessage(n,l));let h=n.length,p=[];if(h>0){p[h-1]=1;for(let m=h-2;m>=0;--m)p[m]=p[m+1]*n[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<h;++y)g+=e[m*h+y]*p[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 eb(e,t,r,n,a,s=!1,i=0){let o=n.length,l=[t[0],e.length/t[0]],u=l[1],d=o>0?a[o-1]+1:0;if(d<0)throw new Error(N.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let h=t.slice();h[0]=d;let p=h.reduce((A,x)=>A*x,1),c=w.getArrayFromDType(r,p);if(o===0)return d>0&&c.fill(i),[c,h];if(d<=0)throw new Error(N.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let f=0,m=1,g=0,y=a[f];for(;;){let A=0;if(m<o){if(A=a[m],y===A){++m;continue}if(y>=A)throw new Error(N.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage())}if(y<0||y>=d)throw new Error(N.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(y,d));y>g&&c.fill(i,g*u,y*u);for(let x=f;x<m;++x){let b=n[x];if(b<0||b>=l[0])throw new Error(N.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(x,n[x],l[0]));for(let v=0;v<u;v++)c[y*u+v]+=e[b*u+v]}if(s)for(let x=0;x<u;x++)c[y*u+x]/=m-f;if(f=m,++m,g=y+1,y=A,m>o)break}return g<d&&c.fill(i,g*u,d*u),[c,h]}var Zq=Gi(e=>Math.sqrt(e)),Yq=mt(Pi,e=>Math.sqrt(e)),Jq={kernelName:Pi,backendName:"cpu",kernelFunc:Yq},NI=Yt((e,t)=>{let r=e-t;return r*r}),Qq=xr(Oi,NI),eK={kernelName:Oi,backendName:"cpu",kernelFunc:Qq};function CI(e,t,r,n){let a=We(e,t.dtype);for(let s=0;s<a.size;s++){let i=a.indexToLoc(s),o=new Array(i.length);for(let l=0;l<o.length;l++)o[l]=i[l]*r[l]+n[l];a.set(t.get(...o),...i)}return a}var tK=class{constructor(e,t,r,n,a,s){this.separator=w.encodeString(e),this.nGramWidths=t,this.leftPad=w.encodeString(r),this.rightPad=w.encodeString(n),this.padWidth=a,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,n,a,s){for(let i=0;i<a;++i){let o=this.getPadWidth(s),l=Math.max(0,o-i),u=Math.max(0,o-(a-(i+1))),d=s-(l+u),h=t+(l>0?0:i-o),p=0;p+=l*this.leftPad.length;for(let g=0;g<d;++g)p+=e[h+g].length;p+=u*this.rightPad.length,p+=(l+u+d-1)*this.separator.length,r[n+i]=new Uint8Array(p);let c=r[n+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<d-1;++g)m(e[h+g]),m(this.separator);if(d>0){m(e[h+d-1]);for(let g=0;g<u;++g)m(this.separator),m(this.rightPad)}else{for(let g=0;g<u-1;++g)m(this.rightPad),m(this.separator);m(this.rightPad)}}}compute(e,t){let r=e.length,n=t.length;if(n>0){let o=t[0];if(o!==0)throw new Error(`First split value must be 0, got ${o}`);for(let l=1;l<n;++l){let u=t[l]>=o;if(u=u&&t[l]<=r,!u)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 a=n-1,s=w.getArrayFromDType("int32",n);if(r===0||n===0){let o=new Array(r);for(let l=0;l<=a;++l)s[l]=0;return[o,s]}s[0]=0;for(let o=1;o<=a;++o){let l=t[o]-t[o-1],u=0;this.nGramWidths.forEach(d=>{u+=this.getNumNGrams(l,d)}),this.preserveShort&&l>0&&u===0&&(u=1),s[o]=s[o-1]+u}let i=new Array(s[a]);for(let o=0;o<a;++o){let l=t[o],u=s[o];if(this.nGramWidths.forEach(d=>{let h=t[o+1]-t[o],p=this.getNumNGrams(h,d);this.createNGrams(e,l,i,u,p,d),u+=p}),this.preserveShort&&u===s[o]){let d=t[o+1]-t[o];if(d===0)continue;let h=d+2*this.padWidth,p=1;this.createNGrams(e,l,i,u,p,h)}}return[i,s]}};function EI(e,t,r,n,a,s,i,o){return new tK(r,n,a,s,i,o).compute(e,t)}function rK(e,t,r,n){if(!e.length)return;if(t.length===0){for(let s=0;s<e.length;++s)n.push(e.subarray(s,s+1));return}if(t.length===1){let s=t[0],i=e.indexOf(s);for(;i!==-1;){let o=e.subarray(0,i);(!r||o.length!==0)&&n.push(o),e=e.subarray(i+1),i=e.indexOf(s)}(!r||e.length!==0)&&n.push(e);return}let a=0;for(let s=0;s<e.length+1;s++)if(s===e.length||t.indexOf(e[s])!==-1){let i=e.subarray(a,s);(!r||i.length!==0)&&n.push(i),a=s+1}}function RI(e,t,r){let n=e.length,a=[],s=0,i=0,o=new Array(n);for(let p=0;p<n;++p){let c=a.length;rK(e[p],t,r,a);let f=a.length-c;o[p]=f,s+=f,i=Math.max(i,f)}let l=w.getArrayFromDType("int32",s*2),u=new Array(s),d=[n,i],h=0;for(let p=0;p<n;++p)for(let c=0;c<o[p];++c)l[h*2]=p,l[h*2+1]=c,u[h]=a[h],++h;return[l,u,d]}function MI(e,t){let r=w.getArrayFromDType("int32",e.length);for(let n=0;n<e.length;++n)r[n]=w.fingerPrint64(e[n]).modulo(t).getLowBitsUnsigned();return r}var FI=Yt((e,t)=>e-t),nK=Kx((e,t,r,n)=>({real:e-r,imag:t-n})),tb=xr(Di,FI,nK),aK={kernelName:Di,backendName:"cpu",kernelFunc:tb};function $I(e,t){let r=new Array(e.rank);for(let a=0;a<r.length;a++)r[a]=e.shape[a]*t[a];let n=We(r,e.dtype);for(let a=0;a<n.values.length;++a){let s=n.indexToLoc(a),i=new Array(e.rank);for(let l=0;l<i.length;l++)i[l]=s[l]%e.shape[l];let o=e.locToIndex(i);n.values[a]=e.values[o]}return n}var kp=(e,t)=>{let r=t.value-e.value;return r===0?e.index-t.index:r};function PI(e,t,r=0,n=e.length-1){for(;n>r;){if(n-r>600){let o=n-r+1,l=t-r+1,u=Math.log(o),d=.5*Math.exp(2*u/3),h=.5*Math.sqrt(u*d*(o-d)/o)*Math.sign(l-o/2),p=Math.max(r,Math.floor(t-l*d/o+h)),c=Math.min(n,Math.floor(t+(o-l)*d/o+h));PI(e,t,p,c)}let a=e[t],s=r,i=n;for(w.swap(e,r,t),kp(e[n],a)>0&&w.swap(e,r,n);s<i;){for(w.swap(e,s,i),s++,i--;kp(e[s],a)<0;)s=s+1;for(;kp(e[i],a)>0;)i=i-1}kp(e[r],a)===0?w.swap(e,r,i):(i=i+1,w.swap(e,i,n)),i<=t&&(r=i+1),t<=i&&(n=i-1)}}function _I(e,t,r,n,a){let s=t[t.length-1],[i,o]=[e.length/s,s],l=w.getTypedArrayFromDType(r,i*n),u=w.getTypedArrayFromDType("int32",i*n);for(let h=0;h<i;h++){let p=h*o,c=e.subarray(p,p+o),f=new Array(c.length);c.forEach((A,x)=>f[x]={value:A,index:x}),n<f.length&&(PI(f,n),f=f.slice(0,n)),a&&f.sort(kp);let m=h*n,g=l.subarray(m,m+n),y=u.subarray(m,m+n);for(let A=0;A<n;A++)g[A]=f[A].value,y[A]=f[A].index}let d=t.slice();return d[d.length-1]=n,[We(d,r,l),We(d,"int32",u)]}function zI(e,t,r,n){let a=w.parseAxisParam(t,r)[0],s=[1,r[0],1];for(let f=0;f<a;f++)s[0]*=r[f];s[1]=r[a];for(let f=a+1;f<r.length;f++)s[2]*=r[f];let i={},o=new Int32Array(r[a]),l=new sr(s,n,e),u=[],d=s[0]===1&&s[2]===1;for(let f=0;f<r[a];f++){let m;if(d)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,u.push(f)}}let h=s.slice();h[1]=Object.keys(i).length;let p=new sr(h,n);u.forEach((f,m)=>{for(let g=0;g<s[0];g++)for(let y=0;y<s[2];y++)p.set(l.get(g,f,y),g,m,y)});let c=r.slice();return c[a]=h[1],{outputValues:p.values,outputShape:c,indices:o}}var sK="0.0.0";Cl("cpu",()=>new qx,1);var OI=mt(oi,e=>e>=0?e:Math.exp(e)-1),iK={kernelName:oi,backendName:"cpu",kernelFunc:OI};function DI(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{alpha:s}=n;Te([a],"leakyRelu");let i=w.sizeFromShape(a.shape),o=r.data.get(a.dataId).values,l=w.getTypedArrayFromDType("float32",i);for(let u=0;u<o.length;u++)l[u]=o[u]<0?s*o[u]:o[u];return r.makeTensorInfo(a.shape,"float32",l)}var oK={kernelName:fi,backendName:"cpu",kernelFunc:DI},lK=Yt((e,t)=>e<0?t*e:e);function LI(e){let{inputs:t,backend:r}=e,{x:n,alpha:a}=t;Te([n,a],"prelu");let s=r.data.get(n.dataId).values,i=r.data.get(a.dataId).values,[o,l]=lK(n.shape,a.shape,s,i,"float32");return r.makeTensorInfo(l,"float32",o)}var uK={kernelName:Ti,backendName:"cpu",kernelFunc:LI},BI=mt(Ci,e=>Math.max(0,e)),dK={kernelName:Ci,backendName:"cpu",kernelFunc:BI},WI=mt(Ri,e=>Math.min(Math.max(0,e),6)),pK={kernelName:Ri,backendName:"cpu",kernelFunc:WI};function rb(e,t,r,n,a){if(r==="linear")return $a({inputs:{x:t},backend:e});if(r==="relu")return BI({inputs:{x:t},backend:e});if(r==="elu")return OI({inputs:{x:t},backend:e});if(r==="relu6")return WI({inputs:{x:t},backend:e});if(r==="prelu")return LI({inputs:{x:t,alpha:n},backend:e});if(r==="leakyrelu")return DI({inputs:{x:t},backend:e,attrs:{alpha:a}});if(r==="sigmoid")return II({inputs:{x:t},backend:e});throw new Error(`Activation ${r} has not been implemented for the CPU backend.`)}function Mt(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{shape:s}=n,i=w.sizeFromShape(a.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 (${a.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`),r.incRef(a.dataId);let u=r.data.get(a.dataId);if(u.complexTensorInfos!=null){let d=u.complexTensorInfos.real,h=u.complexTensorInfos.imag;d.shape=o,h.shape=o}return{dataId:a.dataId,shape:o,dtype:a.dtype}}var hK={kernelName:pl,backendName:"cpu",kernelFunc:Mt};function VI(e){let{inputs:t,backend:r,attrs:n}=e,{a,b:s}=t,{transposeA:i,transposeB:o}=n;Te([a,s],"matMul");let l=a.shape.length,u=s.shape.length,d=i?a.shape[l-2]:a.shape[l-1],h=o?s.shape[u-1]:s.shape[u-2],p=i?a.shape[l-1]:a.shape[l-2],c=o?s.shape[u-2]:s.shape[u-1],f=a.shape.slice(0,-2),m=s.shape.slice(0,-2),g=w.sizeFromShape(f),y=w.sizeFromShape(m),A=Nl.assertAndGetBroadcastShape(a.shape.slice(0,-2),s.shape.slice(0,-2)).concat([p,c]);w.assert(d===h,()=>`Error in matMul: inner shapes (${d}) and (${h}) of Tensors with shapes ${a.shape} and ${s.shape} and transposeA=${i} and transposeB=${o} must match.`);let x=i?[g,d,p]:[g,p,d],b=o?[y,c,h]:[y,h,c],v=Mt({inputs:{x:a},backend:r,attrs:{shape:x}}),S=Mt({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?S.shape[1]:S.shape[2],_=Math.max(g,y),M=r.data.get(v.dataId).values,I=r.data.get(S.dataId).values,z=w.computeStrides(v.shape),O=w.computeStrides(S.shape),[j,X,D]=i?[z[0],1,z[1]]:[z[0],z[1],1],[Q,V,ee]=o?[1,O[1],O[0]]:[O[1],1,O[0]],J=E*R,ie=We([_,E,R],v.dtype),Z=ie.values,ae=r.blockSize;for(let de=0;de<_;de++)for(let Ae=0;Ae<E;Ae+=ae)for(let be=0;be<R;be+=ae)for(let Ee=0;Ee<T;Ee+=ae){let Me=Math.min(Ae+ae,E),De=Math.min(be+ae,R),Be=Math.min(Ee+ae,T);for(let Ze=Ae;Ze<Me;Ze++)for(let ot=be;ot<De;ot++){let dt=0;for(let pt=Ee;pt<Be;pt++){let $e=Math.min(de,g-1)*j,vt=Math.min(de,y-1)*ee,yt=M[$e+Ze*X+pt*D],$r=I[pt*Q+ot*V+vt];dt+=yt*$r}Z[de*J+(Ze*R+ot)]+=dt}}return r.disposeIntermediateTensorInfo(v),r.disposeIntermediateTensorInfo(S),r.makeTensorInfo(A,ie.dtype,ie.values)}var cK={kernelName:Ys,backendName:"cpu",kernelFunc:VI};function fK(e){let{inputs:t,backend:r,attrs:n}=e,{a,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:u,activation:d,leakyreluAlpha:h}=n,p,c,f,m=[];p=VI({inputs:{a,b:s},attrs:{transposeA:l,transposeB:u},backend:r}),i&&(c=$h({inputs:{a:p,b:i},backend:r}),m.push(p),p=c),d&&(f=rb(r,p,d,o,h),m.push(p),p=f);for(let g of m)r.disposeIntermediateTensorInfo(g);return p}var mK={kernelName:Fs,backendName:"cpu",kernelFunc:fK},gK=mt(_u,e=>Math.acos(e)),yK={kernelName:_u,backendName:"cpu",kernelFunc:gK},AK=mt(zu,e=>Math.acosh(e)),xK={kernelName:zu,backendName:"cpu",kernelFunc:AK};function bK(e){let{inputs:t,backend:r}=e,n=t;Te(t,"addN");let a=n.map(o=>r.data.get(o.dataId).values),s=We(n[0].shape,n[0].dtype),i=s.values;for(let o=0;o<n.length;o++){let l=a[o];for(let u=0;u<i.length;u++)i[u]+=l[u]}return r.makeTensorInfo(s.shape,s.dtype,s.values)}var vK={kernelName:Ks,backendName:"cpu",kernelFunc:bK};function wK(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n;Te(a,"all");let o=w.parseAxisParam(s,a.shape),l=o,u=N.getAxesPermutation(l,a.shape.length),d=a;u!=null&&(d=an({inputs:{x:a},backend:r,attrs:{perm:u}}),l=N.getInnerMostAxes(l.length,a.shape.length)),N.assertAxesAreInnerMostDims("all",l,d.shape.length);let[h,p]=N.computeOutAndReduceShapes(d.shape,l),c=w.sizeFromShape(p),f=w.makeZerosTypedArray(w.sizeFromShape(h),d.dtype),m=r.data.get(d.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}u!=null&&r.disposeIntermediateTensorInfo(d);let g=r.makeTensorInfo(h,d.dtype,f);if(i){let y=N.expandShapeToKeepDim(h,o),A=Mt({inputs:{x:g},backend:r,attrs:{shape:y}});return r.disposeIntermediateTensorInfo(g),A}return g}var kK={kernelName:Ou,backendName:"cpu",kernelFunc:wK};function IK(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n;Te(a,"any");let o=w.parseAxisParam(s,a.shape),l=o,u=N.getAxesPermutation(l,a.shape.length),d=a;u!=null&&(d=an({inputs:{x:a},backend:r,attrs:{perm:u}}),l=N.getInnerMostAxes(l.length,a.shape.length)),N.assertAxesAreInnerMostDims("any",l,d.shape.length);let[h,p]=N.computeOutAndReduceShapes(d.shape,l),c=w.sizeFromShape(p),f=w.makeZerosTypedArray(w.sizeFromShape(h),d.dtype),m=r.data.get(d.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}u!=null&&r.disposeIntermediateTensorInfo(d);let g=r.makeTensorInfo(h,d.dtype,f);if(i){let y=N.expandShapeToKeepDim(h,o),A=Mt({inputs:{x:g},backend:r,attrs:{shape:y}});return r.disposeIntermediateTensorInfo(g),A}return g}var SK={kernelName:Du,backendName:"cpu",kernelFunc:IK};function TK(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s}=n;Te(a,"argMax");let i=w.parseAxisParam(s,a.shape),o=N.getAxesPermutation(i,a.shape.length),l=a,u=[];o!=null&&(l=an({inputs:{x:a},backend:r,attrs:{perm:o}}),u.push(l),i=N.getInnerMostAxes(i.length,l.shape.length)),i=[i[0]],N.assertAxesAreInnerMostDims("argMax",i,l.shape.length);let[d,h]=N.computeOutAndReduceShapes(l.shape,i),p=w.sizeFromShape(d),c=w.makeZerosTypedArray(p,"int32"),f=w.sizeFromShape(h),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 u.forEach(g=>r.disposeIntermediateTensorInfo(g)),r.makeTensorInfo(d,"int32",c)}var NK={kernelName:Xs,backendName:"cpu",kernelFunc:TK};function CK(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s}=n;Te(a,"argMin");let i=w.parseAxisParam(s,a.shape),o=N.getAxesPermutation(i,a.shape.length),l=a,u=[];o!=null&&(l=an({inputs:{x:a},backend:r,attrs:{perm:o}}),u.push(l),i=N.getInnerMostAxes(i.length,l.shape.length)),i=[i[0]],N.assertAxesAreInnerMostDims("argMin",i,l.shape.length);let[d,h]=N.computeOutAndReduceShapes(l.shape,i),p=w.sizeFromShape(d),c=w.makeZerosTypedArray(p,"int32"),f=w.sizeFromShape(h),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 u.forEach(g=>r.disposeIntermediateTensorInfo(g)),r.makeTensorInfo(d,"int32",c)}var EK={kernelName:Lu,backendName:"cpu",kernelFunc:CK},RK=mt(Bu,e=>Math.asin(e)),MK={kernelName:Bu,backendName:"cpu",kernelFunc:RK},FK=mt(Wu,e=>Math.asinh(e)),$K={kernelName:Wu,backendName:"cpu",kernelFunc:FK},PK=mt(Vu,e=>Math.atan(e)),_K={kernelName:Vu,backendName:"cpu",kernelFunc:PK},zK=Yt((e,t)=>Math.atan2(e,t)),OK=xr(Gu,zK),DK={kernelName:Gu,backendName:"cpu",kernelFunc:OK},LK=mt(Uu,e=>Math.atanh(e)),BK={kernelName:Uu,backendName:"cpu",kernelFunc:LK};function nb(e,t,r,n,a,s){let i=a.strideHeight,o=a.strideWidth,l=a.dilationHeight,u=a.dilationWidth,d=a.effectiveFilterHeight,h=a.effectiveFilterWidth,p=a.padInfo.top,c=a.padInfo.left,f=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=We(a.outShape,r),g=m.values,y=a.outShape[1]*a.outShape[2]*a.outShape[3],A=a.outShape[2]*a.outShape[3],x=a.outShape[3];for(let b=0;b<a.batchSize;++b){let v=b*y,S=b*n[0];for(let T=0;T<a.inChannels;++T)for(let E=0;E<a.outHeight;++E){let R=E*i-p,_=Math.max(0,R),M=Math.min(a.inHeight,d+R),I=v+E*A;for(let z=0;z<a.outWidth;++z){let O=z*o-c,j=Math.max(0,O),X=Math.min(a.inWidth,h+O),D=f,Q=0,V=0;for(let J=_;J<M;J+=l){let ie=S+J*n[1];for(let Z=j;Z<X;Z+=u){let ae=ie+Z*n[2],de=e[ae+T];s==="max"&&de>D?D=de:s==="avg"&&(Q+=de,V++)}if(isNaN(D))break}let ee=I+z*x+T;g[ee]=s==="avg"?Q/V:D}}}return m}function UI(e,t,r,n,a=!1,s=!1){let i=We(n.outShape,"int32"),o=n.strideHeight,l=n.strideWidth,u=n.dilationHeight,d=n.dilationWidth,h=n.effectiveFilterHeight,p=n.effectiveFilterWidth,c=n.padInfo.top,f=n.padInfo.left,m=We(t,r,e);for(let g=0;g<n.batchSize;++g)for(let y=0;y<n.inChannels;++y)for(let A=0;A<n.outHeight;++A){let x=A*o-c,b=x;for(;b<0;)b+=u;let v=Math.min(n.inHeight,h+x);for(let S=0;S<n.outWidth;++S){let T=S*l-f,E=T;for(;E<0;)E+=d;let R=Math.min(n.inWidth,p+T),_=Number.NEGATIVE_INFINITY,M=-1;for(let I=b;I<v;I+=u){let z=I-x;for(let O=E;O<R;O+=d){let j=O-T,X=m.get(g,I,O,y);X>_&&(_=X,a?M=s?((g*n.inHeight+I)*n.inWidth+O)*n.inChannels+y:(I*n.inWidth+O)*n.inChannels+y:M=z*p+j)}}i.set(M,g,A,S,y)}}return i}function GI(e,t,r,n,a,s){let i=a.strideDepth,o=a.strideHeight,l=a.strideWidth,u=a.dilationDepth,d=a.dilationHeight,h=a.dilationWidth,p=a.effectiveFilterDepth,c=a.effectiveFilterHeight,f=a.effectiveFilterWidth,m=a.padInfo.front,g=a.padInfo.top,y=a.padInfo.left,A=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,x=We(a.outShape,r),b=x.values,v=a.outShape[1]*a.outShape[2]*a.outShape[3]*a.outShape[4],S=a.outShape[2]*a.outShape[3]*a.outShape[4],T=a.outShape[3]*a.outShape[4],E=a.outShape[4];for(let R=0;R<a.batchSize;++R){let _=R*v,M=R*n[0];for(let I=0;I<a.inChannels;++I)for(let z=0;z<a.outDepth;++z){let O=z*i-m,j=O;for(;j<0;)j+=u;let X=Math.min(a.inDepth,p+O),D=_+z*S;for(let Q=0;Q<a.outHeight;++Q){let V=Q*o-g,ee=V;for(;ee<0;)ee+=d;let J=Math.min(a.inHeight,c+V),ie=D+Q*T;for(let Z=0;Z<a.outWidth;++Z){let ae=Z*l-y,de=ae;for(;de<0;)de+=h;let Ae=Math.min(a.inWidth,f+ae),be=ie+Z*E,Ee=A,Me=0,De=0;for(let Ze=j;Ze<X;Ze+=u){let ot=M+Ze*n[1];for(let dt=ee;dt<J;dt+=d){let pt=ot+dt*n[2];for(let $e=de;$e<Ae;$e+=h){let vt=pt+$e*n[3],yt=e[vt+I];if(s==="max"&&yt>Ee?Ee=yt:s==="avg"&&(Me+=yt,De++),isNaN(Ee))break}if(isNaN(Ee))break}if(isNaN(Ee))break}let Be=be+I;b[Be]=s==="avg"?Me/De:Ee}}}}return x}function WK(e,t){let r=We(t.outShape,"int32"),n=t.strideDepth,a=t.strideHeight,s=t.strideWidth,i=t.dilationDepth,o=t.dilationHeight,l=t.dilationWidth,u=t.effectiveFilterDepth,d=t.effectiveFilterHeight,h=t.effectiveFilterWidth,p=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*n-p,x=A;for(;x<0;)x+=i;let b=Math.min(t.inDepth,u+A);for(let v=0;v<t.outHeight;++v){let S=v*a-c,T=S;for(;T<0;)T+=o;let E=Math.min(t.inHeight,d+S);for(let R=0;R<t.outWidth;++R){let _=R*s-f,M=_;for(;M<0;)M+=l;let I=Math.min(t.inWidth,h+_),z=Number.NEGATIVE_INFINITY,O=-1;for(let j=x;j<b;j+=i){let X=j-A;for(let D=T;D<E;D+=o){let Q=D-S;for(let V=M;V<I;V+=l){let ee=V-_,J=e.get(m,j,D,V,g);J>=z&&(z=J,O=X*d*h+Q*d+ee)}}}r.set(O,m,y,v,R,g)}}}return r}function VK(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t;Te(a,"avgPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,u=1;w.assert(N.eitherStridesOrDilationsAreOne(i,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let d=N.computePool2DInfo(a.shape,s,i,u,o,l),h;if(d.filterWidth===1&&d.filterHeight===1&&w.arraysEqual(d.inShape,d.outShape))h=$a({inputs:{x:a},backend:r});else{let p=r.data.get(a.dataId).values,c=w.computeStrides(a.shape),f=nb(p,a.shape,a.dtype,c,d,"avg");h=r.makeTensorInfo(d.outShape,a.dtype,f.values)}return h}var UK={kernelName:Zs,backendName:"cpu",kernelFunc:VK};function GK(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=n;Te(a,"avgPool3d");let d=N.computePool3DInfo(a.shape,s,i,1,o,l,u),h=r.data.get(a.dataId).values,p=GI(h,a.shape,a.dtype,w.computeStrides(a.shape),d,"avg");return r.makeTensorInfo(p.shape,"float32",p.values)}var jK={kernelName:Kp,backendName:"cpu",kernelFunc:GK};function HK(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=n;Te([a,s],"avgPool3DGrad");let d=N.computePool3DInfo(s.shape,i,o,1,l,u),h=d.strideDepth,p=d.strideHeight,c=d.strideWidth,f=d.filterDepth,m=d.filterHeight,g=d.filterWidth,y=d.dilationDepth,A=d.dilationHeight,x=d.dilationWidth,b=d.effectiveFilterDepth,v=d.effectiveFilterHeight,S=d.effectiveFilterWidth,T=b-1-d.padInfo.front,E=S-1-d.padInfo.left,R=v-1-d.padInfo.top,_=We(s.shape,"float32"),M=1/(f*m*g),I=r.bufferSync(a);for(let z=0;z<d.batchSize;++z)for(let O=0;O<d.inChannels;++O)for(let j=0;j<d.inDepth;++j)for(let X=0;X<d.inHeight;++X)for(let D=0;D<d.inWidth;++D){let Q=j-T,V=X-R,ee=D-E,J=0;for(let ie=0;ie<b;ie+=y){let Z=(Q+ie)/h;if(!(Z<0||Z>=d.outDepth||Math.floor(Z)!==Z))for(let ae=0;ae<v;ae+=A){let de=(V+ae)/p;if(!(de<0||de>=d.outHeight||Math.floor(de)!==de))for(let Ae=0;Ae<S;Ae+=x){let be=(ee+Ae)/c;be<0||be>=d.outWidth||Math.floor(be)!==be||(J+=I.get(z,Z,de,be,O))}}}_.set(J*M,z,j,X,D,O)}return r.makeTensorInfo(_.shape,_.dtype,_.values)}var qK={kernelName:Xf,backendName:"cpu",kernelFunc:HK};function KK(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s}=t,i=s;Te([a,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:u}=n,d=N.computePool2DInfo(i.shape,o,l,1,u),h=d.strideHeight,p=d.strideWidth,c=d.filterHeight,f=d.filterWidth,m=d.dilationHeight,g=d.dilationWidth,y=d.effectiveFilterHeight,A=d.effectiveFilterWidth,x=A-1-d.padInfo.left,b=y-1-d.padInfo.top,v=We(i.shape,"float32"),S=1/(c*f),T=r.data.get(a.dataId).values,E=We(a.shape,"float32",T);for(let R=0;R<d.batchSize;++R)for(let _=0;_<d.inChannels;++_)for(let M=0;M<d.inHeight;++M)for(let I=0;I<d.inWidth;++I){let z=M-b,O=I-x,j=0;for(let X=0;X<y;X+=m){let D=(z+X)/h;if(!(D<0||D>=d.outHeight||Math.floor(D)!==D))for(let Q=0;Q<A;Q+=g){let V=(O+Q)/p;V<0||V>=d.outWidth||Math.floor(V)!==V||(j+=E.get(R,D,V,_))}}v.set(j*S,R,M,I,_)}return r.makeTensorInfo(v.shape,v.dtype,v.values)}var XK={kernelName:Kf,backendName:"cpu",kernelFunc:KK};function ZK(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,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."),Te([a,o,l,s,i],"batchNorm");let{varianceEpsilon:u}=n;u==null&&(u=.001);let d=r.data.get(a.dataId).values,h=r.data.get(o.dataId).values,p=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(d.length),g=f.length,y=c.length,A=p.length,x=h.length,b=0,v=0,S=0,T=0;for(let E=0;E<d.length;++E)m[E]=f[b++]+(d[E]-h[v++])*c[S++]/Math.sqrt(p[T++]+u),b>=g&&(b=0),v>=x&&(v=0),S>=y&&(S=0),T>=A&&(T=0);return r.makeTensorInfo(a.shape,a.dtype,m)}var YK={kernelName:pi,backendName:"cpu",kernelFunc:ZK};function JK(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockShape:s,crops:i}=n;Te([a],"batchToSpaceND");let o=s.reduce((y,A)=>y*A),l=N.getReshaped(a.shape,s,o),u=N.getPermuted(l.length,s.length),d=N.getReshapedPermuted(a.shape,s,o),h=N.getSliceBeginCoords(i,s.length),p=N.getSliceSize(d,i,s.length),c=Mt({inputs:{x:a},backend:r,attrs:{shape:l}}),f=an({inputs:{x:c},backend:r,attrs:{perm:u}}),m=Mt({inputs:{x:f},backend:r,attrs:{shape:d}}),g=zo({inputs:{x:m},backend:r,attrs:{begin:h,size:p}});return r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(f),r.disposeIntermediateTensorInfo(m),g}var QK={kernelName:Uo,backendName:"cpu",kernelFunc:JK};function eX(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,weights:s}=t,{size:i}=n,o=r.data.get(a.dataId).values,l=r.data.get(s.dataId).values,u=Xx(o,l,s.dtype,s.shape,i);return r.makeTensorInfo([i],s.dtype,u)}var tX={kernelName:Zf,backendName:"cpu",kernelFunc:eX};function rX(e){let{inputs:t,backend:r}=e,{s0:n,s1:a}=t,s=r.data.get(n.dataId).values,i=r.data.get(a.dataId).values,o=N.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return r.makeTensorInfo([o.length],"int32",Int32Array.from(o))}var nX={kernelName:Yf,backendName:"cpu",kernelFunc:rX},aX=mt(Qa,(e,t)=>{let r=t;return e>r.clipValueMax?r.clipValueMax:e<r.clipValueMin?r.clipValueMin:e}),sX={kernelName:Qa,backendName:"cpu",kernelFunc:aX},iX=e=>{let{x:t}=e.inputs,r=e.backend,n=new Float32Array(w.sizeFromShape(t.shape)),a=r.data.get(t.dataId),s=a.complexTensorInfos.real,i=a.complexTensorInfos.imag,o=r.data.get(s.dataId).values,l=r.data.get(i.dataId).values;for(let u=0;u<o.length;u++){let d=o[u],h=l[u];n[u]=Math.hypot(d,h)}return r.makeOutput(n,t.shape,"float32")},oX={kernelName:Zp,backendName:"cpu",kernelFunc:iX};function Ru(e){let{inputs:t,backend:r}=e,{input:n}=t,a=r.data.get(n.dataId).complexTensorInfos.imag,s=r.data.get(a.dataId).values;return r.makeTensorInfo(a.shape,a.dtype,s)}var lX={kernelName:eh,backendName:"cpu",kernelFunc:Ru};function Mu(e){let{inputs:t,backend:r,attrs:n}=e,{axis:a}=n,s=w.parseAxisParam(a,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 $a({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=>_o({inputs:{input:b},backend:r})),g=o.map(b=>Ru({inputs:{input:b},backend:r})),y=Mu({inputs:m,backend:r,attrs:{axis:s}}),A=Mu({inputs:g,backend:r,attrs:{axis:s}}),x=pn({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 u=o.map(m=>{let g=w.sizeFromShape(m.shape.slice(s));return Mt({inputs:{x:m},backend:r,attrs:{shape:[-1,g]}})}),d=u.map(m=>({vals:r.data.get(m.dataId).values,shape:m.shape}));i=N.computeOutShape(u.map(m=>m.shape),1);let h=u[0].shape[0]===1,p=Zx(d,i,t[0].dtype,h),c=N.computeOutShape(o.map(m=>m.shape),s),f=r.makeTensorInfo(c,t[0].dtype,p);return u.forEach(m=>r.disposeIntermediateTensorInfo(m)),f}var uX={kernelName:Go,backendName:"cpu",kernelFunc:Mu};function jI(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:d}=n;Te([a,s],"conv2d");let h=N.convertConv2DDataFormat(l),p=N.computeConv2DInfo(a.shape,s.shape,i,u,o,d,!1,h),c=p.filterHeight,f=p.filterWidth,m=p.dilationHeight,g=p.dilationWidth,y=p.padInfo.left,A=p.padInfo.top,x=p.dataFormat==="channelsLast",b=new sr(p.outShape,a.dtype),v=w.computeStrides(a.shape),S=w.computeStrides(s.shape),T=v[0],E=x?v[1]:v[2],R=x?v[2]:1,_=x?1:v[1],M=b.strides[0],I=x?b.strides[1]:b.strides[2],z=x?b.strides[2]:1,O=x?1:b.strides[1],j=r.data.get(a.dataId).values,X=r.data.get(s.dataId).values,D=b.values;for(let Q=0;Q<p.batchSize;++Q){let V=Q*T,ee=Q*M;for(let J=0;J<p.outHeight;++J){let ie=ee+J*I,Z=J*p.strideHeight-A;for(let ae=0;ae<c;++ae){let de=Z+ae*m;if(de<0||de>=p.inHeight)continue;let Ae=ae*S[0],be=V+de*E;for(let Ee=0;Ee<p.outWidth;++Ee){let Me=ie+Ee*z,De=Ee*p.strideWidth-y;for(let Be=0;Be<f;++Be){let Ze=De+Be*g;if(Ze<0||Ze>=p.inWidth)continue;let ot=Ae+Be*S[1],dt=be+Ze*R,pt=ot;for(let $e=0;$e<p.inChannels;++$e){let vt=j[dt+$e*_];for(let yt=0;yt<p.outChannels;++yt)D[Me+yt*O]+=vt*X[pt+yt];pt+=p.outChannels}}}}}}return r.makeTensorInfo(b.shape,b.dtype,D)}var dX={kernelName:ei,backendName:"cpu",kernelFunc:jI};function pX(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,dy:s}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,filterShape:d}=n;Te([a,s],"conv2dBackpropFilter");let h=N.convertConv2DDataFormat(l),p=N.computeConv2DInfo(a.shape,d,i,1,o,u,!1,h),{strideHeight:c,strideWidth:f,filterHeight:m,filterWidth:g}=p,y=p.dataFormat==="channelsLast",A=new sr(p.filterShape,"float32"),x=p.padInfo.left,b=p.padInfo.top,v=r.data.get(a.dataId).values,S=r.data.get(s.dataId).values,T=new sr(a.shape,a.dtype,v),E=new sr(s.shape,s.dtype,S);for(let R=0;R<m;++R){let _=Math.max(0,Math.ceil((b-R)/c)),M=Math.min(p.outHeight,(p.inHeight+b-R)/c);for(let I=0;I<g;++I){let z=Math.max(0,Math.ceil((x-I)/f)),O=Math.min(p.outWidth,(p.inWidth+x-I)/f);for(let j=0;j<p.inChannels;++j)for(let X=0;X<p.outChannels;++X){let D=0;for(let Q=0;Q<p.batchSize;++Q)for(let V=_;V<M;++V){let ee=R+V*c-b;for(let J=z;J<O;++J){let ie=I+J*f-x;y?D+=T.get(Q,ee,ie,j)*E.get(Q,V,J,X):D+=T.get(Q,j,ee,ie)*E.get(Q,X,V,J)}}A.set(D,R,I,j,X)}}}return r.makeTensorInfo(A.shape,A.dtype,A.values)}var hX={kernelName:Jf,backendName:"cpu",kernelFunc:pX};function cX(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:u,dimRoundingMode:d}=n;Te([a,s],"conv2dBackpropInput");let h=w.computeStrides(s.shape),p=w.computeStrides(a.shape),c=N.convertConv2DDataFormat(u),f=N.computeConv2DInfo(i,s.shape,o,1,l,d,!1,c),m=new sr(f.inShape,"float32"),g=m.values,y=r.data.get(a.dataId).values,A=r.data.get(s.dataId).values,[x,b,v]=h,{batchSize:S,filterHeight:T,filterWidth:E,inChannels:R,inHeight:_,inWidth:M,outChannels:I,outHeight:z,outWidth:O,strideHeight:j,strideWidth:X}=f;c=f.dataFormat;let D=T-1-f.padInfo.top,Q=E-1-f.padInfo.left,V=c==="channelsLast",ee=m.strides[0],J=V?m.strides[1]:m.strides[2],ie=V?m.strides[2]:1,Z=V?1:m.strides[1],ae=p[0],de=V?p[1]:p[2],Ae=V?p[2]:1,be=V?1:p[1];for(let Ee=0;Ee<S;++Ee)for(let Me=0;Me<R;++Me)for(let De=0;De<_;++De){let Be=De-D,Ze=Math.max(0,Math.ceil(Be/j)),ot=Math.min(z,(T+Be)/j);for(let dt=0;dt<M;++dt){let pt=dt-Q,$e=Math.max(0,Math.ceil(pt/X)),vt=Math.min(O,(E+pt)/X),yt=0;for(let pr=Ze;pr<ot;++pr){let Yr=pr*j-Be;for(let er=$e;er<vt;++er){let hr=er*X-pt,Qn=ae*Ee+de*pr+Ae*er,Jr=x*(T-1-Yr)+b*(E-1-hr)+v*Me;for(let tr=0;tr<I;++tr){let vn=y[Qn+be*tr],wn=A[Jr+tr];yt+=vn*wn}}}let $r=ee*Ee+J*De+ie*dt+Z*Me;g[$r]=yt}}return r.makeTensorInfo(m.shape,m.dtype,m.values)}var fX={kernelName:ti,backendName:"cpu",kernelFunc:cX};function mX(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dilations:l}=n;Te([a,s],"conv3d");let u=N.computeConv3DInfo(a.shape,s.shape,i,l,o),{filterDepth:d,filterHeight:h,filterWidth:p,dilationDepth:c,dilationHeight:f,dilationWidth:m,padInfo:g}=u,y=g.front,A=g.left,x=g.top,b=new sr(u.outShape,a.dtype),v=r.data.get(a.dataId).values,S=r.data.get(s.dataId).values,T=b.values,E=w.computeStrides(a.shape),R=w.computeStrides(s.shape);for(let _=0;_<u.batchSize;++_){let M=_*E[0],I=_*b.strides[0];for(let z=0;z<u.outDepth;++z){let O=I+z*b.strides[1],j=z*u.strideDepth-y;for(let X=0;X<d;++X){let D=j+X*c;if(D<0||D>=u.inDepth)continue;let Q=X*R[0],V=M+D*E[1];for(let ee=0;ee<u.outHeight;++ee){let J=O+ee*b.strides[2],ie=ee*u.strideHeight-x;for(let Z=0;Z<h;++Z){let ae=ie+Z*f;if(ae<0||ae>=u.inHeight)continue;let de=Q+Z*R[1],Ae=V+ae*E[2];for(let be=0;be<u.outWidth;++be){let Ee=J+be*u.outChannels,Me=be*u.strideWidth-A;for(let De=0;De<p;++De){let Be=Me+De*m;if(Be<0||Be>=u.inWidth)continue;let Ze=de+De*R[2],ot=Ae+Be*u.inChannels,dt=Ze;for(let pt=0;pt<u.inChannels;++pt){let $e=v[ot+pt];for(let vt=0;vt<u.outChannels;++vt)T[Ee+vt]+=$e*S[dt+vt];dt+=u.outChannels}}}}}}}}return r.makeTensorInfo(b.shape,b.dtype,b.values)}var gX={kernelName:Yp,backendName:"cpu",kernelFunc:mX};function yX(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,dy:s}=t,{strides:i,pad:o,filterShape:l}=n;Te([a,s],"conv3dBackpropFilterV2");let u=w.computeStrides(a.shape),d=w.computeStrides(s.shape),h=N.computeConv3DInfo(a.shape,l,i,1,o),p=h.strideDepth,c=h.strideHeight,f=h.strideWidth,m=h.filterDepth,g=h.filterHeight,y=h.filterWidth,A=new sr(h.filterShape,"float32"),x=A.values,[b,v,S,T]=A.strides,E=r.data.get(s.dataId).values,[R,_,M,I]=d,z=r.data.get(a.dataId).values,[O,j,X,D]=u,Q=h.padInfo.front,V=h.padInfo.left,ee=h.padInfo.top;for(let J=0;J<m;++J){let ie=Math.max(0,Math.ceil((Q-J)/p)),Z=Math.min(h.outDepth,(h.inDepth+Q-J)/p),ae=J*b;for(let de=0;de<g;++de){let Ae=Math.max(0,Math.ceil((ee-de)/c)),be=Math.min(h.outHeight,(h.inHeight+ee-de)/c),Ee=de*v+ae;for(let Me=0;Me<y;++Me){let De=Math.max(0,Math.ceil((V-Me)/f)),Be=Math.min(h.outWidth,(h.inWidth+V-Me)/f),Ze=Me*S+Ee;for(let ot=0;ot<h.inChannels;++ot){let dt=ot*T+Ze;for(let pt=0;pt<h.outChannels;++pt){let $e=0;for(let vt=0;vt<h.batchSize;++vt){let yt=vt*O,$r=vt*R;for(let pr=ie;pr<Z;++pr){let Yr=(J+pr*p-Q)*j+yt,er=pr*_+$r;for(let hr=Ae;hr<be;++hr){let Qn=(de+hr*c-ee)*X+Yr,Jr=hr*M+er;for(let tr=De;tr<Be;++tr){let vn=(Me+tr*f-V)*D+Qn,wn=tr*I+Jr;$e+=z[vn+ot]*E[wn+pt]}}}}x[dt+pt]=$e}}}}}return r.makeTensorInfo(A.shape,A.dtype,A.values)}var AX={kernelName:Qf,backendName:"cpu",kernelFunc:yX};function xX(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,filter:s}=t,{pad:i,strides:o,inputShape:l}=n;Te([a],"conv3dBackpropInputV2");let u=w.computeStrides(a.shape),d=w.computeStrides(s.shape),h=N.computeConv3DInfo(l,s.shape,o,1,i),p=new sr(h.inShape,"float32"),c=p.values,[f,m,g,y]=p.strides,A=r.data.get(a.dataId).values,[x,b,v,S]=u,T=r.data.get(s.dataId).values,[E,R,_,M]=d,{batchSize:I,filterDepth:z,filterHeight:O,filterWidth:j,inChannels:X,inDepth:D,inHeight:Q,inWidth:V,outChannels:ee,outDepth:J,outHeight:ie,outWidth:Z,strideDepth:ae,strideHeight:de,strideWidth:Ae}=h,be=z-1-h.padInfo.front,Ee=O-1-h.padInfo.top,Me=j-1-h.padInfo.left;for(let De=0;De<I;++De)for(let Be=0;Be<X;++Be)for(let Ze=0;Ze<D;++Ze){let ot=Ze-be,dt=Math.max(0,Math.ceil(ot/ae)),pt=Math.min(J,(z+ot)/ae);for(let $e=0;$e<Q;++$e){let vt=$e-Ee,yt=Math.max(0,Math.ceil(vt/de)),$r=Math.min(ie,(O+vt)/de);for(let pr=0;pr<V;++pr){let Yr=pr-Me,er=Math.max(0,Math.ceil(Yr/Ae)),hr=Math.min(Z,(j+Yr)/Ae),Qn=0;for(let Jr=dt;Jr<pt;++Jr){let tr=Jr*ae-ot;for(let vn=yt;vn<$r;++vn){let wn=vn*de-vt;for(let ms=er;ms<hr;++ms){let so=ms*Ae-Yr,ic=x*De+b*Jr+v*vn+S*ms,gs=E*(z-1-tr)+R*(O-1-wn)+_*(j-1-so)+M*Be;for(let Ua=0;Ua<ee;++Ua){let Qd=A[ic+Ua],ql=T[gs+Ua];Qn+=Qd*ql}}}}c[f*De+m*Ze+g*$e+y*pr+Be]=Qn}}}return r.makeTensorInfo(p.shape,p.dtype,p.values)}var bX={kernelName:em,backendName:"cpu",kernelFunc:xX},vX=mt(ri,e=>Math.cos(e)),wX={kernelName:ri,backendName:"cpu",kernelFunc:vX},kX=mt(ni,e=>Math.cosh(e)),IX={kernelName:ni,backendName:"cpu",kernelFunc:kX};function SX(e){let{inputs:t,backend:r,attrs:n}=e,{image:a,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=n,[d,h,p,c]=a.shape,f=s.shape[0],[m,g]=o,y=We([f,m,g,c],"float32"),A=r.data.get(s.dataId).values,x=r.data.get(i.dataId).values,b=r.data.get(a.dataId).values,v=w.computeStrides(a.shape),S=w.computeStrides(y.shape);for(let T=0;T<f;T++){let E=T*4,R=A[E],_=A[E+1],M=A[E+2],I=A[E+3],z=x[T];if(z>=d)continue;let O=m>1?(M-R)*(h-1)/(m-1):0,j=g>1?(I-_)*(p-1)/(g-1):0;for(let X=0;X<m;X++){let D=m>1?R*(h-1)+X*O:.5*(R+M)*(h-1);if(D<0||D>h-1){for(let Q=0;Q<g;Q++)for(let V=0;V<c;V++){let ee=V+Q*S[2]+X*S[1]+T*S[0];y.values[ee]=u}continue}if(l==="bilinear"){let Q=Math.floor(D),V=Math.ceil(D),ee=D-Q;for(let J=0;J<g;J++){let ie=g>1?_*(p-1)+J*j:.5*(_+I)*(p-1);if(ie<0||ie>p-1){for(let Ae=0;Ae<c;Ae++){let be=Ae+J*S[2]+X*S[1]+T*S[0];y.values[be]=u}continue}let Z=Math.floor(ie),ae=Math.ceil(ie),de=ie-Z;for(let Ae=0;Ae<c;Ae++){let be=Ae+Z*v[2]+Q*v[1]+z*v[0],Ee=b[be];be=Ae+ae*v[2]+Q*v[1]+z*v[0];let Me=b[be];be=Ae+Z*v[2]+V*v[1]+z*v[0];let De=b[be];be=Ae+ae*v[2]+V*v[1]+z*v[0];let Be=b[be],Ze=Ee+(Me-Ee)*de,ot=De+(Be-De)*de;be=Ae+J*S[2]+X*S[1]+T*S[0],y.values[be]=Ze+(ot-Ze)*ee}}}else for(let Q=0;Q<g;++Q){let V=g>1?_*(p-1)+Q*j:.5*(_+I)*(p-1);if(V<0||V>p-1){for(let ie=0;ie<c;ie++){let Z=ie+Q*S[2]+X*S[1]+T*S[0];y.values[Z]=u}continue}let ee=Math.round(V),J=Math.round(D);for(let ie=0;ie<c;ie++){let Z=ie+ee*v[2]+J*v[1]+z*v[0],ae=ie+Q*S[2]+X*S[1]+T*S[0];y.values[ae]=b[Z]}}}}return r.makeTensorInfo(y.shape,y.dtype,y.values)}var TX={kernelName:Ho,backendName:"cpu",kernelFunc:SX};function NX(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,exclusive:i,reverse:o}=n;Te(a,"cumprod");let l=N.getAxesPermutation([s],a.shape.length),u=a;l!=null&&(u=an({inputs:{x:a},backend:r,attrs:{perm:l}}));let d=N.getInnerMostAxes(1,a.shape.length)[0];if(d!==u.shape.length-1)throw new Error(`backend.cumprod in CPU expects an inner-most axis=${u.shape.length-1} but got axis=${d}`);let h=Cr(u.dtype,"int32"),p=w.makeOnesTypedArray(w.sizeFromShape(u.shape),h),c=r.data.get(u.dataId).values,f=u.shape[u.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)p[x]=i?1:c[x];else{let b=m(y,A-1);p[x]=i?c[b]*p[b]:c[x]*p[b]}}let g=r.makeTensorInfo(u.shape,h,p);if(l!=null){let y=N.getUndoAxesPermutation(l),A=an({inputs:{x:g},backend:r,attrs:{perm:y}});return r.disposeIntermediateTensorInfo(g),r.disposeIntermediateTensorInfo(u),A}return g}var CX={kernelName:jo,backendName:"cpu",kernelFunc:NX};function EX(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,exclusive:i,reverse:o}=n;Te(a,"cumsum");let l=N.getAxesPermutation([s],a.shape.length),u=a;l!=null&&(u=an({inputs:{x:a},backend:r,attrs:{perm:l}}));let d=N.getInnerMostAxes(1,a.shape.length)[0];if(d!==u.shape.length-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${u.shape.length-1} but got axis=${d}`);let h=Cr(u.dtype,"int32"),p=w.makeZerosTypedArray(w.sizeFromShape(u.shape),h),c=r.data.get(u.dataId).values,f=u.shape[u.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)p[x]=i?0:c[x];else{let b=m(y,A-1);p[x]=i?c[b]+p[b]:c[x]+p[b]}}let g=r.makeTensorInfo(u.shape,h,p);if(l!=null){let y=N.getUndoAxesPermutation(l),A=an({inputs:{x:g},backend:r,attrs:{perm:y}});return r.disposeIntermediateTensorInfo(g),r.disposeIntermediateTensorInfo(u),A}return g}var RX={kernelName:ai,backendName:"cpu",kernelFunc:EX};function MX(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,weights:s}=t,{size:i,binaryOutput:o}=n;if(a.shape.length===1){let l=r.data.get(a.dataId).values,u=r.data.get(s.dataId).values,d=Xx(l,u,s.dtype,s.shape,i);return r.makeTensorInfo([i],s.dtype,d)}else if(a.shape.length===2){let l=r.bufferSync(a),u=r.bufferSync(s),d=tI(l,u,i,o);return r.makeTensorInfo(d.shape,s.dtype,d.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${a.shape.length}.`)}var FX={kernelName:tm,backendName:"cpu",kernelFunc:MX};function $X(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockSize:s,dataFormat:i}=n;w.assert(i==="NHWC",()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${i}`);let o=a.shape[0],l=a.shape[1],u=a.shape[2],d=a.shape[3],h=l*s,p=u*s,c=d/(s*s),f=r.data.get(a.dataId).values,m=new Float32Array(o*h*p*c),g=0;for(let y=0;y<o;++y)for(let A=0;A<h;++A){let x=Math.floor(A/s),b=A%s;for(let v=0;v<p;++v){let S=Math.floor(v/s),T=v%s,E=(b*s+T)*c;for(let R=0;R<c;++R){let _=R+E+d*(S+u*(x+l*y));m[g++]=f[_]}}}return r.makeTensorInfo([o,h,p,c],a.dtype,m)}var PX={kernelName:qo,backendName:"cpu",kernelFunc:$X};function HI(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:u}=n;Te([a,s],"depthwiseConv2DNative");let d=w.computeStrides(a.shape),h=w.computeStrides(s.shape),p=l;p==null&&(p=[1,1]),w.assert(N.eitherStridesOrDilationsAreOne(i,p),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${p}'`);let c=N.computeConv2DInfo(a.shape,s.shape,i,p,o,u,!0),{filterHeight:f,filterWidth:m,dilationHeight:g,dilationWidth:y,padInfo:A}=c,x=A.left,b=A.top,v=c.outChannels/c.inChannels,S=new sr(c.outShape,a.dtype),T=r.data.get(a.dataId).values,E=r.data.get(s.dataId).values,R=S.values;for(let _=0;_<c.batchSize;++_){let M=_*d[0],I=_*S.strides[0];for(let z=0;z<c.outHeight;++z){let O=I+z*S.strides[1],j=z*c.strideHeight-b;for(let X=0;X<f;++X){let D=j+X*g;if(D<0||D>=c.inHeight)continue;let Q=X*h[0],V=M+D*d[1];for(let ee=0;ee<c.outWidth;++ee){let J=O+ee*S.strides[2],ie=ee*c.strideWidth-x;for(let Z=0;Z<m;++Z){let ae=ie+Z*y;if(ae<0||ae>=c.inWidth)continue;let de=Q+Z*h[1],Ae=V+ae*c.inChannels,be=J,Ee=de;for(let Me=0;Me<c.inChannels;++Me){let De=T[Ae+Me];for(let Be=0;Be<v;++Be)R[be+Be]+=De*E[Ee+Be];be+=v,Ee+=v}}}}}}return r.makeTensorInfo(S.shape,S.dtype,S.values)}var _X={kernelName:si,backendName:"cpu",kernelFunc:HI};function zX(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,dy:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,filterShape:d}=n;Te([a,s],"depthwiseConv2dNativeBackpropFilter");let h=N.computeConv2DInfo(a.shape,d,i,o,l,u,!0),{strideHeight:p,strideWidth:c,filterHeight:f,filterWidth:m}=h,g=new sr(h.filterShape,"float32"),y=h.padInfo.left,A=h.padInfo.top,x=h.outChannels/h.inChannels,b=r.data.get(a.dataId).values,v=new sr(a.shape,a.dtype,b),S=r.data.get(s.dataId).values,T=new sr(s.shape,s.dtype,S);for(let E=0;E<f;++E){let R=Math.max(0,Math.ceil((A-E)/p)),_=Math.min(h.outHeight,(h.inHeight+A-E)/p);for(let M=0;M<m;++M){let I=Math.max(0,Math.ceil((y-M)/c)),z=Math.min(h.outWidth,(h.inWidth+y-M)/c);for(let O=0;O<h.outChannels;++O){let j=Math.trunc(O/x),X=O%x,D=0;for(let Q=0;Q<h.batchSize;++Q)for(let V=R;V<_;++V){let ee=E+V*p-A;for(let J=I;J<z;++J){let ie=M+J*c-y;D+=v.get(Q,ee,ie,j)*T.get(Q,V,J,O)}}g.set(D,E,M,j,X)}}}return r.makeTensorInfo(g.shape,g.dtype,g.values)}var OX={kernelName:rm,backendName:"cpu",kernelFunc:zX};function DX(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,filter:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,inputShape:d}=n;Te([a,s],"depthwiseConv2DNativeBackpropInput");let h=w.computeStrides(a.shape),p=w.computeStrides(s.shape),c=N.computeConv2DInfo(d,s.shape,i,o,l,u,!0),f=new sr(c.inShape,"float32"),m=f.values,[g,y,A]=f.strides,x=r.data.get(a.dataId).values,[b,v,S]=h,T=r.data.get(s.dataId).values,[E,R,_]=p,{batchSize:M,filterHeight:I,filterWidth:z,inChannels:O,inHeight:j,inWidth:X,outChannels:D,outHeight:Q,outWidth:V,strideHeight:ee,strideWidth:J}=c,ie=I-1-c.padInfo.top,Z=z-1-c.padInfo.left,ae=D/O;for(let de=0;de<M;++de)for(let Ae=0;Ae<O;++Ae)for(let be=0;be<j;++be){let Ee=be-ie,Me=Math.max(0,Math.ceil(Ee/ee)),De=Math.min(Q,(I+Ee)/ee);for(let Be=0;Be<X;++Be){let Ze=Be-Z,ot=Math.max(0,Math.ceil(Ze/J)),dt=Math.min(V,(z+Ze)/J),pt=0;for(let $e=Me;$e<De;++$e){let vt=$e*ee-Ee;for(let yt=ot;yt<dt;++yt){let $r=yt*J-Ze,pr=b*de+v*$e+S*yt,Yr=E*(I-1-vt)+R*(z-1-$r)+_*Ae;for(let er=0;er<ae;++er){let hr=Ae*ae+er,Qn=x[pr+hr],Jr=T[Yr+er];pt+=Qn*Jr}}}m[g*de+y*be+A*Be+Ae]=pt}}return r.makeTensorInfo(f.shape,f.dtype,f.values)}var LX={kernelName:nm,backendName:"cpu",kernelFunc:DX};function BX(e){let{inputs:t,backend:r}=e,{x:n}=t,a=w.sizeFromShape(n.shape),s=r.data.get(n.dataId).values,i=We([a,a],n.dtype),o=i.values;for(let u=0;u<s.length;u++)o[u*a+u]=s[u];let l=[...n.shape,...n.shape];return r.makeTensorInfo(l,i.dtype,i.values)}var WX={kernelName:am,backendName:"cpu",kernelFunc:BX},VX={kernelName:Jp,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:r})=>{let{x:n,filter:a}=e,{strides:s,pad:i,dilations:o}=r,l=t,u=l.data.get(n.dataId).values,d=n.shape.length,h=l.data.get(a.dataId).values,p=a.shape.length,{batchSize:c,inHeight:f,inWidth:m,inChannels:g,outHeight:y,outWidth:A,padInfo:x,strideHeight:b,strideWidth:v,filterHeight:S,filterWidth:T,dilationHeight:E,dilationWidth:R,outShape:_}=N.computeDilation2DInfo(n.shape,a.shape,s,i,"NHWC",o),M=w.sizeFromShape(_),I=_.length,z=w.getArrayFromDType(n.dtype,M);for(let O=0;O<c;++O)for(let j=0;j<y;++j){let X=j*b-x.top;for(let D=0;D<A;++D){let Q=D*v-x.left;for(let V=0;V<g;++V){let ee=Number.MIN_SAFE_INTEGER;for(let ie=0;ie<S;++ie){let Z=X+ie*E;if(Z>=0&&Z<f)for(let ae=0;ae<T;++ae){let de=Q+ae*R;if(de>=0&&de<m){let Ae=w.locToIndex([O,Z,de,V],d,w.computeStrides(n.shape)),be=w.locToIndex([ie,ae,V],p,w.computeStrides(a.shape)),Ee=u[Ae]+h[be];Ee>ee&&(ee=Ee)}}}let J=w.locToIndex([O,j,D,V],I,w.computeStrides(_));z[J]=ee}}}return{dataId:l.write(w.toTypedArray(z,n.dtype),_,n.dtype),shape:_,dtype:n.dtype}}},UX={kernelName:gf,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:r})=>{let{x:n,filter:a,dy:s}=e,{strides:i,pad:o,dilations:l}=r,u=t,d=w.toNestedArray(n.shape,u.data.get(n.dataId).values),h=w.toNestedArray(a.shape,u.data.get(a.dataId).values),{batchSize:p,inHeight:c,inWidth:f,inChannels:m,outHeight:g,outWidth:y,padInfo:A,strideHeight:x,strideWidth:b,filterHeight:v,filterWidth:S,dilationHeight:T,dilationWidth:E,outShape:R}=N.computeDilation2DInfo(n.shape,a.shape,i,o,"NHWC",l);w.assert(s.rank===R.length,()=>`Error in ${gf}, dy must have the same rank as output ${R.length}, but got ${s.rank}`);let _=w.toNestedArray(R,u.data.get(s.dataId).values),M=w.makeZerosNestedTypedArray(a.shape,a.dtype);for(let I=0;I<p;++I)for(let z=0;z<g;++z){let O=z*x-A.top;for(let j=0;j<y;++j){let X=j*b-A.left;for(let D=0;D<m;++D){let Q=Number.MIN_SAFE_INTEGER,V=0,ee=0;for(let J=0;J<v;++J){let ie=O+J*T;if(ie>=0&&ie<c)for(let Z=0;Z<S;++Z){let ae=X+Z*E;if(ae>=0&&ae<f){let de=d[I][ie][ae][D]+h[J][Z][D];de>Q&&(Q=de,V=J,ee=Z)}}}M[V][ee][D]+=_[I][z][j][D]}}}return{dataId:u.write(w.toTypedArray(M,n.dtype),a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}},GX={kernelName:mf,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:r})=>{let{x:n,filter:a,dy:s}=e,{strides:i,pad:o,dilations:l}=r,u=t,d=w.toNestedArray(n.shape,u.data.get(n.dataId).values),h=w.toNestedArray(a.shape,u.data.get(a.dataId).values),{batchSize:p,inHeight:c,inWidth:f,inChannels:m,outHeight:g,outWidth:y,padInfo:A,strideHeight:x,strideWidth:b,filterHeight:v,filterWidth:S,dilationHeight:T,dilationWidth:E,outShape:R}=N.computeDilation2DInfo(n.shape,a.shape,i,o,"NHWC",l);w.assert(s.rank===R.length,()=>`Error in ${mf}, dy must have the same rank as output ${R.length}, but got ${s.rank}`);let _=w.toNestedArray(R,u.data.get(s.dataId).values),M=w.makeZerosNestedTypedArray(n.shape,n.dtype);for(let I=0;I<p;++I)for(let z=0;z<g;++z){let O=z*x-A.top;for(let j=0;j<y;++j){let X=j*b-A.left;for(let D=0;D<m;++D){let Q=Number.MIN_SAFE_INTEGER,V=O<0?0:O,ee=X<0?0:X;for(let J=0;J<v;++J){let ie=O+J*T;if(ie>=0&&ie<c)for(let Z=0;Z<S;++Z){let ae=X+Z*E;if(ae>=0&&ae<f){let de=d[I][ie][ae][D]+h[J][Z][D];de>Q&&(Q=de,V=ie,ee=ae)}}}M[I][V][ee][D]+=_[I][z][j][D]}}}return{dataId:u.write(w.toTypedArray(M,n.dtype),n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}};function Ph(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n;Te(a,"sum");let o;a.dtype==="bool"?o=js({inputs:{x:a},backend:r,attrs:{dtype:"int32"}}):o=$a({inputs:{x:a},backend:r});let l=o.shape.length,u=w.parseAxisParam(s,o.shape),d=N.getAxesPermutation(u,l),h=u,p=o;d!=null&&(p=an({inputs:{x:o},backend:r,attrs:{perm:d}}),h=N.getInnerMostAxes(h.length,l)),N.assertAxesAreInnerMostDims("sum",h,p.shape.length);let[c,f]=N.computeOutAndReduceShapes(p.shape,h),m=N.upcastType(p.dtype,"int32"),g=zf(r,c,m),y=w.sizeFromShape(f),A=r.data.get(g.dataId).values,x=r.data.get(p.dataId).values;for(let b=0;b<A.length;++b){let v=b*y,S=0;for(let T=0;T<y;++T)S+=x[v+T];A[b]=S}if(i){let b=N.expandShapeToKeepDim(g.shape,u),v=g;g=Mt({inputs:{x:g},backend:r,attrs:{shape:b}}),r.disposeIntermediateTensorInfo(v)}return r.disposeIntermediateTensorInfo(o),d!=null&&r.disposeIntermediateTensorInfo(p),g}var jX={kernelName:_i,backendName:"cpu",kernelFunc:Ph};function HX(e){let{inputs:t,backend:r,attrs:n}=e,{equation:a}=n,s=t,{allDims:i,summedDims:o,idDims:l}=N.decodeEinsumEquation(a,s.length);N.checkEinsumDimSizes(i.length,l,s);let{path:u,steps:d}=N.getEinsumComputePath(o,l),h=d.length,p=null,c=i.length,f=[];for(let m=0;m<h;++m){for(let g of d[m]){let{permutationIndices:y,expandDims:A}=N.getEinsumPermutation(c,l[g]),x;N.isIdentityPermutation(y)?x=s[g]:(x=an({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=Mt({inputs:{x},backend:r,attrs:{shape:b}}),f.push(x)),p===null?p=x:(p=y0({inputs:{a:x,b:p},backend:r}),f.push(p))}m<h-1&&(u[m]>=0&&(p=Ph({inputs:{x:p},backend:r,attrs:{axis:u[m]-(i.length-c),keepDims:!1}}),f.push(p)),c--)}for(let m of f)m!==p&&r.disposeIntermediateTensorInfo(m);return p}var qX={kernelName:Qp,backendName:"cpu",kernelFunc:HX};function KX(e){let{inputs:t,backend:r}=e,{dy:n,y:a}=t;Te([n,a],"eluGrad");let s=new Float32Array(w.sizeFromShape(a.shape)),i=r.data.get(a.dataId).values,o=r.data.get(n.dataId).values;for(let l=0;l<i.length;++l){let u=i[l];u>=1?s[l]=o[l]:s[l]=o[l]*(u+1)}return r.makeTensorInfo(a.shape,"float32",s)}var XX={kernelName:sm,backendName:"cpu",kernelFunc:KX},ZX=N.ERF_P,YX=N.ERF_A1,JX=N.ERF_A2,QX=N.ERF_A3,eZ=N.ERF_A4,tZ=N.ERF_A5,rZ=mt(ju,e=>{let t=Math.sign(e),r=Math.abs(e),n=1/(1+ZX*r);return t*(1-((((tZ*n+eZ)*n+QX)*n+JX)*n+YX)*n*Math.exp(-r*r))}),nZ={kernelName:ju,backendName:"cpu",kernelFunc:rZ};function Df(e){let{inputs:t,backend:r,attrs:n}=e,{input:a}=t,{dim:s}=n,i=a.shape.length,o=a.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),Mt({inputs:{x:a},backend:r,attrs:{shape:o}})}var aZ={kernelName:Xo,backendName:"cpu",kernelFunc:Df},sZ=Yt((e,t)=>e/t),ab=xr(ii,sZ),Hy={kernelName:ii,backendName:"cpu",kernelFunc:ab};function qI(e,t,r){let n=e.shape,a=n[0],s=n[1],i=r.data.get(e.dataId),o=i.complexTensorInfos.real,l=i.complexTensorInfos.imag,u=[a,s],d=w.sizeFromShape(u),h=w.getTypedArrayFromDType("float32",d),p=w.getTypedArrayFromDType("float32",d);for(let g=0;g<a;g++){let y=zo({inputs:{x:o},backend:r,attrs:{begin:[g,0],size:[1,s]}}),A=zo({inputs:{x:l},backend:r,attrs:{begin:[g,0],size:[1,s]}}),x=pn({inputs:{real:y,imag:A},backend:r}),{real:b,imag:v}=iZ(x,t,r),S=N.mergeRealAndImagArrays(b,v);for(let T=0;T<s;T++){let E=N.getComplexWithIndex(S,T);h[g*s+T]=E.real,p[g*s+T]=E.imag}r.disposeIntermediateTensorInfo(y),r.disposeIntermediateTensorInfo(A),r.disposeIntermediateTensorInfo(x)}let c=r.makeTensorInfo(u,"float32",h),f=r.makeTensorInfo(u,"float32",p),m=pn({inputs:{real:c,imag:f},backend:r});return r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(f),m}function iZ(e,t,r){let n=w.sizeFromShape(e.shape),a=r.data.get(e.dataId),s=r.data.get(a.complexTensorInfos.real.dataId).values,i=r.data.get(a.complexTensorInfos.imag.dataId).values;if(oZ(n)){let o=qy(s,i,n,t,r),l=[e.shape[0],e.shape[1]];if(t){let u=r.makeTensorInfo(l,"float32",o.real),d=r.makeTensorInfo(l,"float32",o.imag),h=r.makeTensorInfo([],"float32",w.createScalarValue(n,"float32")),p=$a({inputs:{x:h},backend:r}),c=Hy.kernelFunc({inputs:{a:u,b:h},backend:r}),f=Hy.kernelFunc({inputs:{a:d,b:p},backend:r}),m=r.data.get(c.dataId).values,g=r.data.get(f.dataId).values;return r.disposeIntermediateTensorInfo(u),r.disposeIntermediateTensorInfo(d),r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(f),{real:m,imag:g}}return o}else{let o=N.mergeRealAndImagArrays(s,i),l=lZ(o,n,t);return N.splitRealAndImagArrays(l)}}function oZ(e){return(e&e-1)===0}function qy(e,t,r,n,a){if(r===1)return{real:e,imag:t};let s=N.mergeRealAndImagArrays(e,t),i=r/2,o=N.complexWithEvenIndex(s),l=o.real,u=o.imag,d=[l.length],h=a.makeTensorInfo(d,"float32",l),p=a.makeTensorInfo(d,"float32",u),c=pn({inputs:{real:h,imag:p},backend:a}),f=N.complexWithOddIndex(s),m=f.real,g=f.imag,y=[m.length],A=a.makeTensorInfo(y,"float32",m),x=a.makeTensorInfo(y,"float32",g),b=pn({inputs:{real:A,imag:x},backend:a}),v=qy(l,u,i,n,a),S=v.real,T=v.imag,E=[S.length],R=a.makeTensorInfo(E,"float32",S),_=a.makeTensorInfo(E,"float32",T),M=pn({inputs:{real:R,imag:_},backend:a}),I=qy(m,g,i,n,a),z=I.real,O=I.imag,j=[z.length],X=a.makeTensorInfo(j,"float32",z),D=a.makeTensorInfo(j,"float32",O),Q=pn({inputs:{real:X,imag:D},backend:a}),V=N.exponents(r,n),ee=[V.real.length],J=a.makeTensorInfo(ee,"float32",V.real),ie=a.makeTensorInfo(ee,"float32",V.imag),Z=pn({inputs:{real:J,imag:ie},backend:a}),ae=y0({inputs:{a:Z,b:Q},backend:a}),de=$h({inputs:{a:M,b:ae},backend:a}),Ae=tb({inputs:{a:M,b:ae},backend:a}),be=_o({inputs:{input:de},backend:a}),Ee=_o({inputs:{input:Ae},backend:a}),Me=Ru({inputs:{input:de},backend:a}),De=Ru({inputs:{input:Ae},backend:a}),Be=Mu({inputs:[be,Ee],backend:a,attrs:{axis:0}}),Ze=Mu({inputs:[Me,De],backend:a,attrs:{axis:0}}),ot=a.data.get(Be.dataId).values,dt=a.data.get(Ze.dataId).values;return a.disposeIntermediateTensorInfo(h),a.disposeIntermediateTensorInfo(p),a.disposeIntermediateTensorInfo(c),a.disposeIntermediateTensorInfo(A),a.disposeIntermediateTensorInfo(x),a.disposeIntermediateTensorInfo(b),a.disposeIntermediateTensorInfo(R),a.disposeIntermediateTensorInfo(_),a.disposeIntermediateTensorInfo(M),a.disposeIntermediateTensorInfo(X),a.disposeIntermediateTensorInfo(D),a.disposeIntermediateTensorInfo(Q),a.disposeIntermediateTensorInfo(J),a.disposeIntermediateTensorInfo(ie),a.disposeIntermediateTensorInfo(Z),a.disposeIntermediateTensorInfo(ae),a.disposeIntermediateTensorInfo(de),a.disposeIntermediateTensorInfo(Ae),a.disposeIntermediateTensorInfo(be),a.disposeIntermediateTensorInfo(Me),a.disposeIntermediateTensorInfo(Ee),a.disposeIntermediateTensorInfo(De),a.disposeIntermediateTensorInfo(Be),a.disposeIntermediateTensorInfo(Ze),{real:ot,imag:dt}}function lZ(e,t,r){let n=new Float32Array(t*2);for(let a=0;a<t;a++){let s=0,i=0;for(let o=0;o<t;o++){let l=N.exponent(a*o,t,r),u=N.getComplexWithIndex(e,o);s+=u.real*l.real-u.imag*l.imag,i+=u.real*l.imag+u.imag*l.real}r&&(s/=t,i/=t),N.assignToTypedArray(n,s,i,a)}return n}function uZ(e){let{inputs:t,backend:r}=e,{input:n}=t,a=w.sizeFromShape(n.shape),s=n.shape[n.shape.length-1],i=a/s,o=Mt({inputs:{x:n},backend:r,attrs:{shape:[i,s]}}),l=qI(o,!1,r),u=Mt({inputs:{x:l},backend:r,attrs:{shape:n.shape}});return r.disposeIntermediateTensorInfo(o),r.disposeIntermediateTensorInfo(l),u}var dZ={kernelName:im,backendName:"cpu",kernelFunc:uZ};function sb(e){let{backend:t,attrs:r}=e,{shape:n,value:a,dtype:s}=r,i=s||w.inferDtype(a),o=w.getArrayFromDType(i,w.sizeFromShape(n));return hZ(o,a,i),t.makeTensorInfo(n,i,o)}var pZ={kernelName:Hu,backendName:"cpu",kernelFunc:sb};function hZ(e,t,r){e.fill(t)}var cZ={kernelName:Yo,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{image:n}=e,a=r,s=w.getTypedArrayFromDType(n.dtype,w.sizeFromShape(n.shape)),[i,o,l,u]=n.shape,d=a.data.get(n.dataId).values;for(let h=0;h<i;h++){let p=h*l*o*u;for(let c=0;c<o;c++){let f=c*(l*u);for(let m=0;m<l;m++){let g=m*u;for(let y=0;y<u;y++){let A=Math.round(l-m-1),x=p+f+g+y,b=d[x];if(A>=0&&A<l){let v=A*u,S=p+f+v+y;b=d[S]}s[x]=b}}}}return{dataId:a.write(s,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},fZ=Yt((e,t)=>Math.floor(e/t)),mZ=xr(di,fZ,null,"int32"),gZ={kernelName:di,backendName:"cpu",kernelFunc:mZ};function yZ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:d,dilations:h,dimRoundingMode:p,activation:c,leakyreluAlpha:f}=n,m=jI({inputs:{x:a,filter:s},backend:r,attrs:{strides:l,pad:u,dataFormat:d,dilations:h,dimRoundingMode:p}});if(i){let g=m;m=$h({inputs:{a:m,b:i},backend:r}),r.disposeIntermediateTensorInfo(g)}if(c){let g=m;m=rb(r,m,c,o,f),r.disposeIntermediateTensorInfo(g)}return m}var AZ={kernelName:$s,backendName:"cpu",kernelFunc:yZ};function xZ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:d,dilations:h,dimRoundingMode:p,activation:c,leakyreluAlpha:f}=n,m=HI({inputs:{x:a,filter:s},backend:r,attrs:{strides:l,pad:u,dataFormat:d,dilations:h,dimRoundingMode:p}});if(i){let g=m;m=$h({inputs:{a:m,b:i},backend:r}),r.disposeIntermediateTensorInfo(g)}if(c){let g=m;m=rb(r,m,c,o,f),r.disposeIntermediateTensorInfo(g)}return m}var bZ={kernelName:Ps,backendName:"cpu",kernelFunc:xZ};function vZ(e){let{inputs:t,backend:r}=e,{params:n,indices:a}=t,s=w.sizeFromShape(n.shape),i=a.shape,o=i[i.length-1],[l,u,d,h]=N.prepareAndValidate(n,a);if(u===0)return r.makeTensorInfo(l,n.dtype,[]);let p=r.data.get(a.dataId).values,c=r.bufferSync(n),f=uI(p,c,n.dtype,u,o,d,h,n.shape,s);return r.makeTensorInfo(l,n.dtype,f.values)}var wZ={kernelName:Qo,backendName:"cpu",kernelFunc:vZ};function kZ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,indices:s}=t,{axis:i,batchDims:o}=n;Te([a,s],"gatherV2");let l=w.parseAxisParam(i,a.shape)[0],u=r.data.get(s.dataId).values,d=a.shape[l];for(let b=0;b<u.length;++b){let v=u[b];w.assert(v<=d-1&&v>=0,()=>`GatherV2: the index value ${v} is not in [0, ${d-1}]`)}let h=o;o==null&&(h=0);let p=w.sizeFromShape(s.shape),c=N.segment_util.collectGatherOpShapeInfo(a,s,l,h),f=Mt({inputs:{x:a},backend:r,attrs:{shape:[c.batchSize,c.outerSize,c.dimSize,c.sliceSize]}}),m=Mt({inputs:{x:s},backend:r,attrs:{shape:[c.batchSize,p/c.batchSize]}}),g=[c.batchSize,c.outerSize,p/c.batchSize,c.sliceSize],y=r.bufferSync(m),A=r.bufferSync(f),x=dI(A,y,g);return r.disposeIntermediateTensorInfo(f),r.disposeIntermediateTensorInfo(m),r.makeTensorInfo(c.outputShape,x.dtype,x.values)}var IZ={kernelName:Jo,backendName:"cpu",kernelFunc:kZ};function SZ(e){let{inputs:t,backend:r}=e,{input:n}=t,a=w.sizeFromShape(n.shape),s=n.shape[n.shape.length-1],i=a/s,o=Mt({inputs:{x:n},backend:r,attrs:{shape:[i,s]}}),l=qI(o,!0,r),u=Mt({inputs:{x:l},backend:r,attrs:{shape:n.shape}});return r.disposeIntermediateTensorInfo(o),r.disposeIntermediateTensorInfo(l),u}var TZ={kernelName:om,backendName:"cpu",kernelFunc:SZ},NZ=mt(qu,e=>Number.isFinite(e)?1:0,"bool"),CZ={kernelName:qu,backendName:"cpu",kernelFunc:NZ},EZ=mt(Ku,e=>Math.abs(e)===1/0?1:0,"bool"),RZ={kernelName:Ku,backendName:"cpu",kernelFunc:EZ},MZ=mt(Xu,e=>Number.isNaN(e)?1:0,"bool"),FZ={kernelName:Xu,backendName:"cpu",kernelFunc:MZ};function $Z(e){let{backend:t,attrs:r}=e,{start:n,stop:a,num:s}=r,i=mI(n,a,s);return t.makeTensorInfo([i.length],"float32",i)}var PZ={kernelName:lm,backendName:"cpu",kernelFunc:$Z},_Z=mt(Zu,e=>Math.log1p(e)),zZ={kernelName:Zu,backendName:"cpu",kernelFunc:_Z},OZ=Yt((e,t)=>e&&t),DZ=xr(nl,OZ,null,"bool"),LZ={kernelName:nl,backendName:"cpu",kernelFunc:DZ},BZ=mt(Yu,e=>e?0:1,"bool"),WZ={kernelName:Yu,backendName:"cpu",kernelFunc:BZ},VZ=Yt((e,t)=>e||t),UZ=xr(th,VZ,null,"bool"),GZ={kernelName:th,backendName:"cpu",kernelFunc:UZ};function jZ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=n;Te(a,"LRN");let u=a.shape[3],d=u-1,h=r.data.get(a.dataId).values,p=w.sizeFromShape(a.shape),c=new Float32Array(p);function f(m){let g=m%u,y=m-g+Math.max(0,g-s),A=m-g+Math.min(g+s,d),x=0;for(;y<=A;y++){let b=h[y];x+=b*b}return x}for(let m=0;m<p;m++){let g=f(m),y=h[m]*Math.pow(i+o*g,-l);c[m]=y}return r.makeTensorInfo(a.shape,a.dtype,c)}var HZ={kernelName:rh,backendName:"cpu",kernelFunc:jZ};function qZ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,y:s,dy:i}=t,{depthRadius:o,bias:l,alpha:u,beta:d}=n;Te(i,"LRNGrad");let h=w.sizeFromShape(i.shape),p=i.shape[3],c=r.data.get(i.dataId).values,f=r.data.get(a.dataId).values,m=r.data.get(s.dataId).values,g=new Float32Array(h),y=h;for(let A=0;A<y;A++){let x=A%p,b=A-x+Math.max(0,x-o),v=A-x+Math.min(p,x+o+1),S=0;for(let T=b;T<v;T++)S+=Math.pow(f[T],2);S=u*S+l;for(let T=b;T<v;T++){let E=-2*u*d*f[T]*m[A]/S;A===T&&(E+=Math.pow(S,-d)),E*=c[A],g[T]+=E}}return r.makeTensorInfo(i.shape,a.dtype,g)}var KZ={kernelName:um,backendName:"cpu",kernelFunc:qZ};function KI(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{reductionIndices:s,keepDims:i}=n,o=r,l=a.shape,u=l.length,d=w.parseAxisParam(s,l),h=d,p=N.getAxesPermutation(h,u),c=o.data.get(a.dataId).values;if(p!=null){let b=new Array(u);for(let v=0;v<b.length;v++)b[v]=l[p[v]];c=Jx(c,l,a.dtype,p,b),h=N.getInnerMostAxes(h.length,u),l=b}Te(a,"max"),N.assertAxesAreInnerMostDims("max",h,u);let[f,m]=N.computeOutAndReduceShapes(l,h),g=w.sizeFromShape(m),y=yI(c,g,f,a.dtype),A=o.write(y,f,a.dtype),x=f;return i&&(x=N.expandShapeToKeepDim(f,d)),{dataId:A,shape:x,dtype:a.dtype}}var XZ={kernelName:gi,backendName:"cpu",kernelFunc:KI};function ZZ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t;Te(a,"maxPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,u=1;w.assert(N.eitherStridesOrDilationsAreOne(i,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let d=N.computePool2DInfo(a.shape,s,i,u,o,l),h;if(d.filterWidth===1&&d.filterHeight===1&&w.arraysEqual(d.inShape,d.outShape))h=$a({inputs:{x:a},backend:r});else{let p=r.data.get(a.dataId).values,c=w.computeStrides(a.shape),f=nb(p,a.shape,a.dtype,c,d,"max");h=r.makeTensorInfo(d.outShape,a.dtype,f.values)}return h}var YZ={kernelName:Ai,backendName:"cpu",kernelFunc:ZZ};function JZ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=n;Te(a,"maxPool3d");let d=N.computePool3DInfo(a.shape,s,i,1,o,l,u),h=r.data.get(a.dataId).values,p=GI(h,a.shape,a.dtype,w.computeStrides(a.shape),d,"max");return r.makeTensorInfo(p.shape,"float32",p.values)}var QZ={kernelName:nh,backendName:"cpu",kernelFunc:JZ};function eY(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=n;Te([a,s],"maxPool3DGrad");let d=N.computePool3DInfo(s.shape,i,o,1,l,u),h=r.bufferSync(s),p=WK(h,d),c=d.strideDepth,f=d.strideHeight,m=d.strideWidth,g=d.dilationDepth,y=d.dilationHeight,A=d.dilationWidth,x=d.effectiveFilterDepth,b=d.effectiveFilterHeight,v=d.effectiveFilterWidth,S=x-1-d.padInfo.front,T=v-1-d.padInfo.left,E=b-1-d.padInfo.top,R=We(s.shape,"float32"),_=r.bufferSync(a);for(let M=0;M<d.batchSize;++M)for(let I=0;I<d.inChannels;++I)for(let z=0;z<d.inDepth;++z)for(let O=0;O<d.inHeight;++O)for(let j=0;j<d.inWidth;++j){let X=z-S,D=O-E,Q=j-T,V=0;for(let ee=0;ee<x;ee+=g){let J=(X+ee)/c;if(!(J<0||J>=d.outDepth||Math.floor(J)!==J))for(let ie=0;ie<b;ie+=y){let Z=(D+ie)/f;if(!(Z<0||Z>=d.outHeight||Math.floor(Z)!==Z))for(let ae=0;ae<v;ae+=A){let de=(Q+ae)/m;if(de<0||de>=d.outWidth||Math.floor(de)!==de)continue;let Ae=x*b*v-1-p.get(M,J,Z,de,I),be=ee*b*v+ie*v+ae,Ee=Ae===be?1:0;Ee!==0&&(V+=_.get(M,J,Z,de,I)*Ee)}}}R.set(V,M,z,O,j,I)}return r.makeTensorInfo(R.shape,R.dtype,R.values)}var tY={kernelName:pm,backendName:"cpu",kernelFunc:eY};function rY(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s,output:i}=t,o=s;Te([s,i],"maxPoolGrad");let{filterSize:l,strides:u,pad:d,dimRoundingMode:h}=n,p=N.computePool2DInfo(o.shape,l,u,1,d,h),c=r.data.get(o.dataId).values,f=We(p.outShape,o.dtype,UI(c,o.shape,o.dtype,p).values),m=p.strideHeight,g=p.strideWidth,y=p.dilationHeight,A=p.dilationWidth,x=p.effectiveFilterHeight,b=p.effectiveFilterWidth,v=b-1-p.padInfo.left,S=x-1-p.padInfo.top,T=We(o.shape,"float32"),E=r.data.get(a.dataId).values,R=We(a.shape,"float32",E);for(let _=0;_<p.batchSize;++_)for(let M=0;M<p.inChannels;++M)for(let I=0;I<p.inHeight;++I)for(let z=0;z<p.inWidth;++z){let O=I-S,j=z-v,X=0;for(let D=0;D<x;D+=y){let Q=(O+D)/m;if(!(Q<0||Q>=p.outHeight||Math.floor(Q)!==Q))for(let V=0;V<b;V+=A){let ee=(j+V)/g;if(ee<0||ee>=p.outWidth||Math.floor(ee)!==ee)continue;let J=x*b-1-f.get(_,Q,ee,M),ie=D*b+V,Z=J===ie?1:0;Z!==0&&(X+=R.get(_,Q,ee,M)*Z)}}T.set(X,_,I,z,M)}return r.makeTensorInfo(T.shape,T.dtype,T.values)}var nY={kernelName:dm,backendName:"cpu",kernelFunc:rY};function aY(e,t,r,n,a){let s=w.computeStrides(t),i=nb(e,t,r,s,a,"max"),o=UI(e,t,r,a,!0,n);return[i.values,o.values]}var sY={kernelName:hm,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{x:n}=e,{filterSize:a,strides:s,pad:i,includeBatchInIndex:o}=t,l=r;Te(n,"MaxPoolWithArgmax");let u=l.data.get(n.dataId).values,d=N.computePool2DInfo(n.shape,a,s,[1,1],i),[h,p]=aY(u,n.shape,n.dtype,o,d),c=l.write(h,d.outShape,n.dtype),f=l.write(p,d.outShape,n.dtype);return[{dataId:c,shape:d.outShape,dtype:n.dtype},{dataId:f,shape:d.outShape,dtype:"int32"}]}};function iY(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n,o=w.parseAxisParam(s,a.shape),l=N.computeOutAndReduceShapes(a.shape,o)[1],u=w.sizeFromShape(l),d=[],h=r.makeTensorInfo([],"float32",new Float32Array([u]));d.push(h);let p=js({inputs:{x:a},backend:r,attrs:{dtype:"float32"}});d.push(p);let c=ab({inputs:{a:p,b:h},backend:r});d.push(c);let f=Ph({inputs:{x:c},backend:r,attrs:{axis:s,keepDims:i}});return d.forEach(m=>r.disposeIntermediateTensorInfo(m)),f}var oY={kernelName:xi,backendName:"cpu",kernelFunc:iY};function lY(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n;Te(a,"min");let o=w.parseAxisParam(s,a.shape),l=o,u=N.getAxesPermutation(l,a.shape.length),d=a;u!=null&&(d=an({inputs:{x:a},backend:r,attrs:{perm:u}}),l=N.getInnerMostAxes(l.length,a.shape.length)),N.assertAxesAreInnerMostDims("min",l,d.shape.length);let[h,p]=N.computeOutAndReduceShapes(d.shape,l),c=w.sizeFromShape(p),f=w.makeZerosTypedArray(w.sizeFromShape(h),d.dtype),m=r.data.get(d.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}u!=null&&r.disposeIntermediateTensorInfo(d);let g=r.makeTensorInfo(h,d.dtype,f);if(i){let y=N.expandShapeToKeepDim(h,o),A=Mt({inputs:{x:g},backend:r,attrs:{shape:y}});return r.disposeIntermediateTensorInfo(g),A}return g}var uY={kernelName:bi,backendName:"cpu",kernelFunc:lY};function dY(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{paddings:s,mode:i}=n;Te(a,"mirrorPad");let o=s.map((A,x)=>A[0]+a.shape[x]+A[1]),l=s.map(A=>A[0]),u=s.map((A,x)=>A[0]+a.shape[x]),d=i==="reflect"?0:1,h=r.data.get(a.dataId).values,p=a.shape.length,c=w.computeStrides(a.shape),f=w.sizeFromShape(o),m=o.length,g=w.computeStrides(o),y=w.getTypedArrayFromDType(a.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]-d:x[v]>=u[v]&&(x[v]=(u[v]-1)*2-x[v]+d);x=x.map((v,S)=>v-l[S]);let b=w.locToIndex(x,p,c);y[A]=h[b]}return{dataId:r.write(y,o,a.dtype),shape:o,dtype:a.dtype}}var pY={kernelName:wi,backendName:"cpu",kernelFunc:dY},hY=Yt((e,t)=>{let r=e%t;return e<0&&t<0||e>=0&&t>=0?r:(r+t)%t}),cY=xr(Ju,hY),fY={kernelName:Ju,backendName:"cpu",kernelFunc:cY},mY=Bo(jf());function XI(e){let{inputs:t,backend:r,attrs:n}=e,{logits:a}=t,{dim:s}=n,i=a.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],a.shape),u=KI({inputs:{x:a},backend:r,attrs:{reductionIndices:l,keepDims:!1}}),d=N.expandShapeToKeepDim(u.shape,l),h=Mt({inputs:{x:u},backend:r,attrs:{shape:d}}),p=tb({inputs:{a,b:h},backend:r}),c=iI({inputs:{x:p},backend:r}),f=Ph({inputs:{x:c},backend:r,attrs:{axis:l,keepDims:!1}}),m=Mt({inputs:{x:f},backend:r,attrs:{shape:d}}),g=ab({inputs:{a:c,b:m},backend:r});return r.disposeIntermediateTensorInfo(u),r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(f),r.disposeIntermediateTensorInfo(m),g}var gY={kernelName:zi,backendName:"cpu",kernelFunc:XI};function yY(e){let{inputs:t,backend:r,attrs:n}=e,{logits:a}=t,{numSamples:s,seed:i,normalized:o}=n;Te(a,"multinomial");let l=o?a:XI({inputs:{logits:a},backend:r,attrs:{dim:-1}}),u=l.shape[0],d=l.shape[1],h=r.data.get(l.dataId).values,p=[u,s],c=w.makeZerosTypedArray(w.sizeFromShape(p),"int32");for(let f=0;f<u;++f){let m=f*d,g=new Float32Array(d-1);g[0]=h[m];for(let x=1;x<g.length;++x)g[x]=g[x-1]+h[m+x];let y=mY.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(p,"int32",c)}var AY={kernelName:cm,backendName:"cpu",kernelFunc:yY},xY=qn.nonMaxSuppressionV3Impl;function bY(e){let{inputs:t,backend:r,attrs:n}=e,{boxes:a,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=n;Te(a,"NonMaxSuppression");let u=r.data.get(a.dataId).values,d=r.data.get(s.dataId).values,{selectedIndices:h}=xY(u,d,i,o,l);return r.makeTensorInfo([h.length],"int32",new Int32Array(h))}var vY={kernelName:il,backendName:"cpu",kernelFunc:bY},wY=qn.nonMaxSuppressionV4Impl;function kY(e){let{inputs:t,backend:r,attrs:n}=e,{boxes:a,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:u}=n;Te(a,"NonMaxSuppressionPadded");let d=r.data.get(a.dataId).values,h=r.data.get(s.dataId).values,{selectedIndices:p,validOutputs:c}=wY(d,h,i,o,l,u);return[r.makeTensorInfo([p.length],"int32",new Int32Array(p)),r.makeTensorInfo([],"int32",new Int32Array([c]))]}var IY={kernelName:Qu,backendName:"cpu",kernelFunc:kY},SY=qn.nonMaxSuppressionV5Impl;function TY(e){let{inputs:t,backend:r,attrs:n}=e,{boxes:a,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=n;Te(a,"NonMaxSuppressionWithScore");let d=r.data.get(a.dataId).values,h=r.data.get(s.dataId).values,p=i,c=o,f=l,m=u,{selectedIndices:g,selectedScores:y}=SY(d,h,p,c,f,m);return[r.makeTensorInfo([g.length],"int32",new Int32Array(g)),r.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var NY={kernelName:ol,backendName:"cpu",kernelFunc:TY};function CY(e){let{inputs:t,backend:r,attrs:n}=e,{indices:a}=t,{depth:s,onValue:i,offValue:o}=n;Te(a,"oneHot");let l=w.sizeFromShape(a.shape),u=new Float32Array(l*s);u.fill(o);let d=r.data.get(a.dataId).values;for(let h=0;h<l;++h)d[h]>=0&&d[h]<s&&(u[h*s+d[h]]=i);return r.makeTensorInfo([...a.shape,s],"int32",u)}var EY={kernelName:ul,backendName:"cpu",kernelFunc:CY};function Lf(e){let{inputs:t,backend:r}=e,{x:n}=t;if(n.dtype==="string")throw new Error("zerosLike is not supported for string tensors");if(n.dtype==="complex64"){let a=_o({inputs:{input:n},backend:r}),s=Lf({inputs:{x:a},backend:r}),i=Ru({inputs:{input:n},backend:r}),o=Lf({inputs:{x:i},backend:r}),l=pn({inputs:{real:s,imag:o},backend:r});return r.disposeIntermediateTensorInfo(a),r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(o),l}else return sb({backend:r,attrs:{shape:n.shape,value:0,dtype:n.dtype}})}var RY={kernelName:Sl,backendName:"cpu",kernelFunc:Lf};function ZI(e){let{inputs:t,backend:r}=e,{x:n}=t;if(n.dtype==="string")throw new Error("onesLike is not supported for string tensors");if(n.dtype==="complex64"){let a=_o({inputs:{input:n},backend:r}),s=ZI({inputs:{x:a},backend:r}),i=Ru({inputs:{input:n},backend:r}),o=Lf({inputs:{x:i},backend:r}),l=pn({inputs:{real:s,imag:o},backend:r});return r.disposeIntermediateTensorInfo(a),r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(o),l}else return sb({backend:r,attrs:{shape:n.shape,value:1,dtype:n.dtype}})}var MY={kernelName:ll,backendName:"cpu",kernelFunc:ZI};function YI(e){let{inputs:t,backend:r,attrs:n}=e,{axis:a}=n;if(t.length===1)return Df({inputs:{input:t[0]},backend:r,attrs:{dim:a}});let s=t[0].shape,i=t[0].dtype;t.forEach(d=>{w.assertShapesMatch(s,d.shape,"All tensors passed to stack must have matching shapes"),w.assert(i===d.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(d=>{let h=Df({inputs:{input:d},backend:r,attrs:{dim:a}});return o.push(h),h}),u=Mu({inputs:l,backend:r,attrs:{axis:a}});return o.forEach(d=>r.disposeIntermediateTensorInfo(d)),u}var FY={kernelName:dl,backendName:"cpu",kernelFunc:YI};function $Y(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{paddings:s,constantValue:i}=n;Te(a,"pad");let o=s.map((y,A)=>y[0]+a.shape[A]+y[1]),l=s.map(y=>y[0]),u=r.data.get(a.dataId).values,d=w.sizeFromShape(a.shape),h=a.shape.length,p=w.computeStrides(a.shape),c=w.sizeFromShape(o),f=o.length,m=w.computeStrides(o),g=w.getTypedArrayFromDType(a.dtype,c);i!==0&&g.fill(i);for(let y=0;y<d;y++){let A=w.indexToLoc(y,h,p).map((b,v)=>b+l[v]),x=w.locToIndex(A,f,m);g[x]=u[y]}return{dataId:r.write(g,o,a.dtype),shape:o,dtype:a.dtype}}var JI={kernelName:Ii,backendName:"cpu",kernelFunc:$Y},PY=Yt((e,t)=>Math.pow(e,t)),_Y=xr(Si,PY),zY={kernelName:Si,backendName:"cpu",kernelFunc:_Y};function OY(e){let{backend:t,attrs:r}=e,{start:n,stop:a,dtype:s,step:i}=r,o=Qx(n,a,i,s);return t.makeTensorInfo([o.length],s,o)}var DY={kernelName:ed,backendName:"cpu",kernelFunc:OY},LY=mt(td,e=>1/e),BY={kernelName:td,backendName:"cpu",kernelFunc:LY};function WY(e){let{inputs:t,backend:r,attrs:n}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:i,size:o}=n;Te(a,"resizeBilinear");let l=w.computeStrides(a.shape),[u,d]=o,[h,p,c,f]=a.shape,m=r.data.get(a.dataId).values,g=new Float32Array(w.sizeFromShape([h,u,d,f])),y=[s&&u>1?p-1:p,s&&d>1?c-1:c],A=[s&&u>1?u-1:u,s&&d>1?d-1:d],x=0,b=y[0]/A[0],v=y[1]/A[1];for(let S=0;S<h;S++)for(let T=0;T<u;T++){let E;i?E=b*(T+.5)-.5:E=b*T;let R=Math.max(0,Math.floor(E)),_=E-R,M=Math.min(p-1,Math.ceil(E)),I=S*l[0]+R*l[1],z=S*l[0]+M*l[1];for(let O=0;O<d;O++){let j;i?j=v*(O+.5)-.5:j=v*O;let X=Math.max(0,Math.floor(j)),D=j-X,Q=Math.min(c-1,Math.ceil(j)),V=I+X*l[2],ee=z+X*l[2],J=I+Q*l[2],ie=z+Q*l[2];for(let Z=0;Z<f;Z++){let ae=m[V+Z],de=m[ee+Z],Ae=m[J+Z],be=m[ie+Z],Ee=ae+(Ae-ae)*D,Me=de+(be-de)*D,De=Ee+(Me-Ee)*_;g[x++]=De}}}return r.makeTensorInfo([h,u,d,f],"float32",g)}var VY={kernelName:Ei,backendName:"cpu",kernelFunc:WY};function UY(e){let{inputs:t,backend:r,attrs:n}=e,{images:a,dy:s}=t,{alignCorners:i}=n;Te([s,a],"resizeBilinearGrad");let o=w.computeStrides(a.shape),[l,u,d,h]=a.shape,[,p,c]=s.shape,f=new Float32Array(l*u*d*h),m=[i&&p>1?u-1:u,i&&c>1?d-1:d],g=[i&&p>1?p-1:p,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 S=v*o[0];for(let T=0;T<p;T++){let E=T*y,R=Math.floor(E),_=Math.min(Math.ceil(E),u-1),M=S+R*o[1],I=S+_*o[1],z=E-R,O=1-z;for(let j=0;j<c;j++){let X=j*A,D=Math.floor(X),Q=Math.min(Math.ceil(X),d-1),V=X-D,ee=1-V,J=M+D*o[2],ie=M+Q*o[2],Z=I+D*o[2],ae=I+Q*o[2],de=O*ee,Ae=O*V,be=z*ee,Ee=z*V;for(let Me=0;Me<h;Me++){let De=x[b++];f[J+Me]+=De*de,f[ie+Me]+=De*Ae,f[Z+Me]+=De*be,f[ae+Me]+=De*Ee}}}}return r.makeTensorInfo([l,d,u,h],"float32",f)}var GY={kernelName:mm,backendName:"cpu",kernelFunc:UY};function jY(e){let{inputs:t,backend:r,attrs:n}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:i,size:o}=n;Te(a,"resizeNearestNeighbor");let l=w.computeStrides(a.shape),[u,d]=o,[h,p,c,f]=a.shape,m=r.data.get(a.dataId).values,g=new Float32Array(h*u*d*f),y=[s&&u>1?p-1:p,s&&d>1?c-1:c],A=[s&&u>1?u-1:u,s&&d>1?d-1:d],x=y[0]/A[0],b=y[1]/A[1],v=0;for(let S=0;S<h;S++){let T=S*l[0];for(let E=0;E<u;E++){let R=i?x*(E+.5):x*E,_=Math.min(p-1,s?Math.round(R):Math.floor(R));i&&(_=Math.max(0,_));let M=T+_*l[1];for(let I=0;I<d;I++){let z=i?b*(I+.5):b*I,O=Math.min(c-1,s?Math.round(z):Math.floor(z));i&&(O=Math.max(0,O));let j=M+O*l[2];for(let X=0;X<f;X++){let D=m[j+X];g[v++]=D}}}}return r.makeTensorInfo([h,u,d,f],a.dtype,g)}var HY={kernelName:rd,backendName:"cpu",kernelFunc:jY};function qY(e){let{inputs:t,backend:r,attrs:n}=e,{images:a,dy:s}=t,{alignCorners:i}=n;Te([s,a],"resizeNearestNeighborGrad");let o=w.computeStrides(a.shape),l=w.computeStrides(s.shape),[u,d,h,p]=a.shape,[,c,f]=s.shape,m=new Float32Array(u*d*h*p),g=r.data.get(s.dataId).values,y=[i&&c>1?d-1:d,i&&f>1?h-1:h],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,S=1/b,T=Math.ceil(v)*2+2,E=Math.ceil(S)*2+2;for(let R=0;R<u;R++){let _=R*o[0];for(let M=0;M<d;M++){let I=_+M*o[1],z=Math.floor(M*v),O=Math.floor(z-T/2);for(let j=0;j<h;j++){let X=I+j*o[2],D=Math.floor(j*S),Q=Math.floor(D-E/2);for(let V=0;V<p;V++){let ee=0;for(let J=0;J<T;J++){let ie=J+O;if(ie<0||ie>=c)continue;let Z=_+ie*l[1],ae=ie*x,de=Math.min(d-1,i?Math.round(ae):Math.floor(ae));if(M===de)for(let Ae=0;Ae<E;Ae++){let be=Ae+Q;if(be<0||be>=f)continue;let Ee=Z+be*l[2],Me=be*b,De=Math.min(h-1,i?Math.round(Me):Math.floor(Me));j===De&&(ee+=g[Ee+V])}}m[X+V]=ee}}}}return r.makeTensorInfo(a.shape,a.dtype,m)}var KY={kernelName:fm,backendName:"cpu",kernelFunc:qY};function XY(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{dims:s}=n;Te(a,"reverse");let i=a.shape.length,o=w.parseAxisParam(s,a.shape);if(i===0)return $a({inputs:{x:a},backend:r});let l=new sr(a.shape,a.dtype),u=r.bufferSync(a);for(let d=0;d<l.size;d++){let h=l.indexToLoc(d),p=h.slice();o.forEach(c=>p[c]=a.shape[c]-1-p[c]),l.set(u.get(...p),...h)}return r.makeTensorInfo(l.shape,l.dtype,l.values)}var ZY={kernelName:hl,backendName:"cpu",kernelFunc:XY},YY={kernelName:Tl,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{image:n}=e,{radians:a,fillValue:s,center:i}=t,o=r,l=w.getTypedArrayFromDType(n.dtype,w.sizeFromShape(n.shape)),[u,d,h,p]=n.shape,[c,f]=N.getImageCenter(i,d,h),m=255,g=Math.sin(a),y=Math.cos(a),A=o.data.get(n.dataId).values;for(let x=0;x<u;x++){let b=x*h*d*p;for(let v=0;v<d;v++){let S=v*(h*p);for(let T=0;T<h;T++){let E=T*p;for(let R=0;R<p;R++){let _=[u,v,T,R],M=_[2],I=_[1],z=(M-c)*y-(I-f)*g,O=(M-c)*g+(I-f)*y;z=Math.round(z+c),O=Math.round(O+f);let j=s;if(typeof s!="number"&&(R===3?j=m:j=s[R]),z>=0&&z<h&&O>=0&&O<d){let D=O*(h*p),Q=z*p,V=b+D+Q+R;j=A[V]}let X=b+S+E+R;l[X]=j}}}}return{dataId:o.write(l,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},JY=mt(cl,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}),QY={kernelName:cl,backendName:"cpu",kernelFunc:JY};function QI(e,t,r,n,a,s,i,o,l,u){let d=[n/a,a],h=e.values,p=t.values;if(n===0)return We(r,t.dtype);let c=We(d,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=h[f*i+y];m.push(A),g+=A*o[y]}if(g<0||g>=n/a)throw new Error(`Invalid indices: ${m} does not index into ${r}`);for(let y=0;y<a;y++)u?c.values[g*a+y]+=p[f*a+y]:c.values[g*a+y]=t.rank===0?p[0]:p[f*a+y]}return c}function eJ(e){let{inputs:t,backend:r,attrs:n}=e,{indices:a,updates:s}=t,{shape:i}=n,{sliceRank:o,numUpdates:l,sliceSize:u,strides:d,outputSize:h}=N.calculateShapes(s,a,i),p=!0,c=r.bufferSync(a),f=r.bufferSync(s),m=QI(c,f,i,h,u,l,o,d,0,p);return r.makeTensorInfo(i,m.dtype,m.values)}var tJ={kernelName:fl,backendName:"cpu",kernelFunc:eJ};function rJ(e){let{inputs:t,backend:r}=e,{condition:n,t:a,e:s}=t;Te([n,a,s],"select");let i=n.shape.length,o=r.data.get(n.dataId).values,l=r.data.get(a.dataId).values,u=r.data.get(s.dataId).values,d=Cr(a.dtype,s.dtype),h=w.makeZerosTypedArray(w.sizeFromShape(a.shape),d),p=0,c=i===0||i>1||a.shape.length===1?1:w.sizeFromShape(a.shape.slice(1));for(let f=0;f<o.length;f++)for(let m=0;m<c;m++)o[f]===1?h[p++]=l[f]:h[p++]=u[f];return r.makeTensorInfo(a.shape,d,h)}var nJ={kernelName:ml,backendName:"cpu",kernelFunc:rJ},aJ=N.SELU_SCALEALPHA,sJ=N.SELU_SCALE,iJ=mt(nd,e=>e>=0?sJ*e:aJ*(Math.exp(e)-1)),oJ={kernelName:nd,backendName:"cpu",kernelFunc:iJ},lJ=mt(ad,e=>e<0?-1:e>0?1:0),uJ={kernelName:ad,backendName:"cpu",kernelFunc:lJ},dJ=mt(Fi,e=>Math.sin(e)),pJ={kernelName:Fi,backendName:"cpu",kernelFunc:dJ},hJ=mt(yl,e=>Math.sinh(e)),cJ={kernelName:yl,backendName:"cpu",kernelFunc:hJ},fJ=11920928955078125e-23,Ev=Math.log(fJ)+2,mJ=mt(sd,e=>{let t=e>-Ev,r=e<Ev,n=Math.exp(e),a;return r?a=n:t?a=e:a=Math.log(1+n),a}),gJ={kernelName:sd,backendName:"cpu",kernelFunc:mJ};function yJ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockShape:s,paddings:i}=n;Te([a],"spaceToBatchND");let o=w.sizeFromShape(s),l=[[0,0]];l.push(...i);for(let g=1+s.length;g<a.shape.length;++g)l.push([0,0]);let u=JI.kernelFunc({inputs:{x:a},backend:r,attrs:{paddings:l,constantValue:0}}),d=N.getReshaped(u.shape,s,o,!1),h=N.getPermuted(d.length,s.length,!1),p=N.getReshapedPermuted(u.shape,s,o,!1),c=Mt({inputs:{x:u},backend:r,attrs:{shape:d}}),f=an({inputs:{x:c},backend:r,attrs:{perm:h}}),m=Mt({inputs:{x:f},backend:r,attrs:{shape:p}});return r.disposeIntermediateTensorInfo(u),r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(f),m}var AJ={kernelName:Al,backendName:"cpu",kernelFunc:yJ};function xJ(e){let{inputs:t,backend:r}=e,{indices:n,values:a,denseShape:s,defaultValue:i}=t;if(s.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
|
|
${s.shape}`);if(n.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
|
|
${n.shape}`);if(a.shape.length!==1)throw new Error(`Values must be a vector, saw:
|
|
${a.shape}`);if(i.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
|
|
${i.shape}`);let o=r.data.get(n.dataId).values,l=r.data.get(a.dataId).values,u=r.data.get(s.dataId).values,d=r.data.get(i.dataId).values[0],[h,p,c,f,m]=SI(o,n.shape,n.dtype,l,a.dtype,u,d);return[r.makeTensorInfo(p,n.dtype,h),r.makeTensorInfo([p[0]],a.dtype,c),r.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),r.makeTensorInfo([m.length],n.dtype,new Int32Array(m))]}var bJ={kernelName:sh,backendName:"cpu",kernelFunc:xJ};function vJ(e){let{inputs:t,backend:r}=e,{inputIndices:n,inputShape:a,newShape:s}=t;if(n.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
|
|
${n.shape}`);if(a.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
|
|
${a.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(a.dataId).values),o=r.data.get(n.dataId).values,l=Array.from(r.data.get(s.dataId).values),[u,d,h]=TI(o,n.shape,n.dtype,i,l);return[r.makeTensorInfo(d,n.dtype,u),r.makeTensorInfo([h.length],s.dtype,new Int32Array(h))]}var wJ={kernelName:id,backendName:"cpu",kernelFunc:vJ};function kJ(e){let{inputs:t,backend:r}=e,{data:n,indices:a,segmentIds:s}=t;if(n.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(a.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${a.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${s.shape}`);if(a.shape[0]!==s.shape[0])throw new Error("segmentIds and indices should have same size.");let i=r.data.get(n.dataId).values,o=r.data.get(a.dataId).values,l=r.data.get(s.dataId).values,[u,d]=eb(i,n.shape,n.dtype,o,l,!0);return r.makeTensorInfo(d,n.dtype,u)}var IJ={kernelName:ih,backendName:"cpu",kernelFunc:kJ};function SJ(e){let{inputs:t,backend:r}=e,{data:n,indices:a,segmentIds:s}=t;if(n.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(a.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${a.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${s.shape}`);if(a.shape[0]!==s.shape[0])throw new Error("segmentIds and indices should have same size.");let i=r.data.get(n.dataId).values,o=r.data.get(a.dataId).values,l=r.data.get(s.dataId).values,[u,d]=eb(i,n.shape,n.dtype,o,l);return r.makeTensorInfo(d,n.dtype,u)}var TJ={kernelName:oh,backendName:"cpu",kernelFunc:SJ};function NJ(e){let{inputs:t,backend:r,attrs:n}=e,{sparseIndices:a,sparseValues:s,defaultValue:i}=t,{outputShape:o}=n,{sliceRank:l,numUpdates:u,sliceSize:d,strides:h,outputSize:p}=N.calculateShapes(s,a,o),c=!1,f=r.bufferSync(a),m=r.bufferSync(s),g=r.data.get(i.dataId).values[0],y=QI(f,m,o,p,d,u,l,h,g,c);return r.makeTensorInfo(o,y.dtype,y.values)}var CJ={kernelName:lh,backendName:"cpu",kernelFunc:NJ};function EJ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{numOrSizeSplits:s,axis:i}=n,o=w.parseAxisParam(i,a.shape)[0],l=N.prepareSplitSize(a,s,o),u=new Array(a.shape.length).fill(0),d=a.shape.slice();return l.map(h=>{let p=[...d];p[o]=h;let c=zo({inputs:{x:a},backend:r,attrs:{begin:u,size:p}});return u[o]+=h,c})}var RJ={kernelName:xl,backendName:"cpu",kernelFunc:EJ},MJ={kernelName:od,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{let{x:r}=e,n=t;Te(r,"square");let a=n.data.get(r.dataId).values,s=new Float32Array(a.length);for(let i=0;i<a.length;++i){let o=a[i];s[i]=o*o}return{dataId:n.write(s,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},FJ=mt(Wi,(e,t)=>{let r=t;return isNaN(e)?NaN:e>0?1:r.alpha}),$J={kernelName:Wi,backendName:"cpu",kernelFunc:FJ};function PJ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:d,newAxisMask:h,shrinkAxisMask:p}=n;Te(a,"stridedSlice");let{finalShapeSparse:c,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:A,end:x,strides:b}=zt.sliceInfo(a.shape,s,i,o,l,u,d,h,p),v;if(m)v=Mt({inputs:{x:a},backend:r,attrs:{shape:f}});else if(g||y){w.assert(a.shape.length>=1,()=>`Input must have rank at least 1, got: ${a.shape.length}`);let S=zt.computeOutShape(A,x,b),T=zo({inputs:{x:a},backend:r,attrs:{begin:A,size:S}});v=Mt({inputs:{x:T},backend:r,attrs:{shape:f}}),r.disposeIntermediateTensorInfo(T)}else{let S=r.bufferSync(a),T=CI(c,S,b,A);v=r.makeTensorInfo(f,T.dtype,T.values)}return v}var _J={kernelName:bl,backendName:"cpu",kernelFunc:PJ};function zJ(e){let{inputs:t,backend:r,attrs:n}=e,{separator:a,nGramWidths:s,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=n,{data:d,dataSplits:h}=t,p=r.data.get(d.dataId).values,c=r.data.get(h.dataId).values,[f,m]=EI(p,c,a,s,i,o,l,u);return[r.makeTensorInfo([f.length],"string",f),r.makeTensorInfo(h.shape,"int32",m)]}var OJ={kernelName:uh,backendName:"cpu",kernelFunc:zJ};function DJ(e){let{inputs:t,backend:r,attrs:n}=e,{skipEmpty:a}=n,{input:s,delimiter:i}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(s.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${s.shape}`);if(i.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);let o=r.data.get(s.dataId).values,l=r.data.get(i.dataId).values[0],[u,d,h]=RI(o,l,a),p=d.length;return[r.makeTensorInfo([p,2],"int32",u),r.makeTensorInfo([p],"string",d),r.makeTensorInfo([2],"int32",new Int32Array(h))]}var LJ={kernelName:gm,backendName:"cpu",kernelFunc:DJ};function BJ(e){let{inputs:t,backend:r,attrs:n}=e,{numBuckets:a}=n,{input:s}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(a<=0)throw new Error("Number of buckets must be at least 1");let i=r.data.get(s.dataId).values,o=MI(i,a);return r.makeTensorInfo(s.shape,"int32",o)}var WJ={kernelName:ym,backendName:"cpu",kernelFunc:BJ},VJ=mt(vl,e=>Math.tan(e)),UJ={kernelName:vl,backendName:"cpu",kernelFunc:VJ},GJ=mt(Li,e=>Math.tanh(e)),jJ={kernelName:Li,backendName:"cpu",kernelFunc:GJ};function HJ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{reps:s}=n;Te(a,"tile");let i=$I(r.bufferSync(a),s);return r.makeTensorInfo(i.shape,i.dtype,i.values)}var qJ={kernelName:es,backendName:"cpu",kernelFunc:HJ};function KJ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{k:s,sorted:i}=n;Te(a,"topk");let o=r.data.get(a.dataId).values,[l,u]=_I(o,a.shape,a.dtype,s,i);return[r.makeTensorInfo(l.shape,l.dtype,l.values),r.makeTensorInfo(u.shape,u.dtype,u.values)]}var XJ={kernelName:wl,backendName:"cpu",kernelFunc:KJ};function ZJ(e){let{inputs:t,attrs:r,backend:n}=e,{image:a,transforms:s}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=r,[d,h,p,c]=a.shape,[f,m]=u!=null?u:[h,p],g=[d,f,m,c],y=w.computeStrides(a.shape),A=y[0],x=y[1],b=y[2],v=w.getTypedArrayFromDType(a.dtype,w.sizeFromShape(g));v.fill(l);let S=n.data.get(a.dataId).values,T=n.data.get(s.dataId).values;for(let E=0;E<d;++E){let R=s.shape[0]===1?T:T.subarray(E*8,E*8+8);for(let _=0;_<f;++_)for(let M=0;M<m;++M)for(let I=0;I<c;++I){let z,O=R[6]*M+R[7]*_+1;if(O===0)continue;let j=(R[0]*M+R[1]*_+R[2])/O,X=(R[3]*M+R[4]*_+R[5])/O,D=Rv(j,p,o),Q=Rv(X,h,o);switch(i){case"nearest":z=rQ(S,h,p,A,x,b,E,Q,D,I,l);break;case"bilinear":z=nQ(S,h,p,A,x,b,E,Q,D,I,l);break;default:throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${i}`)}let V=E*A+_*x+M*b+I;v[V]=z}return n.makeTensorInfo(g,a.dtype,v)}return{dataId:n.write(v,g,a.dtype),shape:a.shape,dtype:a.dtype}}var YJ={kernelName:kl,backendName:"cpu",kernelFunc:ZJ};function Rv(e,t,r){switch(r){case"reflect":return JJ(e,t);case"wrap":return QJ(e,t);case"nearest":return tQ(e,t);case"constant":default:return eQ(e,t)}}function JJ(e,t){let r=e;if(r<0)if(t<=1)r=0;else{let n=2*t;r<n&&(r=n*Math.trunc(-r/n)+r),r=r<-t?r+n:-r-1}else if(r>t-1)if(t<=1)r=0;else{let n=2*t;r-=n*Math.trunc(r/n),r>=t&&(r=n-r-1)}return w.clamp(0,r,t-1)}function QJ(e,t){let r=e;if(r<0)if(t<=1)r=0;else{let n=t-1;r+=t*(Math.trunc(-r/n)+1)}else if(r>t-1)if(t<=1)r=0;else{let n=t-1;r-=t*Math.trunc(r/n)}return w.clamp(0,r,t-1)}function eQ(e,t){return e}function tQ(e,t){return w.clamp(0,e,t-1)}function Ip(e,t,r,n,a,s,i,o,l,u,d){let h=i*n+o*a+l*s+u;return 0<=o&&o<t&&0<=l&&l<r?e[h]:d}function rQ(e,t,r,n,a,s,i,o,l,u,d){let h=Math.round(o),p=Math.round(l);return Ip(e,t,r,n,a,s,i,h,p,u,d)}function nQ(e,t,r,n,a,s,i,o,l,u,d){let h=Math.floor(o),p=Math.floor(l),c=h+1,f=p+1,m=(f-l)*Ip(e,t,r,n,a,s,i,h,p,u,d)+(l-p)*Ip(e,t,r,n,a,s,i,h,f,u,d),g=(f-l)*Ip(e,t,r,n,a,s,i,c,p,u,d)+(l-p)*Ip(e,t,r,n,a,s,i,c,f,u,d);return(c-o)*m+(o-h)*g}function aQ(e){let{inputs:t,attrs:r,backend:n}=e,{axis:a}=r,{x:s}=t;Te(s,"unique");let i=n.data.get(s.dataId).values,{outputValues:o,outputShape:l,indices:u}=zI(i,a,s.shape,s.dtype);return[n.makeTensorInfo(l,s.dtype,o),n.makeTensorInfo([u.length],"int32",u)]}var sQ={kernelName:Am,backendName:"cpu",kernelFunc:aQ};function iQ(e){let{inputs:t,backend:r,attrs:n}=e,{value:a}=t,{axis:s}=n;s<0&&(s+=a.shape.length);let i=a.shape.length,o=a.shape[s],l=new Array(i-1),u=0;for(let c=0;c<i;c++)c!==s&&(l[u++]=a.shape[c]);let d=new Array(i).fill(0),h=a.shape.slice();h[s]=1;let p=new Array(o);for(let c=0;c<p.length;c++){d[s]=c;let f=zo({inputs:{x:a},backend:r,attrs:{begin:d,size:h}});p[c]=Mt({inputs:{x:f},backend:r,attrs:{shape:l}}),r.disposeIntermediateTensorInfo(f)}return p}var oQ={kernelName:Il,backendName:"cpu",kernelFunc:iQ};function lQ(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,segmentIds:s}=t,{numSegments:i}=n;Te(a,"unsortedSegmentSum");let o=a.shape.length,l=s.shape.length,u=[],d=[],h=o-l,p=s;for(let f=0;f<h;++f){let m=Df({inputs:{input:p},backend:r,attrs:{dim:f+1}});p=m,d.push(m)}for(let f=0;f<i;++f){let m=w.createScalarValue(f,"int32"),g=r.makeTensorInfo([],"int32",m),y=aI({inputs:{a:g,b:p},backend:r}),A=js({inputs:{x:y},backend:r,attrs:{dtype:"float32"}}),x=y0({inputs:{a:A,b:a},backend:r}),b=Ph({inputs:{x},backend:r,attrs:{axis:0,keepDims:!1}});u.push(b),d.push(g),d.push(y),d.push(A),d.push(x),d.push(b)}let c=YI({inputs:u,backend:r,attrs:{axis:0}});return d.forEach(f=>r.disposeIntermediateTensorInfo(f)),c}var uQ={kernelName:dh,backendName:"cpu",kernelFunc:lQ},dQ=[mK,oq,yK,xK,cq,vK,kK,SK,NK,EK,MK,$K,_K,DK,BK,UK,jK,qK,XK,cK,YK,QK,tX,nX,pq,mq,sX,lq,oX,uX,dX,hX,fX,gX,AX,bX,wX,IX,TX,CX,RX,FX,PX,_X,OX,LX,WX,VX,UX,GX,qX,iK,XX,gq,nZ,yq,aZ,xq,dZ,pZ,cZ,vq,gZ,AZ,bZ,wZ,IZ,kq,Sq,uq,TZ,lX,CZ,RZ,FZ,oK,Nq,Eq,PZ,Mq,zZ,LZ,WZ,GZ,HZ,KZ,XZ,$q,YZ,QZ,tY,nY,sY,oY,uY,_q,pY,fY,AY,Oq,Lq,vY,IY,NY,Wq,EY,MY,FY,JI,zY,uK,Gq,DY,dq,Hy,BY,dK,pK,hK,VY,GY,HY,KY,ZY,YY,QY,Hq,tJ,nJ,oJ,Kq,uJ,pJ,cJ,Xq,gY,gJ,AJ,bJ,wJ,IJ,TJ,CJ,RJ,Jq,MJ,eK,$J,_J,OJ,LJ,WJ,aK,jX,UJ,jJ,qJ,XJ,YJ,Vq,sQ,oQ,uQ,RY];for(let e of dQ)jn(e);var eS={};Le(eS,{assertNotComplex:()=>vd,bindCanvasToFramebuffer:()=>vQ,bindColorTextureToFramebuffer:()=>sf,bindTextureToProgramUniformSampler:()=>mS,bindTextureUnit:()=>hS,bindVertexBufferToProgramAttribute:()=>Ky,callAndCheck:()=>we,canBeRepresented:()=>tS,createFragmentShader:()=>aS,createFramebuffer:()=>pS,createProgram:()=>sS,createStaticIndexBuffer:()=>lS,createStaticVertexBuffer:()=>oS,createTexture:()=>uS,createVertexShader:()=>nS,getBatchDim:()=>Oo,getExtensionOrThrow:()=>Sp,getFramebufferErrorMessage:()=>gS,getMaxTexturesInShader:()=>bS,getNumChannels:()=>xQ,getProgramUniformLocation:()=>fS,getProgramUniformLocationOrThrow:()=>cS,getRowsCols:()=>Do,getShapeAs3D:()=>of,getTextureShapeFromLogicalShape:()=>AS,getWebGLDisjointQueryTimerVersion:()=>vS,getWebGLErrorMessage:()=>rS,getWebGLMaxTextureSize:()=>xS,hasExtension:()=>Nn,isCapableOfRenderingToFloatTexture:()=>wS,isDownloadFloatTextureEnabled:()=>kS,isReshapeFree:()=>jp,isWebGLFenceEnabled:()=>IS,isWebGLVersionEnabled:()=>Zy,linkProgram:()=>iS,logShaderSourceAndInfoLog:()=>ob,resetMaxTextureSize:()=>wQ,resetMaxTexturesInShader:()=>kQ,unbindColorTextureFromFramebuffer:()=>Xy,unbindTextureUnit:()=>bQ,validateFramebuffer:()=>Tp,validateProgram:()=>af,validateTextureSize:()=>dS});var vo={},iy={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function A0(e,t){vo[e]=t}function ya(e,t){if(!(e in vo)||t!=null){let n=hQ(e,t);if(n!==null)vo[e]=n;else return console.log("Could not get context for WebGL version",e),null}let r=vo[e];return r==null||r.isContextLost()?(delete vo[e],ya(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),vo[e])}function pQ(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 hQ(e,t){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let r=t==null?pQ(e):t;return r.addEventListener("webglcontextlost",n=>{n.preventDefault(),delete vo[e]},!1),e===1?r.getContext("webgl",iy)||r.getContext("experimental-webgl",iy):r.getContext("webgl2",iy)}function _h(e,t){return[t,e]}function cQ(e,t){return e*t}function Yc(e){let t=w.sizeFromShape(e),r=Math.ceil(t/4);return w.sizeToSquarishShape(r)}function bd(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function fQ(e,t){let[r,n]=bd(e,t);return r*n*4}function ib(e,t){let r=e,n,a,s,i,o,l,u,d,h,p;return Y().getNumber("WEBGL_VERSION")===2?(n=r.R32F,a=r.R16F,s=r.RGBA16F,i=r.RGBA32F,o=r.RED,u=4,d=1,h=r.HALF_FLOAT,p=r.FLOAT,l=r.RGBA8):(n=e.RGBA,a=e.RGBA,s=e.RGBA,i=r.RGBA,o=e.RGBA,u=4,d=4,h=t!=null?t.HALF_FLOAT_OES:null,p=e.FLOAT,l=e.RGBA),{internalFormatFloat:n,internalFormatHalfFloat:a,internalFormatPackedHalfFloat:s,internalFormatPackedFloat:i,textureFormatFloat:o,downloadTextureFormat:l,downloadUnpackNumChannels:u,defaultNumChannels:d,textureTypeHalfFloat:h,textureTypeFloat:p}}function we(e,t){let r=t();return Y().getBool("DEBUG")&&mQ(e),r}function mQ(e){let t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+rS(e,t))}var gQ=596e-10,yQ=65504;function tS(e){return!!(Y().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||e===0||gQ<Math.abs(e)&&Math.abs(e)<yQ)}function rS(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 Sp(e,t){return ss(e,()=>e.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function nS(e,t){let r=ss(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 aS(e,t){let r=ss(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(we(e,()=>e.shaderSource(r,t)),we(e,()=>e.compileShader(r)),Y().get("ENGINE_COMPILE_ONLY"))return r;if(e.getShaderParameter(r,e.COMPILE_STATUS)===!1)throw ob(t,e.getShaderInfoLog(r)),new Error("Failed to compile fragment shader.");return r}var AQ=/ERROR: [0-9]+:([0-9]+):/g;function ob(e,t){let r=AQ.exec(t);if(r==null){console.log(`Couldn't parse line number in error: ${t}`),console.log(e);return}let n=+r[1],a=e.split(`
|
|
`),s=a.length.toString().length+2,i=a.map((h,p)=>w.rightPad((p+1).toString(),s)+h),o=0;for(let h=0;h<i.length;h++)o=Math.max(i[h].length,o);let l=i.slice(0,n-1),u=i.slice(n-1,n),d=i.slice(n);console.log(l.join(`
|
|
`)),console.log(t.split(`
|
|
`)[0]),console.log(`%c ${w.rightPad(u[0],o)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(d.join(`
|
|
`))}function sS(e){return ss(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function iS(e,t){if(we(e,()=>e.linkProgram(t)),!Y().get("ENGINE_COMPILE_ONLY")&&e.getProgramParameter(t,e.LINK_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function af(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 oS(e,t){let r=ss(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 lS(e,t){let r=ss(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 xQ(){return Y().getNumber("WEBGL_VERSION")===2?1:4}function uS(e){return ss(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function dS(e,t){let r=Y().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){let n=`[${e}x${t}]`;throw new Error("Requested texture size "+n+" is invalid.")}if(e>r||t>r){let n=`[${e}x${t}]`,a=`[${r}x${r}]`;throw new Error("Requested texture size "+n+" greater than WebGL maximum on this browser / GPU "+a+".")}}function pS(e){return ss(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function Ky(e,t,r,n,a,s,i){let o=e.getAttribLocation(t,r);return o===-1?!1:(we(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),we(e,()=>e.vertexAttribPointer(o,a,e.FLOAT,!1,s,i)),we(e,()=>e.enableVertexAttribArray(o)),!0)}function hS(e,t,r){yS(e,r),we(e,()=>e.activeTexture(e.TEXTURE0+r)),we(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function bQ(e,t){yS(e,t),we(e,()=>e.activeTexture(e.TEXTURE0+t)),we(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function cS(e,t,r){return ss(e,()=>e.getUniformLocation(t,r),'uniform "'+r+'" not present in program.')}function fS(e,t,r){return e.getUniformLocation(t,r)}function mS(e,t,r,n){we(e,()=>hS(e,t,n)),we(e,()=>e.uniform1i(r,n))}function vQ(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 sf(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 Xy(e,t){we(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),we(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function Tp(e){let t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+gS(e,t))}function gS(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 ss(e,t,r){let n=we(e,()=>t());if(n==null)throw new Error(r);return n}function yS(e,t){let r=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,n=t+e.TEXTURE0;if(n<e.TEXTURE0||n>r){let a=`[gl.TEXTURE0, gl.TEXTURE${r}]`;throw new Error(`textureUnit must be in ${a}.`)}}function Oo(e,t=2){return w.sizeFromShape(e.slice(0,e.length-t))}function Do(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 of(e){let t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[Oo(e),...Do(e)]),t}function AS(e,t=!1){let r=Y().getNumber("WEBGL_MAX_TEXTURE_SIZE");t&&(r=r*2,e=e.map((a,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 n=w.sizeFromShape(e);if(e.length<=1&&n<=r)return[1,n];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 a=Oo(e),s=2,i=2;return e.length&&([s,i]=Do(e)),n=a*(s/2)*(i/2),w.sizeToSquarishShape(n).map(o=>o*2)}return w.sizeToSquarishShape(n)}function Jc(e){return e%2===0}function jp(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],n=t.slice(-1)[0];if(r===n||Jc(r)&&Jc(n)&&(e[0]===1||t[0]===1))return!0}return e[1]===t[1]&&Jc(e[0])&&Jc(t[0])}var lf,uf;function xS(e){if(lf==null){let t=ya(e);lf=t.getParameter(t.MAX_TEXTURE_SIZE)}return lf}function wQ(){lf=null}function kQ(){uf=null}function bS(e){if(uf==null){let t=ya(e);uf=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,uf)}function vS(e){if(e===0)return 0;let t,r=ya(e);return Nn(r,"EXT_disjoint_timer_query_webgl2")&&e===2?t=2:Nn(r,"EXT_disjoint_timer_query")?t=1:t=0,t}function Nn(e,t){return e.getExtension(t)!=null}function Zy(e){try{if(ya(e)!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function wS(e){if(e===0)return!1;let t=ya(e);if(e===1){if(!Nn(t,"OES_texture_float"))return!1}else if(!Nn(t,"EXT_color_buffer_float"))return!1;return Yy(t)}function kS(e){if(e===0)return!1;let t=ya(e);if(e===1){if(!Nn(t,"OES_texture_float")||!Nn(t,"WEBGL_color_buffer_float"))return!1}else{if(Nn(t,"EXT_color_buffer_float"))return Yy(t);let r="EXT_color_buffer_half_float";if(Nn(t,r)){let n=t.getExtension(r);return IQ(t,n)}return!1}return Yy(t)}function Yy(e){let t=ib(e),r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r);let n=1,a=1;e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,n,a,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 IQ(e,t){let r=ib(e,t),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n);let a=1,s=1;e.texImage2D(e.TEXTURE_2D,0,r.internalFormatHalfFloat,a,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,n,0);let o=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(i),o}function IS(e){return e!==2?!1:ya(e).fenceSync!=null}function vd(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 Fe=Y();Fe.registerFlag("HAS_WEBGL",()=>Fe.getNumber("WEBGL_VERSION")>0);Fe.registerFlag("WEBGL_VERSION",()=>Zy(2)?2:Zy(1)?1:0);Fe.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);Fe.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>Fe.get("WEBGL_VERSION")===2);Fe.registerFlag("WEBGL_CPU_FORWARD",()=>!0);Fe.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);Fe.registerFlag("WEBGL_PACK",()=>Fe.getBool("HAS_WEBGL"));Fe.registerFlag("WEBGL_PACK_NORMALIZATION",()=>Fe.getBool("WEBGL_PACK"));Fe.registerFlag("WEBGL_PACK_CLIP",()=>Fe.getBool("WEBGL_PACK"));Fe.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>Fe.getBool("WEBGL_PACK"));Fe.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>Fe.getBool("WEBGL_PACK"));Fe.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>Fe.getBool("WEBGL_PACK"));Fe.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>Fe.getBool("WEBGL_PACK"));Fe.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>Fe.getBool("WEBGL_PACK"));Fe.registerFlag("WEBGL_PACK_REDUCE",()=>Fe.getBool("WEBGL_PACK"));Fe.registerFlag("WEBGL_LAZILY_UNPACK",()=>Fe.getBool("WEBGL_PACK"));Fe.registerFlag("WEBGL_CONV_IM2COL",()=>Fe.getBool("WEBGL_PACK"));Fe.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>xS(Fe.getNumber("WEBGL_VERSION")));Fe.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>bS(Fe.getNumber("WEBGL_VERSION")));Fe.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{let e=Fe.getNumber("WEBGL_VERSION");return e===0?0:vS(e)});Fe.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>Fe.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!fh.isMobile());Fe.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>wS(Fe.getNumber("WEBGL_VERSION")));Fe.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>Fe.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:Fe.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));Fe.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>kS(Fe.getNumber("WEBGL_VERSION")));Fe.registerFlag("WEBGL_FENCE_API_ENABLED",()=>IS(Fe.getNumber("WEBGL_VERSION")));Fe.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>Fe.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0);Fe.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}.`)});Fe.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>fh.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}.`)});Fe.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",()=>128);Fe.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",()=>!1);Fe.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e5);Fe.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",()=>128);function jr(){let e,t,r,n,a,s,i,o,l,u;return Y().getNumber("WEBGL_VERSION")===2?(e="#version 300 es",t="in",r="out",n="in",a="texture",s="outputColor",i="out vec4 outputColor;",o=`
|
|
bool isnan_custom(float val) {
|
|
uint floatToUint = floatBitsToUint(val);
|
|
return (floatToUint & 0x7fffffffu) > 0x7f800000u;
|
|
}
|
|
|
|
bvec4 isnan_custom(vec4 val) {
|
|
return bvec4(isnan_custom(val.x),
|
|
isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
|
|
}
|
|
|
|
#define isnan(value) isnan_custom(value)
|
|
`,l="",u=`
|
|
#define round(value) newRound(value)
|
|
int newRound(float value) {
|
|
return int(floor(value + 0.5));
|
|
}
|
|
|
|
ivec4 newRound(vec4 value) {
|
|
return ivec4(floor(value + vec4(0.5)));
|
|
}
|
|
`):(e="",t="attribute",r="varying",n="varying",a="texture2D",s="gl_FragColor",i="",o=`
|
|
#define isnan(value) isnan_custom(value)
|
|
bool isnan_custom(float val) {
|
|
return (val > 0. || val < 1. || val == 0.) ? false : true;
|
|
}
|
|
bvec4 isnan_custom(vec4 val) {
|
|
return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
|
|
}
|
|
`,l=`
|
|
uniform float INFINITY;
|
|
|
|
bool isinf(float val) {
|
|
return abs(val) == INFINITY;
|
|
}
|
|
bvec4 isinf(vec4 val) {
|
|
return equal(abs(val), vec4(INFINITY));
|
|
}
|
|
`,u=`
|
|
int round(float value) {
|
|
return int(floor(value + 0.5));
|
|
}
|
|
|
|
ivec4 round(vec4 value) {
|
|
return ivec4(floor(value + vec4(0.5)));
|
|
}
|
|
`),{version:e,attribute:t,varyingVs:r,varyingFs:n,texture2D:a,output:s,defineOutput:i,defineSpecialNaN:o,defineSpecialInf:l,defineRound:u}}function _l(e,t,r="index"){let n=w.computeStrides(t);return n.map((a,s)=>{let i=`int ${e[s]} = ${r} / ${a}`,o=s===n.length-1?`int ${e[s+1]} = ${r} - ${e[s]} * ${a}`:`index -= ${e[s]} * ${a}`;return`${i}; ${o};`}).join("")}function x0(e,t,r="index"){let n=w.computeStrides(t);return n.map((a,s)=>{let i=`int ${e[s]} = ${r} / outShapeStrides[${s}]`,o=s===n.length-1?`int ${e[s+1]} = ${r} - ${e[s]} * outShapeStrides[${s}]`:`index -= ${e[s]} * outShapeStrides[${s}]`;return`${i}; ${o};`}).join("")}function SQ(e,t){let r=e.length,n=e.map(s=>`${t}[${s}]`),a=new Array(r-1);a[r-2]=n[r-1];for(let s=r-3;s>=0;--s)a[s]=`(${a[s+1]} * ${n[s+1]})`;return a}function TQ(e,t,r="index"){let n=e.map((s,i)=>i),a=SQ(n,t);return a.map((s,i)=>{let o=`int ${e[i]} = ${r} / ${a[i]}`,l=i===a.length-1?`int ${e[i+1]} = ${r} - ${e[i]} * ${a[i]}`:`index -= ${e[i]} * ${a[i]}`;return`${o}; ${l};`}).join("")}function lb(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 ub(){return`
|
|
int getFlatIndex(ivec3 coords) {
|
|
return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;
|
|
}
|
|
`}var SS=`
|
|
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:TS}=N;function NQ(e,t,r){let n=[];if(e.forEach(p=>{let c=w.sizeFromShape(p.shapeInfo.logicalShape);if(p.shapeInfo.isUniform?n.push(`uniform float ${p.name}${c>1?`[${c}]`:""};`):(n.push(`uniform sampler2D ${p.name};`),n.push(`uniform int offset${p.name};`)),r.enableShapeUniforms){let{uniformShape:f}=db(r.packedInputs,p.shapeInfo.logicalShape,p.shapeInfo.texShape);switch(f.length){case 1:n.push(`uniform int ${p.name}Shape;`);break;case 2:n.push(`uniform ivec2 ${p.name}Shape;`);break;case 3:n.push(`uniform ivec3 ${p.name}Shape;`);break;case 4:n.push(`uniform ivec4 ${p.name}Shape;`);break;default:break}n.push(`uniform ivec2 ${p.name}TexShape;`)}}),r.enableShapeUniforms){switch(t.logicalShape.length){case 1:n.push("uniform int outShape;");break;case 2:n.push("uniform ivec2 outShape;"),n.push("uniform int outShapeStrides;");break;case 3:n.push("uniform ivec3 outShape;"),n.push("uniform ivec2 outShapeStrides;");break;case 4:n.push("uniform ivec4 outShape;"),n.push("uniform ivec3 outShapeStrides;");break;default:break}n.push("uniform ivec2 outTexShape;")}r.customUniforms&&r.customUniforms.forEach(p=>{n.push(`uniform ${p.type} ${p.name}${p.arrayIndex?`[${p.arrayIndex}]`:""};`)});let a=n.join(`
|
|
`),s=e.map(p=>CQ(p,t,r.packedInputs,r.enableShapeUniforms)).join(`
|
|
`),i=t.texShape,o=jr(),l=MQ(o),u,d,h=PQ(o);return t.isPacked?(u=EQ(t.logicalShape,i,r.enableShapeUniforms),d=$Q(o)):(u=RQ(t.logicalShape,i,r.enableShapeUniforms),d=FQ(o)),r.packedInputs&&(h+=DQ),[h,l,d,a,u,s,r.userCode].join(`
|
|
`)}function wd(e,t=!1){let r=e.shapeInfo.logicalShape;switch(r.length){case 0:return ZQ(e,t);case 1:return JQ(e,t);case 2:return eee(e,t);case 3:return ree(e,t);case 4:return aee(e,t);case 5:return see(e);case 6:return iee(e);default:throw new Error(`${r.length}-D input sampling is not yet supported`)}}function NS(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return XQ(e);case 1:return YQ(e,t);case 2:return QQ(e,t);case 3:return tee(e,t);default:return nee(e,t)}}function CQ(e,t,r=!1,n){let a="";r?a+=NS(e,n):a+=wd(e,n);let s=e.shapeInfo.logicalShape,i=t.logicalShape;return s.length<=i.length&&(r?a+=oee(e,t):a+=lee(e,t)),a}function EQ(e,t,r){switch(e.length){case 0:return CS();case 1:return LQ(e,t,r);case 2:return qQ(e,t,r);case 3:return WQ(e,t,r);default:return UQ(e,t,r)}}function RQ(e,t,r){switch(e.length){case 0:return CS();case 1:return BQ(e,t,r);case 2:return KQ(e,t,r);case 3:return VQ(e,t,r);case 4:return GQ(e,t,r);case 5:return jQ(e,t);case 6:return HQ(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function MQ(e){return`
|
|
float sampleTexture(sampler2D textureSampler, vec2 uv) {
|
|
return ${e.texture2D}(textureSampler, uv).r;
|
|
}
|
|
`}function FQ(e){return`
|
|
void setOutput(float val) {
|
|
${e.output} = vec4(val, 0, 0, 0);
|
|
}
|
|
`}function $Q(e){return`
|
|
void setOutput(vec4 val) {
|
|
${e.output} = val;
|
|
}
|
|
`}function PQ(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);
|
|
}
|
|
|
|
${_Q}
|
|
${zQ}
|
|
${OQ}
|
|
`}var _Q=`
|
|
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);
|
|
}
|
|
`,zQ=`
|
|
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);
|
|
}
|
|
`,OQ=`
|
|
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);
|
|
}
|
|
`,DQ=`
|
|
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 CS(){return`
|
|
int getOutputCoords() {
|
|
return 0;
|
|
}
|
|
`}function LQ(e,t,r){let n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return n[0]===1?r?`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.x * ${n[1]}.0);
|
|
}
|
|
`:n[1]===1?r?`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.y * ${n[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(${n[0]}, ${n[1]}));
|
|
return 2 * (resTexRC.x * ${n[1]} + resTexRC.y);
|
|
}
|
|
`}function BQ(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 WQ(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 n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],a=Math.ceil(e[2]/2),s=a*Math.ceil(e[1]/2);return`
|
|
ivec3 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${n[0]}, ${n[1]}));
|
|
int index = resTexRC.x * ${n[1]} + resTexRC.y;
|
|
|
|
int b = index / ${s};
|
|
index -= b * ${s};
|
|
|
|
int r = 2 * (index / ${a});
|
|
int c = imod(index, ${a}) * 2;
|
|
|
|
return ivec3(b, r, c);
|
|
}
|
|
`}function VQ(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;
|
|
${x0(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`;let n=_l(["r","c","d"],e);return`
|
|
ivec3 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
${n}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`}function UQ(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 n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],a=Math.ceil(e[e.length-1]/2),s=a*Math.ceil(e[e.length-2]/2),i=s,o="",l="b, r, c";for(let u=2;u<e.length-1;u++)i*=e[e.length-u-1],o=`
|
|
int b${u} = index / ${i};
|
|
index -= b${u} * ${i};
|
|
`+o,l=`b${u}, `+l;return`
|
|
ivec${e.length} getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${n[0]}, ${n[1]}));
|
|
int index = resTexRC.x * ${n[1]} + resTexRC.y;
|
|
|
|
${o}
|
|
|
|
int b = index / ${s};
|
|
index -= b * ${s};
|
|
|
|
int r = 2 * (index / ${a});
|
|
int c = imod(index, ${a}) * 2;
|
|
|
|
return ivec${e.length}(${l});
|
|
}
|
|
`}function GQ(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;
|
|
${x0(["r","c","d","d2"],e)}
|
|
return ivec4(r, c, d, d2);
|
|
}
|
|
`;let n=_l(["r","c","d","d2"],e);return`
|
|
ivec4 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
int index = resTexRC.x * ${t[1]} + resTexRC.y;
|
|
${n}
|
|
return ivec4(r, c, d, d2);
|
|
}
|
|
`}function jQ(e,t){let r=_l(["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 HQ(e,t){let r=_l(["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 qQ(e,t,r){let n=[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(${n[0]}, ${n[1]}));
|
|
}
|
|
`;let a=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(${n[0]}, ${n[1]}));
|
|
|
|
int index = resTexRC.x * ${n[1]} + resTexRC.y;
|
|
int r = 2 * (index / ${a});
|
|
int c = imod(index, ${a}) * 2;
|
|
|
|
return ivec2(r, c);
|
|
}
|
|
`}function KQ(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 zl(e){return`offset${e}`}function XQ(e){let t=e.name,r="get"+t.charAt(0).toUpperCase()+t.slice(1),n=jr();return`
|
|
vec4 ${r}() {
|
|
return ${n.texture2D}(${t}, halfCR);
|
|
}
|
|
`}function ZQ(e,t){let r=e.name,n="get"+r.charAt(0).toUpperCase()+r.slice(1);if(e.shapeInfo.isUniform)return`float ${n}() {return ${r};}`;let[a,s]=e.shapeInfo.texShape;if(a===1&&s===1)return`
|
|
float ${n}() {
|
|
return sampleTexture(${r}, halfCR);
|
|
}
|
|
`;let i=zl(r);if(t)return`
|
|
float ${n}() {
|
|
vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], ${i});
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`;let[o,l]=e.shapeInfo.texShape;return`
|
|
float ${n}() {
|
|
vec2 uv = uvFromFlat(${o}, ${l}, ${i});
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`}function YQ(e,t){let r=e.name,n="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape,s=jr();if(t)return`
|
|
vec4 ${n}(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(a[0]/2),Math.ceil(a[1]/2)];return`
|
|
vec4 ${n}(int index) {
|
|
vec2 uv = packedUVfrom1D(
|
|
${i[0]}, ${i[1]}, index);
|
|
return ${s.texture2D}(${r}, uv);
|
|
}
|
|
`}function JQ(e,t){let r=e.name,n="get"+r.charAt(0).toUpperCase()+r.slice(1);if(e.shapeInfo.isUniform)return`
|
|
float ${n}(int index) {
|
|
${kd(e)}
|
|
}
|
|
`;let a=e.shapeInfo.texShape,s=a[0],i=a[1];if(i===1&&s===1)return`
|
|
float ${n}(int index) {
|
|
return sampleTexture(${r}, halfCR);
|
|
}
|
|
`;let o=zl(r);return i===1?t?`
|
|
float ${n}(int index) {
|
|
vec2 uv = vec2(0.5, (float(index + ${o}) + 0.5) / float(${r}TexShape[0]));
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${n}(int index) {
|
|
vec2 uv = vec2(0.5, (float(index + ${o}) + 0.5) / ${s}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:s===1?t?`
|
|
float ${n}(int index) {
|
|
vec2 uv = vec2((float(index + ${o}) + 0.5) / float(${r}TexShape[1]), 0.5);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${n}(int index) {
|
|
vec2 uv = vec2((float(index + ${o}) + 0.5) / ${i}.0, 0.5);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:t?`
|
|
float ${n}(int index) {
|
|
vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index + ${o});
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${n}(int index) {
|
|
vec2 uv = uvFromFlat(${s}, ${i}, index + ${o});
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`}function QQ(e,t){let r=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),s=e.shapeInfo.texShape,i=s[0],o=s[1],l=jr();if(s!=null&&w.arraysEqual(r,s))return t?`
|
|
vec4 ${a}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${n}TexShape[1], ${n}TexShape[0]);
|
|
|
|
return ${l.texture2D}(${n}, uv);
|
|
}
|
|
`:`
|
|
vec4 ${a}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${o}.0, ${i}.0);
|
|
|
|
return ${l.texture2D}(${n}, uv);
|
|
}
|
|
`;if(t)return`
|
|
vec4 ${a}(int row, int col) {
|
|
ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
|
|
int valuesPerRow = int(ceil(float(${n}Shape[1]) / 2.0));
|
|
vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);
|
|
return ${l.texture2D}(${n}, uv);
|
|
}
|
|
`;let u=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)],d=Math.ceil(r[1]/2);return`
|
|
vec4 ${a}(int row, int col) {
|
|
vec2 uv = packedUVfrom2D(${d}, ${u[0]}, ${u[1]}, row, col);
|
|
return ${l.texture2D}(${n}, uv);
|
|
}
|
|
`}function eee(e,t){let r=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),s=e.shapeInfo.texShape;if(s!=null&&w.arraysEqual(r,s)){if(t)return`
|
|
float ${a}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${n}TexShape[1], ${n}TexShape[0]);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let p=s[0],c=s[1];return`
|
|
float ${a}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${c}.0, ${p}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}let{newShape:i,keptDims:o}=w.squeezeShape(r),l=i;if(l.length<r.length){let p=Id(e,l),c=["row","col"];return`
|
|
${wd(p,t)}
|
|
float ${a}(int row, int col) {
|
|
return ${a}(${Sd(c,o)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${a}(int row, int col) {
|
|
int index = round(dot(vec2(row, col), vec2(${r[1]}, 1)));
|
|
${kd(e)}
|
|
}
|
|
`;let u=s[0],d=s[1],h=zl(n);return d===1?t?`
|
|
float ${a}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${h}), vec3(${n}Shape[1], 1, 1));
|
|
vec2 uv = vec2(0.5, (index + 0.5) / float(${n}TexShape[0]));
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${a}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${h}), vec3(${r[1]}, 1, 1));
|
|
vec2 uv = vec2(0.5, (index + 0.5) / ${u}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:u===1?t?`
|
|
float ${a}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${h}), vec3(${n}Shape[1], 1, 1));
|
|
vec2 uv = vec2((index + 0.5) / float(${n}TexShape[1]), 0.5);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${a}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${h}), vec3(${r[1]}, 1, 1));
|
|
vec2 uv = vec2((index + 0.5) / ${d}.0, 0.5);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:t?`
|
|
float ${a}(int row, int col) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${n}Shape[1] + col + ${h};
|
|
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${a}(int row, int col) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${r[1]} + col + ${h};
|
|
vec2 uv = uvFromFlat(${u}, ${d}, index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function tee(e,t){let r=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),s=e.shapeInfo.texShape,i=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];if(r[0]===1){let p=r.slice(1),c=[1,2],f=Id(e,p),m=["b","row","col"];return`
|
|
${NS(f,t)}
|
|
vec4 ${a}(int b, int row, int col) {
|
|
return ${a}(${Sd(m,c)});
|
|
}
|
|
`}let o=jr();if(t)return`
|
|
vec4 ${a}(int b, int row, int col) {
|
|
ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
|
|
int valuesPerRow = int(ceil(float(${n}Shape[2]) / 2.0));
|
|
int texelsInBatch = valuesPerRow * int(ceil(float(${n}Shape[1]) / 2.0));
|
|
vec2 uv = packedUVfrom3D(
|
|
packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);
|
|
return ${o.texture2D}(${n}, uv);
|
|
}
|
|
`;let l=i[0],u=i[1],d=Math.ceil(r[2]/2),h=d*Math.ceil(r[1]/2);return`
|
|
vec4 ${a}(int b, int row, int col) {
|
|
vec2 uv = packedUVfrom3D(
|
|
${l}, ${u}, ${h}, ${d}, b, row, col);
|
|
return ${o.texture2D}(${n}, uv);
|
|
}
|
|
`}function ree(e,t){let r=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),s=r[1]*r[2],i=r[2],{newShape:o,keptDims:l}=w.squeezeShape(r),u=o;if(u.length<r.length){let m=Id(e,u),g=["row","col","depth"];return`
|
|
${wd(m,t)}
|
|
float ${a}(int row, int col, int depth) {
|
|
return ${a}(${Sd(g,l)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${a}(int row, int col, int depth) {
|
|
int index = round(dot(vec3(row, col, depth),
|
|
vec3(${s}, ${i}, 1)));
|
|
${kd(e)}
|
|
}
|
|
`;let d=e.shapeInfo.texShape,h=d[0],p=d[1],c=e.shapeInfo.flatOffset;if(p===s&&c==null)return t?`
|
|
float ${a}(int row, int col, int depth) {
|
|
int stride1 = ${n}Shape[2];
|
|
float texR = float(row);
|
|
float texC = dot(vec2(col, depth), vec2(stride1, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${n}TexShape[1], ${n}TexShape[0]);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${a}(int row, int col, int depth) {
|
|
float texR = float(row);
|
|
float texC = dot(vec2(col, depth), vec2(${i}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${p}.0, ${h}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;if(p===i&&c==null)return t?`
|
|
float ${a}(int row, int col, int depth) {
|
|
float texR = dot(vec2(row, col), vec2(${n}Shape[1], 1));
|
|
float texC = float(depth);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${n}TexShape[1], ${n}TexShape[0]);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${a}(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(${p}.0, ${h}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let f=zl(n);return t?`
|
|
float ${a}(int row, int col, int depth) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int stride0 = ${n}Shape[1] * ${n}Shape[2];
|
|
int stride1 = ${n}Shape[2];
|
|
int index = row * ${s} + col * ${i} + depth + ${f};
|
|
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${a}(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(${h}, ${p}, index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function nee(e,t){let r=e.name,n="get"+r.charAt(0).toUpperCase()+r.slice(1),a=jr();if(t)return`
|
|
vec4 ${n}(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 ${a.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)],u=l[0],d=l[1],h=Math.ceil(s[i-1]/2),p=h*Math.ceil(s[i-2]/2),c="int b, int row, int col",f=`b * ${p} + (row / 2) * ${h} + (col / 2)`;for(let m=2;m<i-1;m++)c=`int b${m}, `+c,p*=s[i-m-1],f=`b${m} * ${p} + `+f;return`
|
|
vec4 ${n}(${c}) {
|
|
int index = ${f};
|
|
int texR = index / ${d};
|
|
int texC = index - texR * ${d};
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${d}, ${u});
|
|
return ${a.texture2D}(${r}, uv);
|
|
}
|
|
`}function aee(e,t){let r=e.shapeInfo.logicalShape,n=e.name,a="get"+n.charAt(0).toUpperCase()+n.slice(1),s=r[3],i=r[2]*s,o=r[1]*i,{newShape:l,keptDims:u}=w.squeezeShape(r);if(l.length<r.length){let A=Id(e,l),x=["row","col","depth","depth2"];return`
|
|
${wd(A,t)}
|
|
float ${a}(int row, int col, int depth, int depth2) {
|
|
return ${a}(${Sd(x,u)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${a}(int row, int col, int depth, int depth2) {
|
|
int index = round(dot(vec4(row, col, depth, depth2),
|
|
vec4(${o}, ${i}, ${s}, 1)));
|
|
${kd(e)}
|
|
}
|
|
`;let d=e.shapeInfo.flatOffset,h=e.shapeInfo.texShape,p=h[0],c=h[1],f=`int stride2 = ${n}Shape[3];`,m=`int stride1 = ${n}Shape[2] * stride2;`,g=`int stride0 = ${n}Shape[1] * stride1;`;if(c===o&&d==null)return t?`
|
|
float ${a}(int row, int col, int depth, int depth2) {
|
|
${f}
|
|
${m}
|
|
float texR = float(row);
|
|
float texC =
|
|
dot(vec3(col, depth, depth2),
|
|
vec3(stride1, stride2, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${n}TexShape[1], ${n}TexShape[0]);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${a}(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, ${p}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;if(c===s&&d==null)return t?`
|
|
float ${a}(int row, int col, int depth, int depth2) {
|
|
float texR = dot(vec3(row, col, depth),
|
|
vec3(${n}Shape[1] * ${n}Shape[2], ${n}Shape[2], 1));
|
|
float texC = float(depth2);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${n}TexShape[1], ${n}TexShape[0]);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${a}(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, ${p}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let y=zl(n);return t?`
|
|
float ${a}(int row, int col, int depth, int depth2) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
${f}
|
|
${m}
|
|
${g}
|
|
int index = row * stride0 + col * stride1 +
|
|
depth * stride2 + depth2;
|
|
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index + ${y});
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${a}(int row, int col, int depth, int depth2) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${o} + col * ${i} +
|
|
depth * ${s} + depth2;
|
|
vec2 uv = uvFromFlat(${p}, ${c}, index + ${y});
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function see(e){let t=e.shapeInfo.logicalShape,r=e.name,n="get"+r.charAt(0).toUpperCase()+r.slice(1),a=t[4],s=t[3]*a,i=t[2]*s,o=t[1]*i,{newShape:l,keptDims:u}=w.squeezeShape(t);if(l.length<t.length){let m=Id(e,l),g=["row","col","depth","depth2","depth3"];return`
|
|
${wd(m)}
|
|
float ${n}(int row, int col, int depth, int depth2, int depth3) {
|
|
return ${n}(${Sd(g,u)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${n}(int row, int col, int depth, int depth2, int depth3) {
|
|
float index = dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${o}, ${i}, ${s}, ${a})) +
|
|
depth3;
|
|
${kd(e)}
|
|
}
|
|
`;let d=e.shapeInfo.flatOffset,h=e.shapeInfo.texShape,p=h[0],c=h[1];if(c===o&&d==null)return`
|
|
float ${n}(int row, int col, int depth, int depth2, int depth3) {
|
|
int texR = row;
|
|
float texC = dot(vec4(col, depth, depth2, depth3),
|
|
vec4(${i}, ${s}, ${a}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${c}.0, ${p}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`;if(c===a&&d==null)return`
|
|
float ${n}(int row, int col, int depth, int depth2, int depth3) {
|
|
float texR = dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${t[1]*t[2]*t[3]},
|
|
${t[2]*t[3]}, ${t[3]}, 1));
|
|
int texC = depth3;
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${c}.0, ${p}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`;let f=zl(r);return`
|
|
float ${n}(int row, int col, int depth, int depth2, int depth3) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${o} + col * ${i} + depth * ${s} +
|
|
depth2 * ${a} + depth3 + ${f};
|
|
vec2 uv = uvFromFlat(${p}, ${c}, index);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`}function iee(e){let t=e.shapeInfo.logicalShape,r=e.name,n="get"+r.charAt(0).toUpperCase()+r.slice(1),{newShape:a,keptDims:s}=w.squeezeShape(t);if(a.length<t.length){let g=Id(e,a),y=["row","col","depth","depth2","depth3","depth4"];return`
|
|
${wd(g)}
|
|
float ${n}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
return ${n}(${Sd(y,s)});
|
|
}
|
|
`}let i=t[5],o=t[4]*i,l=t[3]*o,u=t[2]*l,d=t[1]*u;if(e.shapeInfo.isUniform)return`
|
|
float ${n}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
int index = round(dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${d}, ${u}, ${l}, ${o})) +
|
|
dot(
|
|
vec2(depth3, depth4),
|
|
vec2(${i}, 1)));
|
|
${kd(e)}
|
|
}
|
|
`;let h=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,c=p[0],f=p[1];if(f===d&&h==null)return`
|
|
float ${n}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
int texR = row;
|
|
float texC = dot(vec4(col, depth, depth2, depth3),
|
|
vec4(${u}, ${l}, ${o}, ${i})) +
|
|
float(depth4);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${f}.0, ${c}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`;if(f===i&&h==null)return`
|
|
float ${n}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
float texR = dot(vec4(row, col, depth, depth2),
|
|
vec4(${t[1]*t[2]*t[3]*t[4]},
|
|
${t[2]*t[3]*t[4]},
|
|
${t[3]*t[4]},
|
|
${t[4]})) + float(depth3);
|
|
int texC = depth4;
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${f}.0, ${c}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`;let m=zl(r);return`
|
|
float ${n}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${d} + col * ${u} + depth * ${l} +
|
|
depth2 * ${o} + depth3 * ${i} + depth4 + ${m};
|
|
vec2 uv = uvFromFlat(${c}, ${f}, index);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`}function kd(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 oee(e,t){let r=e.name,n=r.charAt(0).toUpperCase()+r.slice(1),a="get"+n+"AtOutCoords",s=e.shapeInfo.logicalShape.length,i=t.logicalShape.length,o=TS(e.shapeInfo.logicalShape,t.logicalShape),l=gt(i),u=i-s,d,h=["x","y","z","w","u","v"];s===0?d="":i<2&&o.length>=1?d="coords = 0;":d=o.map(g=>`coords.${h[g+u]} = 0;`).join(`
|
|
`);let p="";i<2&&s>0?p="coords":p=e.shapeInfo.logicalShape.map((g,y)=>`coords.${h[y+u]}`).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 ${a}() {
|
|
${l} coords = getOutputCoords();
|
|
${d}
|
|
vec4 outputValue = get${n}(${p});
|
|
${c}
|
|
}
|
|
`}function lee(e,t){let r=e.name,n=r.charAt(0).toUpperCase()+r.slice(1),a="get"+n+"AtOutCoords",s=t.texShape,i=e.shapeInfo.texShape,o=e.shapeInfo.logicalShape.length,l=t.logicalShape.length;if(!e.shapeInfo.isUniform&&o===l&&e.shapeInfo.flatOffset==null&&w.arraysEqual(i,s))return`
|
|
float ${a}() {
|
|
return sampleTexture(${r}, resultUV);
|
|
}
|
|
`;let u=gt(l),d=TS(e.shapeInfo.logicalShape,t.logicalShape),h=l-o,p,c=["x","y","z","w","u","v"];o===0?p="":l<2&&d.length>=1?p="coords = 0;":p=d.map(m=>`coords.${c[m+h]} = 0;`).join(`
|
|
`);let f="";return l<2&&o>0?f="coords":f=e.shapeInfo.logicalShape.map((m,g)=>`coords.${c[g+h]}`).join(", "),`
|
|
float ${a}() {
|
|
${u} coords = getOutputCoords();
|
|
${p}
|
|
return get${n}(${f});
|
|
}
|
|
`}function gt(e){if(e<=1)return"int";if(e===2)return"ivec2";if(e===3)return"ivec3";if(e===4)return"ivec4";if(e===5)return"ivec5";if(e===6)return"ivec6";throw Error(`GPU for rank ${e} is not yet supported`)}function db(e,t,r){let{newShape:n,keptDims:a}=w.squeezeShape(t),s=t.length,i=e&&s===3&&t[0]===1,o=i?t.slice(1):n,l=!e&&s>1&&!w.arraysEqual(t,r)&&n.length<s||i;return{useSqueezeShape:l,uniformShape:l?o:t,keptDims:a}}function Id(e,t){let r=JSON.parse(JSON.stringify(e));return r.shapeInfo.logicalShape=t,r}function Sd(e,t){return t.map(r=>e[r]).join(", ")}function uee(e,t,r,n){let a=r.map((d,h)=>{let p={logicalShape:d.shape,texShape:d.isUniform?null:d.texData.texShape,isUniform:d.isUniform,isPacked:d.isUniform?!1:d.texData.isPacked,flatOffset:null};return d.texData!=null&&d.texData.slice!=null&&d.texData.slice.flatOffset>0&&(p.flatOffset=d.texData.slice.flatOffset),{name:t.variableNames[h],shapeInfo:p}}),s=a.map(d=>d.shapeInfo),i={logicalShape:n.shape,texShape:n.texData.texShape,isUniform:!1,isPacked:n.texData.isPacked,flatOffset:null},o=NQ(a,i,t),l=aS(e.gl,o),u=e.createProgram(l);return Y().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:l,source:o,webGLProgram:u,inShapeInfos:s,outShapeInfo:i,uniformLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,inShapesLocations:null,inTexShapesLocations:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:{program:t,fragmentShader:l,source:o,webGLProgram:u,inShapeInfos:s,outShapeInfo:i,...ES(e,t,u)}}function ES(e,t,r){let n={},a={},s={},i=[],o,l,u,d=null,h=null;h=e.getUniformLocation(r,"NAN",!1),Y().getNumber("WEBGL_VERSION")===1&&(d=e.getUniformLocation(r,"INFINITY",!1));let p=!1;for(let c=0;c<t.variableNames.length;c++){let f=t.variableNames[c];n[f]=e.getUniformLocation(r,f,p),n[`offset${f}`]=e.getUniformLocation(r,`offset${f}`,p),t.enableShapeUniforms&&(a[`${f}Shape`]=e.getUniformLocation(r,`${f}Shape`,p),s[`${f}TexShape`]=e.getUniformLocation(r,`${f}TexShape`,p))}return t.enableShapeUniforms&&(o=e.getUniformLocation(r,"outShape",p),u=e.getUniformLocation(r,"outShapeStrides",p),l=e.getUniformLocation(r,"outTexShape",p)),t.customUniforms&&t.customUniforms.forEach((c,f)=>{i[f]=e.getUniformLocation(r,c.name,p)}),{uniformLocations:n,customUniformLocations:i,infLoc:d,nanLoc:h,inShapesLocations:a,inTexShapesLocations:s,outShapeLocation:o,outShapeStridesLocation:u,outTexShapeLocation:l}}function Mv(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,n)=>{let a=r.logicalShape,s=t[n],i=s.shape;if(!w.arraysEqual(a,i))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${a} 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 dee(e,t,r,n,a){t.program.enableShapeUniforms||(Mv(t.inShapeInfos,r),Mv([t.outShapeInfo],[n]));let s=n.texData.texture,i=n.texData.texShape;n.texData.isPacked?e.setOutputPackedMatrixTexture(s.texture,i[0],i[1]):e.setOutputMatrixTexture(s.texture,i[0],i[1]),e.setProgram(t.webGLProgram),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,u)=>{let d=t.program.variableNames[u],h=t.uniformLocations[d],p=t.uniformLocations[`offset${d}`],c=t.inShapesLocations[`${d}Shape`],f=t.inTexShapesLocations[`${d}TexShape`];if(c){let{uniformShape:m}=db(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]),h!=null){if(l.isUniform){if(w.sizeFromShape(l.shape)<2)e.gl.uniform1f(h,l.uniformValues[0]);else{let m=l.uniformValues;m instanceof Float32Array||(m=new Float32Array(m)),e.gl.uniform1fv(h,m)}return}l.texData.slice!=null&&p!=null&&e.gl.uniform1i(p,l.texData.slice.flatOffset),e.setInputMatrixTexture(l.texData.texture.texture,h,u)}});let o=t.outShapeLocation;if(o)switch(n.shape.length){case 1:e.gl.uniform1iv(o,new Int32Array(n.shape));break;case 2:e.gl.uniform2iv(o,new Int32Array(n.shape));break;case 3:e.gl.uniform3iv(o,new Int32Array(n.shape));break;case 4:e.gl.uniform4iv(o,new Int32Array(n.shape));break;default:break}if(t.outShapeStridesLocation){let l=w.computeStrides(n.shape);switch(n.shape.length){case 2:e.gl.uniform1iv(t.outShapeStridesLocation,new Int32Array(l));break;case 3:e.gl.uniform2iv(t.outShapeStridesLocation,new Int32Array(l));break;case 4:e.gl.uniform3iv(t.outShapeStridesLocation,new Int32Array(l));break;default:break}}t.outTexShapeLocation&&e.gl.uniform2i(t.outTexShapeLocation,n.texData.texShape[0],n.texData.texShape[1]),t.program.customUniforms&&a&&t.program.customUniforms.forEach((l,u)=>{let d=t.customUniformLocations[u],h=a[u];if(l.type==="float")e.gl.uniform1fv(d,h);else if(l.type==="vec2")e.gl.uniform2fv(d,h);else if(l.type==="vec3")e.gl.uniform3fv(d,h);else if(l.type==="vec4")e.gl.uniform4fv(d,h);else if(l.type==="int")e.gl.uniform1iv(d,h);else if(l.type==="ivec2")e.gl.uniform2iv(d,h);else if(l.type==="ivec3")e.gl.uniform3iv(d,h);else if(l.type==="ivec4")e.gl.uniform4iv(d,h);else throw Error(`uniform type ${l.type} is not supported yet.`)}),e.executeProgram()}function pee(e,t,r){let n="";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:u,uniformShape:d,keptDims:h}=db(e.packedInputs,i.shape,l),p="",c="",f="";if(d.length===1&&e.packedInputs){let v=[Math.ceil(l[0]/2),Math.ceil(l[1]/2)];p=`${v[0]>1}_${v[1]>1}`}else if(d.length===2&&!e.packedInputs)c=`${d[0]>1}_${d[1]>1}`;else if(d.length>2&&!e.packedInputs){let v=w.computeStrides(d);f=`${v[0]===l[1]}_${v[v.length-1]===l[1]}`}let m=i.shape.length,g=d.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||d.length>2?"":`${l[0]>1}_${l[1]>1}`;n+=`${m}_${x}_${u?h:""}_${d.length}_${y}_${A}_${g}_${p}_${c}_${f}_${b}_${o}`}else{let l=i.isUniform?"uniform":i.texData.texShape;n+=`${i.shape}_${l}_${o}`}});let a=e.userCode,s=e.constructor.name;return s+="_"+n+"_"+a+`${Y().getNumber("WEBGL_VERSION")}`,s}function ln(e){return Y().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4}var hee=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=jr();this.outputShape=e,this.enableShapeUniforms=ln(this.outputShape.length),this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${this.enableShapeUniforms?x0(["r","c","d"],e):_l(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
|
|
int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
for (int i=0; i<4; i++) {
|
|
int flatIndex = index + i;
|
|
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
|
|
result[i] = getA(rc.x, rc.y, rc.z);
|
|
}
|
|
|
|
${t.output} = result;
|
|
}
|
|
`}},cee=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=jr();this.outputShape=e,this.enableShapeUniforms=ln(this.outputShape.length),this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${this.enableShapeUniforms?x0(["r","c","d"],e):_l(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx * vec2(texShape[0], texShape[1]));
|
|
int index = 4 * (resTexRC.x * texShape[1] + resTexRC.y);
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
for (int i=0; i<4; i++) {
|
|
int flatIndex = index + i;
|
|
ivec3 rc = outCoordsFromFlatIndex(flatIndex);
|
|
result[i] = getChannel(getA(rc.x, rc.y, rc.z), vec2(rc.y, rc.z));
|
|
}
|
|
|
|
${t.output} = result;
|
|
}
|
|
`}},fee=class{constructor(e){this.variableNames=["A"],this.outTexUsage=3;let t=jr();this.outputShape=e,this.userCode=`
|
|
${SS}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}},mee=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=3;let t=jr();this.outputShape=e,this.userCode=`
|
|
${SS}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}},gee=class{constructor(e,t=!1){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];let r=jr();this.outputShape=e,this.enableShapeUniforms=ln(this.outputShape.length);let n="result";t&&(n="floor(result * 255. + 0.5)"),this.userCode=`
|
|
${this.enableShapeUniforms?ub():lb(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(${n}, 0., 0., 0.);
|
|
}
|
|
`}},yee=class{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let r=jr();this.outputShape=e,this.enableShapeUniforms=ln(this.outputShape.length);let n="",a="result";t&&(a="floor(result * 255. + 0.5)");for(let s=0;s<=1;s++)for(let i=0;i<=1;i++){let o=s*2+i;n+=`
|
|
localCoords = coords;
|
|
if(localCoords[2] + ${i} < ${this.enableShapeUniforms?"outShape[2]":`${e[2]}`}) {
|
|
localCoords[2] += ${i};
|
|
if (localCoords[1] + ${s} < ${this.enableShapeUniforms?"outShape[1]":`${e[1]}`}) {
|
|
localCoords[1] += ${s};
|
|
|
|
flatIndex = getFlatIndex(localCoords);
|
|
offset = imod(flatIndex, 4);
|
|
|
|
flatIndex = idiv(flatIndex, 4, 1.);
|
|
|
|
int r = flatIndex / texShape[1];
|
|
int c = imod(flatIndex, texShape[1]);
|
|
vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
|
|
values = ${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?ub():lb(e)}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
|
|
vec4 result = vec4(0.);
|
|
int flatIndex, r, c, offset;
|
|
ivec3 localCoords;
|
|
vec2 uv;
|
|
vec4 values;
|
|
|
|
${n}
|
|
|
|
${r.output} = ${a};
|
|
}
|
|
`}},RS={};Le(RS,{bindVertexProgramAttributeStreams:()=>LS,createBufferFromOutputTexture:()=>VS,createFloat16MatrixTexture:()=>_S,createFloat16PackedMatrixTexture:()=>DS,createFloat32MatrixTexture:()=>PS,createIndexBuffer:()=>$S,createPackedMatrixTexture:()=>OS,createUnsignedBytesMatrixTexture:()=>zS,createVertexBuffer:()=>FS,createVertexShader:()=>MS,downloadByteEncodedFloatMatrixFromOutputTexture:()=>GS,downloadFloat32MatrixFromBuffer:()=>US,downloadMatrixFromPackedOutputTexture:()=>HS,downloadPackedMatrixFromBuffer:()=>jS,getInternalFormatForFloat16MatrixTexture:()=>hb,getInternalFormatForFloat16PackedMatrixTexture:()=>mb,getInternalFormatForFloat32MatrixTexture:()=>pb,getInternalFormatForPackedMatrixTexture:()=>fb,getInternalFormatForUnsignedBytesMatrixTexture:()=>cb,uploadDenseMatrixToTexture:()=>BS,uploadPixelDataToTexture:()=>WS});function MS(e){let t=jr(),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 nS(e,r)}function FS(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 oS(e,t)}function $S(e){let t=new Uint16Array([0,1,2,2,1,3]);return lS(e,t)}function zh(e,t,r,n,a,s){dS(t,r);let i=uS(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,n,t,r,0,a,s,null)):we(e,()=>e.texStorage2D(o,1,n,t,r)),we(e,()=>e.bindTexture(e.TEXTURE_2D,null)),{texture:i,texShape:[r,t]}}function pb(e){return e.internalFormatFloat}function PS(e,t,r,n){let[a,s]=_h(t,r);return zh(e,a,s,pb(n),n.textureFormatFloat,e.FLOAT)}function hb(e){return e.internalFormatHalfFloat}function _S(e,t,r,n){let[a,s]=_h(t,r);return zh(e,a,s,hb(n),n.textureFormatFloat,n.textureTypeHalfFloat)}function cb(e){return e.downloadTextureFormat}function zS(e,t,r,n){let[a,s]=_h(t,r);return zh(e,a,s,cb(n),e.RGBA,e.UNSIGNED_BYTE)}function fb(e){return e.internalFormatPackedFloat}function OS(e,t,r,n){let[a,s]=bd(t,r);return zh(e,a,s,fb(n),e.RGBA,e.FLOAT)}function mb(e){return e.internalFormatPackedHalfFloat}function DS(e,t,r,n){let[a,s]=bd(t,r);return zh(e,a,s,mb(n),e.RGBA,n.textureTypeHalfFloat)}function LS(e,t,r){return we(e,()=>e.bindBuffer(e.ARRAY_BUFFER,r)),Ky(e,t,"clipSpacePos",r,3,20,0)&&Ky(e,t,"uv",r,2,20,12)}function BS(e,t,r,n,a,s){we(e,()=>e.bindTexture(e.TEXTURE_2D,t));let i,o,l;a instanceof Uint8Array?(i=new Uint8Array(r*n*4),o=e.UNSIGNED_BYTE,l=e.RGBA):(i=new Float32Array(r*n*4),o=e.FLOAT,l=s.internalFormatPackedFloat),i.set(a),Y().getNumber("WEBGL_VERSION")===2?we(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,r,n,e.RGBA,o,i)):we(e,()=>e.texImage2D(e.TEXTURE_2D,0,l,r,n,0,e.RGBA,o,i)),we(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function WS(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 VS(e,t,r,n){let a=e.createBuffer();we(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,a));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)),a}function US(e,t,r){let n=e,a=new Float32Array(r);return n.bindBuffer(n.PIXEL_PACK_BUFFER,t),n.getBufferSubData(n.PIXEL_PACK_BUFFER,0,a),n.bindBuffer(n.PIXEL_PACK_BUFFER,null),a}function GS(e,t,r,n){let[a,s]=_h(t,r),i=4,o=new Uint8Array(cQ(t*r,i));return we(e,()=>e.readPixels(0,0,a,s,n.downloadTextureFormat,e.UNSIGNED_BYTE,o)),new Float32Array(o.buffer)}function jS(e,t,r,n,a,s,i,o){let l=e,u=new Float32Array(fQ(s,i));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,u),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),u}function HS(e,t,r){let n=new Float32Array(t*r*4);return we(e,()=>e.readPixels(0,0,r,t,e.RGBA,e.FLOAT,n)),n}var Au=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,A0(t,e)):this.gl=ya(t);let r="WEBGL_color_buffer_float",n="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),Y().getNumber("WEBGL_VERSION")===1){let a="OES_texture_float",s="OES_texture_half_float";if(this.textureFloatExtension=Sp(this.gl,a),Nn(this.gl,s))this.textureHalfFloatExtension=Sp(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),Nn(this.gl,n))this.colorBufferHalfFloatExtension=Sp(this.gl,n);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",Nn(this.gl,r))this.colorBufferFloatExtension=this.gl.getExtension(r);else if(Nn(this.gl,n))this.colorBufferHalfFloatExtension=this.gl.getExtension(n);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=FS(this.gl),this.indexBuffer=$S(this.gl),this.framebuffer=pS(this.gl),this.textureConfig=ib(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(),PS(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),_S(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),zS(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),WS(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,r,n){this.throwIfDisposed(),BS(this.gl,e,t,r,n,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),DS(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),OS(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(Xy(this.gl,this.framebuffer),this.outputTexture=null),we(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,r){return this.downloadMatrixDriver(e,()=>GS(this.gl,t,r,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,r,n,a,s){return jS(this.gl,e,t,r,n,a,s,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return US(this.gl,e,t)}createBufferFromTexture(e,t,r){this.bindTextureToFrameBuffer(e);let n=VS(this.gl,t,r,this.textureConfig);return this.unbindTextureToFrameBuffer(),n}createAndWaitForFence(){let e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,r;if(Y().getBool("WEBGL_FENCE_API_ENABLED")){let n=e,a=n.fenceSync(n.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),r=()=>{let s=n.clientWaitSync(a,0,0);return s===n.ALREADY_SIGNALED||s===n.CONDITION_SATISFIED},t=a}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,()=>HS(this.gl,t,r))}createProgram(e){this.throwIfDisposed();let t=this.gl;this.vertexShader==null&&(this.vertexShader=MS(t));let r=sS(t);return we(t,()=>t.attachShader(r,this.vertexShader)),we(t,()=>t.attachShader(r,e)),iS(t,r),this.debug&&af(t,r),this.vertexAttrsAreBound||(this.setProgram(r),this.vertexAttrsAreBound=LS(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&&af(this.gl,this.program),we(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,r=!0){return this.throwIfDisposed(),r?cS(this.gl,e,t):fS(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(),mS(this.gl,e,t,r)}setOutputMatrixTexture(e,t,r){this.setOutputMatrixTextureDriver(e,r,t)}setOutputPackedMatrixTexture(e,t,r){this.throwIfDisposed();let[n,a]=bd(t,r);this.setOutputMatrixTextureDriver(e,n,a)}setOutputMatrixWriteRegion(e,t,r,n){this.setOutputMatrixWriteRegionDriver(r,e,n,t)}setOutputPackedMatrixWriteRegion(e,t,r,n){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){this.program!=null&&af(this.gl,this.program),Tp(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=Sp(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,n=this.getQueryTimerExtensionWebGL2(),a=r.createQuery();return r.beginQuery(n.TIME_ELAPSED_EXT,a),a}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,n=this.getQueryTimerExtensionWebGL2(),a=r.getQueryParameter(e,r.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),a&&!this.disjoint}else{let r=this.getQueryTimerExtensionWebGL1(),n=r.getQueryObjectEXT(e,r.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),n&&!this.disjoint}}pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){let e=Aee(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(),sf(this.gl,e,this.framebuffer),this.debug&&Tp(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(sf(this.gl,this.outputTexture,this.framebuffer),this.debug&&Tp(this.gl)):Xy(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);let r=t();return this.unbindTextureToFrameBuffer(),r}setOutputMatrixTextureDriver(e,t,r){this.throwIfDisposed();let n=this.gl;sf(n,e,this.framebuffer),this.debug&&Tp(n),this.outputTexture=e,we(n,()=>n.viewport(0,0,t,r)),we(n,()=>n.scissor(0,0,t,r))}setOutputMatrixWriteRegionDriver(e,t,r,n){this.throwIfDisposed(),we(this.gl,()=>this.gl.scissor(e,t,r,n))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(this.program==null)throw new Error("No GPU program is currently set.")}};function Aee(e){let t=0;for(;t<e.length&&e[t]();++t);return t-1}var{addImpl:xee,bincountImpl:qS,bincountReduceImpl:bee,ceilImpl:vee,concatImpl:wee,equalImpl:kee,expImpl:Iee,expm1Impl:See,floorImpl:Tee,gatherNdImpl:Nee,gatherV2Impl:Cee,greaterImpl:Eee,greaterEqualImpl:Ree,lessImpl:Mee,lessEqualImpl:Fee,linSpaceImpl:$ee,logImpl:Pee,maxImpl:_ee,maximumImpl:zee,minimumImpl:Oee,multiplyImpl:Dee,negImpl:Lee,notEqualImpl:Bee,prodImpl:Wee,rangeImpl:Vee,rsqrtImpl:Uee,sigmoidImpl:Gee,simpleAbsImpl:KS,sliceImpl:jee,sparseFillEmptyRowsImpl:Hee,sparseReshapeImpl:qee,sparseSegmentReductionImpl:XS,sqrtImpl:Kee,stridedSliceImpl:Xee,stringNGramsImpl:Zee,stringSplitImpl:Yee,stringToHashBucketFastImpl:Jee,subImpl:Qee,tileImpl:ete,topKImpl:tte,transposeImpl:gb,uniqueImpl:rte}=g0;function ZS(e,t){return["x","y","z","w","u","v"].slice(0,t).map(r=>`${e}.${r}`)}function Lr(e,t){return t===1?[e]:ZS(e,t)}function nte(e,t){if(e===1)return"rc";let r="";for(let n=0;n<e;n++)r+=t[n],n<e-1&&(r+=",");return r}var ate=class{constructor(e){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.enableShapeUniforms=ln(this.outputShape.length),this.rank===0)this.userCode=`
|
|
void main() {
|
|
setOutput(vec4(getA(), 0., 0., 0.));
|
|
}
|
|
`;else{let t=Lr("rc",this.rank),r=gt(this.rank),n=this.getOutOfBoundsCondition(t),a=this.getSetup(t),s=this.getOutput(t);this.userCode=`
|
|
void main() {
|
|
${r} rc = getOutputCoords();
|
|
|
|
if(${n}) {
|
|
setOutput(vec4(0));
|
|
} else {
|
|
${a}
|
|
|
|
setOutput(vec4(${s}));
|
|
}
|
|
}
|
|
`}}getSourceCoordsArr(e){let t=[];for(let r=0;r<=1;r++)for(let n=0;n<=1;n++){let a=`${r===0?"r":"rp1"}, ${n===0?"c":"cp1"}`;for(let s=2;s<this.rank;s++)a=`${e[e.length-1-s]},`+a;t.push(a)}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],n=this.enableShapeUniforms?`outShape[${this.rank} - 2]`:this.outputShape[this.rank-2];return`
|
|
int r = ${t[0]};
|
|
int c = ${t[1]};
|
|
int rp1 = r + 1;
|
|
int cp1 = c + 1;
|
|
|
|
bool cEdge = cp1 >= ${r};
|
|
bool rEdge = rp1 >= ${n};
|
|
`}getOutput(e){let t=this.getSourceCoordsArr(e);return this.rank===1?`getA(rc), (rc + 1 >= ${this.enableShapeUniforms?"outShape":this.outputShape[0]} ? 0. : getA(rc + 1)), 0, 0`:`getA(${t[0]}),
|
|
cEdge ? 0. : getA(${t[1]}),
|
|
rEdge ? 0. : getA(${t[2]}),
|
|
rEdge || cEdge ? 0. : getA(${t[3]})`}},YS=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=ln(this.outputShape.length);let r="";for(let n=0;n<4;n++){let a="thisRC = rc;";n%2===1&&(a+="thisRC.z += 1;"),n>1&&(a+="thisRC.y += 1;"),r+=`
|
|
${a}
|
|
${n>0?"if(thisRC.y < rows && thisRC.z < cols){":""}
|
|
int flatIndex = getFlatIndex(thisRC);
|
|
|
|
ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex);
|
|
vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z));
|
|
|
|
result[${n}] =
|
|
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
|
|
${n>0?"}":""}
|
|
`}this.userCode=`
|
|
${ste(t,this.enableShapeUniforms)}
|
|
${this.enableShapeUniforms?ub():lb(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 ste(e,t){return`
|
|
ivec3 inputCoordsFromReshapedOutCoords(int index) {
|
|
${t?TQ(["r","c","d"],"inputShape"):_l(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`}var ite=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 n=$v(t,r),a=Pv(e,n,r);a in this.freeTextures||(this.freeTextures[a]=[]),a in this.usedTextures||(this.usedTextures[a]=[]);let s=Fv(e,n,this.gpgpu.gl,this.gpgpu.textureConfig,r);if(this.freeTextures[a].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=s,this.log();let o=this.freeTextures[a].shift();return this.usedTextures[a].push(o),o}let i;return n===3?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):n===4?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):n===1?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):n===0?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):n===2&&(i=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[a].push(i),this.numUsedTextures++,this._numBytesAllocated+=s,this.log(),i}releaseTexture(e,t,r,n){if(this.freeTextures==null)return;let a=$v(r,n),s=Pv(t,a,n);s in this.freeTextures||(this.freeTextures[s]=[]);let i=Fv(t,a,this.gpgpu.gl,this.gpgpu.textureConfig,n),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],u=l.indexOf(e);if(u<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l.splice(u,1),this.log()}log(){if(!this.logEnabled)return;let e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);let t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures!=null){for(let e in this.freeTextures)this.freeTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});for(let e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}};function ote(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 Fv(e,t,r,n,a){let s=lte(t,n),i;if(a){let[l,u]=bd(e[0],e[1]);i=l*u}else{let[l,u]=_h(e[0],e[1]);i=l*u}let o=ote(r,s);return i*o}function lte(e,t){switch(e){case 3:return fb(t);case 4:return mb(t);case 1:return pb(t);case 0:return hb(t);case 2:return cb(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function ute(e){return Y().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?3:1:e?4:0}function $v(e,t){if(e===1)return 3;if(e===0||e==null)return ute(t);if(e===3||e===2)return 2;throw new Error(`Unknown logical texture type ${e}`)}function Pv(e,t,r){return`${e[0]}_${e[1]}_${t}_${r}`}var Ka=class{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=ln(this.outputShape.length),this.userCode=`
|
|
float unaryOperation(float x) {
|
|
${t}
|
|
}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
float y = unaryOperation(x);
|
|
|
|
setOutput(y);
|
|
}
|
|
`}},Xn="if (isnan(x)) return x;",dte="return x;",_v="return abs(x);",pte="return (x >= 0.0) ? x : (exp(x) - 1.0);",hte=Xn+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,cte=Xn+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,ou="return x;",fte="return 1.0 / (1.0 + exp(-1.0 * x));",mte="return x;",gte=`
|
|
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;
|
|
`,yte=`
|
|
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;
|
|
`,Ate=`
|
|
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;
|
|
`,xte="return 1.0 / (1.0 + exp(-1.0 * x));",Io=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=ln(this.outputShape.length),this.userCode=`
|
|
vec4 unaryOperation(vec4 x) {
|
|
${t}
|
|
}
|
|
|
|
void main() {
|
|
vec4 x = getAAtOutCoords();
|
|
vec4 y = unaryOperation(x);
|
|
|
|
setOutput(y);
|
|
}
|
|
`}},bte=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=ln(this.outputShape.length);let t=e.length,r=Lr("rc",t),n=gt(t),a=nte(t,r),s=r.slice(-2),i=t<=1?"rc":`vec2(${s.join(",")})`;this.userCode=`
|
|
void main() {
|
|
${n} rc = getOutputCoords();
|
|
vec4 packedInput = getA(${a});
|
|
|
|
setOutput(getChannel(packedInput, ${i}));
|
|
}
|
|
`}},vte=qn.whereImpl,wte=1e-7,kte=1e-4,oy={};function Ite(e){return e in oy||(oy[e]={}),oy[e]}var Ste=Y().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),Tte=600;function Nte(){return Y().global.screen==null?1024:Y().global.screen.height*Y().global.screen.width*window.devicePixelRatio*Tte/1024/1024}var JS=class extends $u{constructor(e){if(super(),this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.pendingDeletes=0,this.disposed=!1,!Y().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");let t;if(e!=null){if(e instanceof Au)t=e;else{let r=ya(Y().getNumber("WEBGL_VERSION"),e);t=new Au(r)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{let r=ya(Y().getNumber("WEBGL_VERSION"));t=new Au(r),this.binaryCache=Ite(Y().getNumber("WEBGL_VERSION")),this.gpgpuCreatedLocally=!0}this.gpgpu=t,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new ite(this.gpgpu),this.numMBBeforeWarning=Nte(),this.texData=new qp(this,nr())}nextDataId(){return JS.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 n={id:this.nextDataId()};return this.texData.set(n,{shape:t,dtype:r,values:e,usage:1,refCount:1}),n}refCount(e){return this.texData.has(e)?this.texData.get(e).refCount:0}incRef(e){let t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){let t=this.texData.get(e);t.refCount--}}move(e,t,r,n,a){if(Y().getBool("DEBUG")&&this.checkNumericalProblems(t),n==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:r,dtype:n,values:t,usage:1,refCount:a})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){let t=this.texData.get(e),{values:r,dtype:n,complexTensorInfos:a,slice:s,shape:i,isPacked:o}=t;if(s!=null){let h;o?h=new Io(i,ou):h=new Ka(i,ou);let p=this.runWebGLProgram(h,[{dataId:e,shape:i,dtype:n}],n),c=this.readSync(p.dataId);return this.disposeIntermediateTensorInfo(p),c}if(r!=null)return this.convertAndCacheOnCPU(e);if(n==="string")return r;let l=this.activeTimers!=null,u;l&&(u=w.now());let d;if(n==="complex64"){let h=this.readSync(a.real.dataId),p=this.readSync(a.imag.dataId);d=N.mergeRealAndImagArrays(h,p)}else d=this.getValuesFromTexture(e);return l&&(this.downloadWaitMs+=w.now()-u),this.convertAndCacheOnCPU(e,d)}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:n,slice:a,dtype:s,complexTensorInfos:i,isPacked:o}=t;if(a!=null){let c;o?c=new Io(n,ou):c=new Ka(n,ou);let f=this.runWebGLProgram(c,[{dataId:e,shape:n,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,u;if(s!=="complex64"&&Y().get("WEBGL_BUFFER_SUPPORTED")){u=this.decode(e);let c=this.texData.get(u.dataId);l=this.gpgpu.createBufferFromTexture(c.texture.texture,...Yc(n))}this.pendingRead.set(e,[]),s!=="complex64"&&await this.gpgpu.createAndWaitForFence();let d;if(s==="complex64"){let c=await Promise.all([this.read(i.real.dataId),this.read(i.imag.dataId)]),f=c[0],m=c[1];d=N.mergeRealAndImagArrays(f,m)}else if(l==null)d=this.getValuesFromTexture(e);else{let c=w.sizeFromShape(n);d=this.gpgpu.downloadFloat32MatrixFromBuffer(l,c)}if(u!=null&&this.disposeIntermediateTensorInfo(u),l!=null){let c=this.gpgpu.gl;we(c,()=>c.deleteBuffer(l))}let h=this.convertAndCacheOnCPU(e,d),p=this.pendingRead.get(e);return this.pendingRead.delete(e),p.forEach(c=>c(h)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&nr().removeDataId(e,this),this.pendingDeletes--),h}readToGPU(e,t={}){let r=this.texData.get(e),{values:n,shape:a,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 p;o?p=new Io(a,ou):p=new Ka(a,ou);let c=this.runWebGLProgram(p,[{dataId:e,shape:a,dtype:i}],i),f=this.readToGPU(c,t);return this.disposeIntermediateTensorInfo(c),f}if(l==null)throw n!=null?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");let u=this.decode(e,t.customTexShape),d=nr().makeTensorFromDataId(u.dataId,u.shape,u.dtype),h=this.texData.get(u.dataId);return{tensorRef:d,...h.texture}}bufferSync(e){let t=this.readSync(e.dataId),r=t;if(e.dtype==="string")try{r=t.map(n=>w.decodeString(n))}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return We(e.shape,e.dtype,r)}checkNumericalProblems(e){if(e!=null)for(let t=0;t<e.length;t++){let r=e[t];if(!tS(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:n}=this.texData.get(e),a=w.sizeFromShape(t);if(Y().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){let h=this.decode(e),p=this.texData.get(h.dataId),c=this.gpgpu.downloadMatrixFromPackedTexture(p.texture.texture,...Yc(t)).subarray(0,a);return this.disposeIntermediateTensorInfo(h),c}let s=Y().getBool("WEBGL_PACK")&&n===!0,i=s?of(t):t,o=s?new mee(i):new fee(i),l=this.runWebGLProgram(o,[{shape:i,dtype:r,dataId:e}],"float32"),u=this.texData.get(l.dataId),d=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(u.texture.texture,u.texShape[0],u.texShape[1]).subarray(0,a);return this.disposeIntermediateTensorInfo(l),d}timerAvailable(){return Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}time(e){let t=this.activeTimers,r=[],n=!1;this.programTimersStack==null?(this.programTimersStack=r,n=!0):this.activeTimers.push(r),this.activeTimers=r,e();let a=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,n&&(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(a);i.kernelMs=w.sum(o),i.getExtraProfileInfo=()=>o.map((l,u)=>({name:s[u],ms:l})).map(l=>`${l.name}: ${l.ms}`).join(", ")}else i.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,i})()}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return 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:n,usage:a,isPacked:s,slice:i}=this.texData.get(e),o=i&&i.origDataId||e,l=this.dataRefCount.get(o);l>1?this.dataRefCount.set(o,l-1):(this.dataRefCount.delete(o),t!=null&&(this.numBytesInGPU-=this.computeBytes(n,r),this.textureManager.releaseTexture(t,n,a,s)));let u=this.texData.get(e);u.texture=null,u.texShape=null,u.isPacked=!1,u.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture.texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=Ste){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 vte(e.shape,t)}packedUnaryOp(e,t,r){let n=new Io(e.shape,t),a=this.compileAndRun(n,[e],r);return nr().makeTensorFromDataId(a.dataId,a.shape,a.dtype)}abs(e){if(this.shouldExecuteOnCPU([e])&&e.dtype!=="complex64"){let n=KS(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,n)}if(Y().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,_v,e.dtype);let t=new Ka(e.shape,_v),r=this.compileAndRun(t,[e]);return nr().makeTensorFromDataId(r.dataId,r.shape,r.dtype)}makeTensorInfo(e,t,r){let n;if(t==="string"&&r!=null&&r.length>0&&w.isString(r[0])){let a=r.map(s=>w.encodeString(s));n=this.write(a,e,t)}else n=this.write(r,e,t);return this.texData.get(n).usage=null,{dataId:n,shape:e,dtype:t}}makeOutput(e,t,r){let{dataId:n}=this.makeTensorInfo(e,t,r);return nr().makeTensorFromDataId(n,e,t,this)}unpackTensor(e){let t=new bte(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){let t=new ate(e.shape),r=!0;return this.runWebGLProgram(t,[e],e.dtype,null,r)}packedReshape(e,t){let r=[Oo(e.shape),...Do(e.shape)],n={dtype:e.dtype,shape:r,dataId:e.dataId},a=[Oo(t),...Do(t)],s=new YS(a,r),i=!0,o=[r],l=this.runWebGLProgram(s,[n],e.dtype,o,i);return{dataId:l.dataId,shape:t,dtype:l.dtype}}decode(e,t){let r=this.texData.get(e),{isPacked:n,shape:a,dtype:s}=r;if(t!=null){let h=w.sizeFromShape(a),p=t[0]*t[1]*4;w.assert(h<=p,()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data.")}let i=of(a),o;n?o=new cee(i):o=new hee(i);let l=!0,u=[t!=null?t:Yc(i)],d=this.runWebGLProgram(o,[{shape:i,dtype:s,dataId:e}],s,u,l,t);return{dtype:s,shape:a,dataId:d.dataId}}runWebGLProgram(e,t,r,n,a=!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:Yc(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=[],u=t.map(g=>{if(g.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let y=this.texData.get(g.dataId);if(y.texture==null){if(!e.packedInputs&&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&&!jp(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 d={shape:i.shape,texData:o,isUniform:!1},h=pee(e,u,d),p=this.getAndSaveBinary(h,()=>uee(this.gpgpu,e,u,d)),c=this.activeTimers!=null,f;c&&(f=this.startTimer()),Y().get("ENGINE_COMPILE_ONLY")||dee(this.gpgpu,p,u,d,n),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&&a===!1){let g=this.unpackTensor(i);return this.disposeIntermediateTensorInfo(i),g}return i}compileAndRun(e,t,r,n,a=!1){return r=r||t[0].dtype,this.runWebGLProgram(e,t,r,n,a)}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=K(()=>{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?wte:kte}uploadToGPU(e){let t=this.texData.get(e),{shape:r,dtype:n,values:a,texture:s,usage:i,isPacked:o}=t;if(s!=null)return;let l=this.activeTimers!=null,u;l&&(u=w.now());let d=t.texShape;if(d==null&&(d=AS(r,o),t.texShape=d),a!=null){let h=of(r),p,c=d[1],f=d[0],m=a instanceof Uint8Array||a instanceof Uint8ClampedArray;(o||!m)&&([c,f]=bd(d[0],d[1])),o?p=new yee(h,m):p=new gee(h,m);let g=m?[f,c]:d,y=this.makeTensorInfo(g,n),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,a);let x=[[f,c]],b=!0,v=this.runWebGLProgram(p,[y],n,x,b),S=this.texData.get(v.dataId);t.texShape=S.texShape,t.isPacked=S.isPacked,t.usage=S.usage,Y().get("ENGINE_COMPILE_ONLY")?this.disposeData(v.dataId):(t.texture=S.texture,t.values=null,this.texData.delete(v.dataId)),this.disposeIntermediateTensorInfo(y),l&&(this.uploadWaitMs+=w.now()-u)}else{let h=this.acquireTexture(d,i,n,o);t.texture=h}}convertAndCacheOnCPU(e,t){let r=this.texData.get(e),{dtype:n}=r;return this.releaseGPUData(e),t!=null&&(r.values=Cte(t,n)),r.values}acquireTexture(e,t,r,n){if(this.numBytesInGPU+=this.computeBytes(e,r),!this.warnedAboutMemory&&this.numBytesInGPU>this.numMBBeforeWarning*1024*1024){let a=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${a} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,n)}computeBytes(e,t){return e[0]*e[1]*w.bytesPerElement(t)}checkCompileCompletion(){for(let[,e]of Object.entries(this.binaryCache))this.checkCompletion_(e)}async checkCompileCompletionAsync(){let e=[];if(this.gpgpu.parallelCompilationExtension){for(let[,t]of Object.entries(this.binaryCache))e.push(this.checkCompletionAsync_(t));return Promise.all(e)}else{for(let[,t]of Object.entries(this.binaryCache)){let r=new Promise(n=>{try{this.checkCompletion_(t),n(!0)}catch(a){throw a}});e.push(r)}return Promise.all(e)}}async checkCompletionAsync_(e){return this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)?this.checkCompletion_(e):(await fA(),this.checkCompletionAsync_(e))}checkCompletion_(e){if(this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.gl.LINK_STATUS)===!1)throw console.log(this.gpgpu.gl.getProgramInfoLog(e.webGLProgram)),this.gpgpu.gl.getShaderParameter(e.fragmentShader,this.gpgpu.gl.COMPILE_STATUS)===!1?(ob(e.source,this.gpgpu.gl.getShaderInfoLog(e.fragmentShader)),new Error("Failed to compile fragment shader.")):new Error("Failed to link vertex and fragment shaders.");return!0}getUniformLocations(){for(let[,e]of Object.entries(this.binaryCache)){let{uniformLocations:t,customUniformLocations:r,infLoc:n,nanLoc:a,inShapesLocations:s,inTexShapesLocations:i,outShapeLocation:o,outShapeStridesLocation:l,outTexShapeLocation:u}=ES(this.gpgpu,e.program,e.webGLProgram);e.uniformLocations=t,e.customUniformLocations=r,e.infLoc=n,e.nanLoc=a,e.inShapesLocations=s,e.inTexShapesLocations=i,e.outShapeLocation=o,e.outShapeStridesLocation=l,e.outTexShapeLocation=u}}},Oh=JS;Oh.nextDataId=0;function Cte(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 n=0;n<r.length;++n)r[n]=Math.round(e[n]);return r}else throw new Error(`Unknown dtype ${t}`)}var Ete="0.0.0";function QS(){Y().set("WEBGL_FORCE_F16_TEXTURES",!0)}fh.isBrowser()&&Cl("webgl",()=>new Oh,2);var Rte={forceHalfFloat:QS},e8=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,Fu=class{constructor(e,t,r){this.variableNames=["A","B"],this.outputShape=N.assertAndGetBroadcastShape(t,r),this.enableShapeUniforms=ln(this.outputShape.length),this.userCode=`
|
|
float binaryOperation(float a, float b) {
|
|
${e}
|
|
}
|
|
|
|
void main() {
|
|
float a = getAAtOutCoords();
|
|
float b = getBAtOutCoords();
|
|
setOutput(binaryOperation(a, b));
|
|
}
|
|
`}},b0=`
|
|
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;
|
|
`,Dh=class{constructor(e,t,r,n=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=N.assertAndGetBroadcastShape(t,r);let a=this.outputShape.length;this.enableShapeUniforms=ln(a);let s="";if(n)if(a===0||w.sizeFromShape(this.outputShape)===1)s=`
|
|
result.y = 0.;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;else if(s=`
|
|
${gt(a)} coords = getOutputCoords();
|
|
`,a===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=Lr("coords",a);this.enableShapeUniforms?s+=`
|
|
bool nextRowOutOfBounds =
|
|
(${i[a-2]} + 1) >= outShape[${a} - 2];
|
|
bool nextColOutOfBounds =
|
|
(${i[a-1]} + 1) >= outShape[${a} - 1];
|
|
result.y = nextColOutOfBounds ? 0. : result.y;
|
|
result.z = nextRowOutOfBounds ? 0. : result.z;
|
|
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
|
|
`:s+=`
|
|
bool nextRowOutOfBounds =
|
|
(${i[a-2]} + 1) >= ${this.outputShape[a-2]};
|
|
bool nextColOutOfBounds =
|
|
(${i[a-1]} + 1) >= ${this.outputShape[a-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 sn(e){let{inputs:t,backend:r}=e,{x:n}=t;return r.incRef(n.dataId),{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}var Mte={kernelName:ci,backendName:"webgl",kernelFunc:sn};function ji(e){let{inputs:t,backend:r}=e,{real:n,imag:a}=t,s=r.makeTensorInfo(n.shape,"complex64"),i=r.texData.get(s.dataId),o=sn({inputs:{x:n},backend:r}),l=sn({inputs:{x:a},backend:r});return i.complexTensorInfos={real:o,imag:l},s}var Fte={kernelName:Xp,backendName:"webgl",kernelFunc:ji},t8="return (a < 0.) ? b * a : a;",r8=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function $te(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{alpha:s}=n,i=r.makeTensorInfo([],"float32",w.createScalarValue(s,"float32")),o=Y().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Dh(r8,a.shape,i.shape):new Fu(t8,a.shape,i.shape),l=r.runWebGLProgram(o,[a,i],"float32");return r.disposeIntermediateTensorInfo(i),l}var Pte={kernelName:fi,backendName:"webgl",kernelFunc:$te},n8="return (a < 0.) ? b * a : a;",a8=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function _te(e){let{inputs:t,backend:r}=e,{x:n,alpha:a}=t,s=Y().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Dh(a8,n.shape,a.shape):new Fu(n8,n.shape,a.shape);return r.runWebGLProgram(s,[n,a],"float32")}var zte={kernelName:Ti,backendName:"webgl",kernelFunc:_te},Td="if (isnan(x)) return x;",Ote=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,Dte=`
|
|
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:n}){return({inputs:a,backend:s})=>{let{x:i}=a,o=s,l=n||i.dtype;if(o.shouldExecuteOnCPU([i])&&r!=null){let h=o.texData.get(i.dataId),p=r(h.values,l);return o.makeTensorInfo(i.shape,l,p)}let u=Y().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,d;return u?d=new Io(i.shape,t):d=new Ka(i.shape,e),o.runWebGLProgram(d,[i],l)}}function wr({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:r=!1,supportsComplex:n=!1,cpuKernelImpl:a,dtype:s}){return({inputs:i,backend:o})=>{let{a:l,b:u}=i,d=o;if(n&&l.dtype==="complex64"){let f=d.texData.get(l.dataId),m=d.texData.get(u.dataId),[g,y]=[[f.complexTensorInfos.real,m.complexTensorInfos.real],[f.complexTensorInfos.imag,m.complexTensorInfos.imag]].map(x=>{let[b,v]=x,S={dataId:b.dataId,dtype:b.dtype,shape:l.shape},T={dataId:v.dataId,dtype:v.dtype,shape:u.shape},E=new Fu(e,l.shape,u.shape);return d.runWebGLProgram(E,[S,T],Cr(b.dtype,v.dtype))}),A=ji({inputs:{real:g,imag:y},backend:d});return d.disposeIntermediateTensorInfo(g),d.disposeIntermediateTensorInfo(y),A}let h=s||Cr(l.dtype,u.dtype);if((l.dtype==="string"||u.dtype==="string"||d.shouldExecuteOnCPU([l,u]))&&a!=null){let f=d.texData.get(l.dataId).values,m=d.texData.get(u.dataId).values,g=l.dtype==="string"?N.fromUint8ToStringArray(f):f,y=l.dtype==="string"?N.fromUint8ToStringArray(m):m,[A,x]=a(l.shape,u.shape,g,y,h),b=d.makeTensorInfo(x,h),v=d.texData.get(b.dataId);return v.values=A,b}let p=Y().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,c;return p?c=new Dh(t,l.shape,u.shape,r):c=new Fu(e,l.shape,u.shape),d.runWebGLProgram(c,[l,u],h)}}function v0(e,t=!1){if(e==="linear")return t?mte:dte;if(e==="relu")return t?yte:hte;if(e==="elu")return t?gte:pte;if(e==="relu6")return t?Ate:cte;if(e==="prelu")return t?a8:n8;if(e==="leakyrelu")return t?r8:t8;if(e==="sigmoid")return t?xte:fte;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}var s8=class{constructor(e,t,r,n=!1,a=!1,s=!1,i=null,o=!1,l=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=r,this.enableShapeUniforms=ln(this.outputShape.length);let u=n?e[1]:e[2],d=Math.ceil(u/2),h=n?"i * 2, rc.y":"rc.y, i * 2",p=a?"rc.z, i * 2":"i * 2, rc.z",c=n?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=a?["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 = ${d}.0;
|
|
|
|
vec4 dot2x2ARowBCol(ivec3 rc) {
|
|
vec4 result = vec4(0);
|
|
for (int i = 0; i < ${d}; i++) {
|
|
int batchA = ${A};
|
|
int batchB = ${x};
|
|
vec4 a = getMatrixA(batchA, ${h});
|
|
vec4 b = getMatrixB(batchB, ${p});
|
|
|
|
// 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);
|
|
}
|
|
`}},zv={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},Ov=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));
|
|
}
|
|
`}},Dv="return a * b;";function yb(e){let{inputs:t,backend:r}=e,{a:n,b:a}=t,s=N.upcastType(n.dtype,a.dtype);if(n.dtype==="complex64"){let o=r.texData.get(n.dataId),l=r.texData.get(a.dataId),u=new Ov(zv.REAL,n.shape,a.shape),d=new Ov(zv.IMAG,n.shape,a.shape),h=[{dataId:o.complexTensorInfos.real.dataId,dtype:o.complexTensorInfos.real.dtype,shape:n.shape},{dataId:o.complexTensorInfos.imag.dataId,dtype:o.complexTensorInfos.imag.dtype,shape:n.shape},{dataId:l.complexTensorInfos.real.dataId,dtype:l.complexTensorInfos.real.dtype,shape:a.shape},{dataId:l.complexTensorInfos.imag.dataId,dtype:l.complexTensorInfos.imag.dtype,shape:a.shape}],p=r.runWebGLProgram(u,h,"float32"),c=r.runWebGLProgram(d,h,"float32"),f=ji({inputs:{real:p,imag:c},backend:r});return r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(c),f}if(r.shouldExecuteOnCPU([n,a])){let o=r.texData.get(n.dataId),l=r.texData.get(a.dataId),[u,d]=Dee(n.shape,a.shape,o.values,l.values,s),h=r.makeTensorInfo(d,s),p=r.texData.get(h.dataId);return p.values=u,h}let i;return Y().getBool("WEBGL_PACK_BINARY_OPERATIONS")?i=new Dh(Dv,n.shape,a.shape):i=new Fu(Dv,n.shape,a.shape),r.runWebGLProgram(i,[n,a],s)}var Lte={kernelName:ki,backendName:"webgl",kernelFunc:yb};function Bte(e,t,r){let n=[Oo(e.shape),...Do(e.shape)],a={dtype:e.dtype,shape:n,dataId:e.dataId},s=[Oo(t),...Do(t)],i=new YS(s,n),o=!0,l=[n],u=r.runWebGLProgram(i,[a],e.dtype,l,o);return{dataId:u.dataId,shape:t,dtype:u.dtype}}function ve(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{shape:s}=n,i=r,o=w.sizeFromShape(a.shape),l=w.inferFromImplicitShape(s,o),u=w.sizeFromShape(l);w.assert(o===u,()=>`The new shape (${l}) has ${u} elements and the old shape (${a.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`);let d=i.texData.get(a.dataId);return d.isPacked&&!jp(a.shape,l)&&!(d.texture!==null&&jp(d.shape,l))?Bte(a,l,i):(i.incRef(a.dataId),{dataId:a.dataId,shape:l,dtype:a.dtype})}var Wte={kernelName:pl,backendName:"webgl",kernelFunc:ve},Lv=class{constructor(e,t){this.variableNames=["x"];let{windowSize:r,batchSize:n,inSize:a,outSize:s}=e;this.outputShape=[n,s];let i=Math.floor(r/4)*4,o=r%4,l="sumValue += dot(values, ones);";if(t!=null){let d=1/t;l=`sumValue += dot(values * ${w.isInt(d)?d.toPrecision(2):d}, ones);`}let u="";a%r>0&&(u=`
|
|
if (inIdx < 0 || inIdx >= ${a}) {
|
|
return 0.0;
|
|
}
|
|
`),this.userCode=`
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
${u}
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = outIdx * ${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);
|
|
}
|
|
`}},Vte=class{constructor(e,t){this.variableNames=["x"];let{windowSize:r,batchSize:n,inSize:a,outSize:s}=e;this.outputShape=[n,s];let i="0.0",o="";t==="prod"?i="1.0":t==="min"?(i="1.0 / 1e-20",o="min"):t==="max"&&(i="-1.0 / 1e-20",o="max");let l=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?l="sumValue":t==="prod"?l="prodValue":t==="all"?l="allValue":t==="any"&&(l="anyValue");let u=Math.floor(r/4)*4,d=r%4,h=`
|
|
if (${t==="sum"}) {
|
|
sumValue += dot(values, ones);
|
|
} else if (${t==="prod"}) {
|
|
vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
|
|
prodValue *= tmp[0] * tmp[1];
|
|
} else {
|
|
minMaxValue = ${o}(values, minMaxValue);
|
|
if (${t==="min"} || ${t==="max"}) {
|
|
minMaxValue = ${o}(values, minMaxValue);
|
|
bvec4 isNaN = isnan(values);
|
|
if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {
|
|
minMaxValue = vec4(NAN);
|
|
}
|
|
}
|
|
}
|
|
`,p="vec4";t==="all"?(i="1.0",h=`
|
|
bool reducedAllValue = all(values);
|
|
float floatedReducedAllValue = float(reducedAllValue);
|
|
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
|
|
`,p="bvec4"):t==="any"&&(i="0.0",h=`
|
|
bool reducedAnyValue = any(values);
|
|
float floatedReducedAnyValue = float(reducedAnyValue);
|
|
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
|
|
`,p="bvec4");let c="";a%r>0&&(c=`
|
|
if (inIdx < 0 || inIdx >= ${a}) {
|
|
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 < ${u}; i += 4) {
|
|
int inIdx = inOffset + i;
|
|
${p} values = ${p}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
${h}
|
|
}
|
|
|
|
int inIdx = inOffset + ${u};
|
|
if (${d===1}) {
|
|
${p} values = ${p}(
|
|
getValue(batch, inIdx),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${h}
|
|
} else if (${d===2}) {
|
|
${p} values = ${p}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${h}
|
|
} else if (${d===3}) {
|
|
${p} values = ${p}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
initializationValue
|
|
);
|
|
|
|
${h}
|
|
}
|
|
setOutput(${l});
|
|
}
|
|
`}};function Ute(e){let t=[];for(;t.length===0||t[t.length-1].outSize!==1;){let r=t.length?t[t.length-1].outSize:e[1],n=N.computeOptimalWindowSize(r);t.push({inSize:r,windowSize:n,outSize:Math.ceil(r/n)})}return t}function Ol(e,t,r,n){let a=Ute(e.shape),s=e;for(let i=0;i<a.length;i++){let{inSize:o,windowSize:l,outSize:u}=a[i],d,h;r==="mean"?d=i===0?new Lv({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u},o):new Lv({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u}):d=new Vte({windowSize:l,inSize:o,batchSize:e.shape[0],outSize:u},r),h=s,s=n.runWebGLProgram(d,[s],t),h.dataId!==e.dataId&&n.disposeIntermediateTensorInfo(h)}return s}var Gte=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 n=gt(this.rank),a=jte(t);this.userCode=`
|
|
void main() {
|
|
${n} resRC = getOutputCoords();
|
|
setOutput(getA(${a}));
|
|
}
|
|
`}};function jte(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"],n=new Array(t);for(let a=0;a<e.length;a++)n[e[a]]=r[a];return n.join()}var Hte=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let r=new Array(e.length);for(let u=0;u<r.length;u++)r[u]=e[t[u]];if(this.outputShape=r,this.rank=r.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let n=gt(this.rank),a=ZS("rc",this.rank),s=new Array(this.rank);for(let u=0;u<t.length;u++)s[t[u]]=a[u];let i=`vec2(${s.slice(-2).join()})`,o=`++${a[this.rank-1]} < ${r[this.rank-1]}`,l=`getChannel(getA(${s.join()}), ${i})`;this.userCode=`
|
|
void main() {
|
|
${n} rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result[0] = ${l};
|
|
if(${o}) {
|
|
result[1] = ${l};
|
|
}
|
|
--${a[this.rank-1]};
|
|
if(++${a[this.rank-2]} < ${r[this.rank-2]}) {
|
|
result[2] = ${l};
|
|
if(${o}) {
|
|
result[3] = ${l};
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}};function w0(e,t,r){let n=Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Hte(e.shape,t):new Gte(e.shape,t);return r.runWebGLProgram(n,[e],e.dtype)}function qte(e,t,r,n){let a=t,s=e.shape.length,i=w.parseAxisParam(a,e.shape),o=i,l=N.getAxesPermutation(o,s),u=l!=null,d=e;u&&(d=w0(e,l,n),o=N.getInnerMostAxes(o.length,s)),N.assertAxesAreInnerMostDims("sum",o,s);let[h,p]=N.computeOutAndReduceShapes(d.shape,o),c=h;r&&(c=N.expandShapeToKeepDim(h,i));let f=w.sizeFromShape(p),m=w.sizeFromShape(e.shape)/f,g=ve({inputs:{x:d},attrs:{shape:[m,f]},backend:n}),y=ch(e.dtype),A=Ol(g,y,"sum",n),x=ve({inputs:{x:A},attrs:{shape:c},backend:n});return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(A),u&&n.disposeIntermediateTensorInfo(d),x}function k0(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n;return qte(a,s,i,r)}var Kte={kernelName:_i,backendName:"webgl",kernelFunc:k0};function vr(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{perm:s}=n,i=r,o=a.shape.length,l=new Array(o);for(let d=0;d<l.length;d++)l[d]=a.shape[s[d]];let u;if(i.shouldExecuteOnCPU([a])){let d=i.texData.get(a.dataId).values,h=gb(d,a.shape,a.dtype,s,l);u=i.makeTensorInfo(l,a.dtype);let p=i.texData.get(u.dataId);p.values=h}else u=w0(a,s,i);return u}var Xte={kernelName:Bi,backendName:"webgl",kernelFunc:vr},i8=1e3;function Bf({a:e,b:t,transposeA:r,transposeB:n,backend:a,bias:s=null,preluActivationWeights:i=null,leakyreluAlpha:o=0,activation:l=null}){let u=e.shape.length,d=t.shape.length,h=r?e.shape[u-2]:e.shape[u-1],p=n?t.shape[d-1]:t.shape[d-2],c=r?e.shape[u-1]:e.shape[u-2],f=n?t.shape[d-2]:t.shape[d-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),y=w.sizeFromShape(m),A=w.sizeFromShape(g),x=Nl.assertAndGetBroadcastShape(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([c,f]);w.assert(h===p,()=>`Error in matMul: inner shapes (${h}) and (${p}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${r} and transposeB=${n} must match.`);let b=r?[y,h,c]:[y,c,h],v=n?[A,f,p]:[A,p,f],S=ve({inputs:{x:e},backend:a,attrs:{shape:b}}),T=ve({inputs:{x:t},backend:a,attrs:{shape:v}}),E=[S,T],R=Math.max(y,A),_=r?S.shape[1]:S.shape[2],M=s!=null,I=i!=null,z=l==="leakyrelu",O=l!=null?v0(l,!0):null,j=M||I||z||O!=null,X;if((c===1||f===1)&&_>i8&&j===!1){let Q=S,V=T;r&&(Q=vr({inputs:{x:S},backend:a,attrs:{perm:[0,2,1]}}),E.push(Q)),n&&(V=vr({inputs:{x:T},backend:a,attrs:{perm:[0,2,1]}}),E.push(V));let ee=f!==1,J=f===1,ie=Q;ee&&(ie=ve({inputs:{x:Q},backend:a,attrs:{shape:[R,_,1]}}),E.push(ie));let Z=f===1?2:1,ae=V;J&&(ae=ve({inputs:{x:V},backend:a,attrs:{shape:[R,1,_]}}),E.push(ae));let de=yb({inputs:{a:ie,b:ae},backend:a});X=k0({inputs:{x:de},backend:a,attrs:{axis:Z,keepDims:!0}}),E.push(de)}else{let Q=Cr(e.dtype,t.dtype),V=new s8(b,v,[R,c,f],r,n,M,O,I,z),ee=[S,T];if(s!=null&&ee.push(s),I&&ee.push(i),z){let J=a.makeTensorInfo([],"float32",w.createScalarValue(o,"float32"));ee.push(J),E.push(J)}X=a.runWebGLProgram(V,ee,Q)}let D=ve({inputs:{x:X},backend:a,attrs:{shape:x}});E.push(X);for(let Q of E)a.disposeIntermediateTensorInfo(Q);return D}function Zte(e){let{inputs:t,backend:r,attrs:n}=e,{a,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:u,activation:d,leakyreluAlpha:h}=n;return Bf({a,b:s,transposeA:l,transposeB:u,backend:r,bias:i,preluActivationWeights:o,leakyreluAlpha:h,activation:d})}var Yte={kernelName:Fs,backendName:"webgl",kernelFunc:Zte},Bv="return abs(x);";function Jte(e){let{inputs:t,backend:r}=e,{x:n}=t;if(r.shouldExecuteOnCPU([n])&&n.dtype!=="complex64"){let s=r.texData.get(n.dataId),i=KS(s.values);return r.makeTensorInfo(n.shape,n.dtype,i)}let a;return Y().getBool("WEBGL_PACK_UNARY_OPERATIONS")?a=new Io(n.shape,Bv):a=new Ka(n.shape,Bv),r.runWebGLProgram(a,[n],n.dtype)}var Qte={kernelName:Vo,backendName:"webgl",kernelFunc:Jte},ere=Xn+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return acos(x);
|
|
`,tre=it({opSnippet:ere}),rre={kernelName:_u,backendName:"webgl",kernelFunc:tre},nre=Xn+`
|
|
if (x < 1.0) return NAN;
|
|
return log(x + sqrt(x * x - 1.0));`,are=it({opSnippet:nre}),sre={kernelName:zu,backendName:"webgl",kernelFunc:are},Wv="return a + b;",ire=wr({opSnippet:Wv,packedOpSnippet:Wv,supportsComplex:!0,cpuKernelImpl:xee}),ore={kernelName:Ja,backendName:"webgl",kernelFunc:ire},lre=class{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((a,s)=>`T${s}`);let r=[];this.variableNames.forEach(a=>{r.push(`float v${a} = get${a}AtOutCoords();`)});let n=this.variableNames.map(a=>`v${a}`).join(" + ");this.userCode=`
|
|
void main() {
|
|
${r.join(`
|
|
`)}
|
|
|
|
float result = ${n};
|
|
setOutput(result);
|
|
}
|
|
`}},ure=class{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((a,s)=>`T${s}`);let r=[];this.variableNames.forEach(a=>{r.push(`vec4 v${a} = get${a}AtOutCoords();`)});let n=this.variableNames.map(a=>`v${a}`).join(" + ");this.userCode=`
|
|
void main() {
|
|
${r.join(`
|
|
`)}
|
|
|
|
vec4 result = ${n};
|
|
setOutput(result);
|
|
}
|
|
`}};function df(e){let{inputs:t,backend:r}=e,n=t;if(n.length===1)return sn({inputs:{x:n[0]},backend:r});if(n.length>Y().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let o=Math.floor(n.length/2),l=df({inputs:n.slice(0,o),backend:r}),u=df({inputs:n.slice(o),backend:r});return df({inputs:[l,u],backend:r})}let a=n.map(o=>o.dtype).reduce((o,l)=>Cr(o,l)),s=n.map(o=>o.shape),i=Y().getBool("WEBGL_PACK")?new ure(n[0].shape,s):new lre(n[0].shape,s);return r.runWebGLProgram(i,n,a)}var dre={kernelName:Ks,backendName:"webgl",kernelFunc:df};function pre(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n,o=a.shape.length,l=w.parseAxisParam(s,a.shape),u=l,d=N.getAxesPermutation(u,o),h=a;d!=null&&(h=vr({inputs:{x:a},backend:r,attrs:{perm:d}}),u=N.getInnerMostAxes(u.length,o)),N.assertAxesAreInnerMostDims("all",u,o);let[p,c]=N.computeOutAndReduceShapes(h.shape,u),f=w.sizeFromShape(c),m=ve({inputs:{x:h},backend:r,attrs:{shape:[-1,f]}}),g=Ol(m,m.dtype,"all",r),y;if(i){let A=N.expandShapeToKeepDim(p,l);y=ve({inputs:{x:g},backend:r,attrs:{shape:A}})}else y=ve({inputs:{x:g},backend:r,attrs:{shape:p}});return r.disposeIntermediateTensorInfo(m),r.disposeIntermediateTensorInfo(g),d!=null&&r.disposeIntermediateTensorInfo(h),y}var hre={kernelName:Ou,backendName:"webgl",kernelFunc:pre};function cre(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n,o=a.shape.length,l=w.parseAxisParam(s,a.shape),u=l,d=N.getAxesPermutation(u,o),h=a;d!=null&&(h=vr({inputs:{x:a},backend:r,attrs:{perm:d}}),u=N.getInnerMostAxes(u.length,o)),N.assertAxesAreInnerMostDims("any",u,o);let[p,c]=N.computeOutAndReduceShapes(h.shape,u),f=w.sizeFromShape(c),m=ve({inputs:{x:h},backend:r,attrs:{shape:[-1,f]}}),g=Ol(m,m.dtype,"any",r),y;if(i){let A=N.expandShapeToKeepDim(p,l);y=ve({inputs:{x:g},backend:r,attrs:{shape:A}})}else y=ve({inputs:{x:g},backend:r,attrs:{shape:p}});return r.disposeIntermediateTensorInfo(m),r.disposeIntermediateTensorInfo(g),d!=null&&r.disposeIntermediateTensorInfo(h),y}var fre={kernelName:Du,backendName:"webgl",kernelFunc:cre},mre=class{constructor(e,t,r){this.variableNames=["A"];let{windowSize:n,batchSize:a,outSize:s}=e;r||this.variableNames.push("bestIndicesA"),this.outputShape=[a,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 * ${n};
|
|
|
|
int bestIndex = inOffset;
|
|
float bestValue = getA(batch, bestIndex);
|
|
|
|
for (int i = 0; i < ${n}; i++) {
|
|
int inIdx = ${o};
|
|
float candidate = getA(batch, inIdx);
|
|
if (candidate ${i} bestValue) {
|
|
bestValue = candidate;
|
|
bestIndex = inIdx;
|
|
}
|
|
}
|
|
setOutput(float(bestIndex));
|
|
}
|
|
`}},gre=class{constructor(e,t,r,n){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 a=e[e.length-1],s=Math.ceil(a/t);this.outputShape=e.slice(0,-1),s>1&&this.outputShape.push(s),n||this.variableNames.push("bestIndicesA");let i=this.outputShape,o=i.length,l=gt(o),u=Lr("coords",o),d,h;if(s===1){h=o+1;let T=gt(h);d=`
|
|
${T} sourceLocR = ${T}(${u.join()}, 0);
|
|
++${u[o-1]};
|
|
${T} sourceLocG = ${T}(${u.join()}, 0);
|
|
++${u[o-2]};
|
|
${T} sourceLocA = ${T}(${u.join()}, 0);
|
|
--${u[o-1]};
|
|
${T} sourceLocB = ${T}(${u.join()}, 0);
|
|
--${u[o-2]};`}else h=o,d=`
|
|
${l} sourceLocR = coords;
|
|
++${u[o-1]};
|
|
${l} sourceLocG = coords;
|
|
++${u[o-2]};
|
|
${l} sourceLocA = coords;
|
|
--${u[o-1]};
|
|
${l} sourceLocB = coords;
|
|
--${u[o-2]};`;let p=["x","y","z","w","u","v"].slice(0,h),c="."+p[h-1],f=p.map(T=>"int "+T),m=Lr("sourceLocR",h-1).concat("inIdx.r"),g=Lr("sourceLocG",h-1).concat("inIdx.g"),y=Lr("sourceLocB",h-1).concat("inIdx.b"),A=Lr("sourceLocA",h-1).concat("inIdx.a"),x=r==="max"?"greaterThan":"lessThan",b=n?"":`
|
|
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.)`,S=n?"":`
|
|
float getBestIndicesAChannel(${f.join()}) {
|
|
return getChannel(getBestIndicesA(${p.join()}),
|
|
vec2(${p.slice(-2).join()}));
|
|
}`;this.userCode=`
|
|
float getAChannel(${f.join()}) {
|
|
return getChannel(getA(${p.join()}),
|
|
vec2(${p.slice(-2).join()}));
|
|
}
|
|
${S}
|
|
void main() {
|
|
${l} coords = getOutputCoords();
|
|
bool hasNextCol = ${u[o-1]} < ${i[o-1]-1};
|
|
bool hasNextRow = ${u[o-2]} < ${i[o-2]-1};
|
|
${d}
|
|
ivec4 srcIdx = ivec4(sourceLocR${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 o8(e,t,r,n=null){let a=t.shape[0],s=t.shape[1];n!=null&&(a=n.shape[0],s=n.shape[1]);let i=N.computeOptimalWindowSize(s),o={windowSize:i,inSize:s,batchSize:a,outSize:Math.ceil(s/i)},l=new mre(o,r,n==null),u=[t];n!=null&&u.push(n);let d=e.runWebGLProgram(l,u,"int32");if(d.shape[1]===1)return d;let h=o8(e,t,r,d);return e.disposeIntermediateTensorInfo(d),h}function l8(e,t,r,n=null){let a=n!=null?n.shape:t.shape,s=a[a.length-1],i=N.computeOptimalWindowSize(s),o=new gre(a,i,r,n==null),l=n==null?[t]:[t,n],u=e.runWebGLProgram(o,l,"int32");if(u.shape.length===t.shape.length){let d=l8(e,t,r,u);return e.disposeIntermediateTensorInfo(u),d}return u}function u8(e,t,r,n){let a=[r];if(N.assertAxesAreInnerMostDims("arg"+n.charAt(0).toUpperCase()+n.slice(1),a,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[u,d]=N.computeOutAndReduceShapes(l.shape,a),h=w.sizeFromShape(d),p=ve({inputs:{x:l},backend:e,attrs:{shape:[-1,h]}});s.push(p);let c=o8(e,p,n);s.push(c);let f=ve({inputs:{x:c},backend:e,attrs:{shape:u}});return s.forEach(m=>e.disposeIntermediateTensorInfo(m)),f}return l8(e,t,n)}function yre(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s}=n,i=w.parseAxisParam(s,a.shape),o=N.getAxesPermutation(i,a.shape.length),l=a,u=[];o!=null&&(l=vr({inputs:{x:a},backend:r,attrs:{perm:o}}),u.push(l),i=N.getInnerMostAxes(i.length,l.shape.length)),N.assertAxesAreInnerMostDims("argMax",[i[0]],l.shape.length);let d=u8(r,l,i[0],"max");return u.forEach(h=>r.disposeIntermediateTensorInfo(h)),d}var Are={kernelName:Xs,backendName:"webgl",kernelFunc:yre};function xre(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s}=n,i=w.parseAxisParam(s,a.shape),o=N.getAxesPermutation(i,a.shape.length),l=a,u=[];o!=null&&(l=vr({inputs:{x:a},backend:r,attrs:{perm:o}}),u.push(l),i=N.getInnerMostAxes(i.length,l.shape.length)),N.assertAxesAreInnerMostDims("argMin",[i[0]],l.shape.length);let d=u8(r,l,i[0],"min");return u.forEach(h=>r.disposeIntermediateTensorInfo(h)),d}var bre={kernelName:Lu,backendName:"webgl",kernelFunc:xre},vre=Xn+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return asin(x);
|
|
`,wre=it({opSnippet:vre}),kre={kernelName:Bu,backendName:"webgl",kernelFunc:wre},Ire=Xn+"return log(x + sqrt(x * x + 1.0));",Sre=it({opSnippet:Ire}),Tre={kernelName:Wu,backendName:"webgl",kernelFunc:Sre},Nre=Xn+`
|
|
return atan(x);
|
|
`,Cre=it({opSnippet:Nre}),Ere={kernelName:Vu,backendName:"webgl",kernelFunc:Cre},Rre=Ote+`
|
|
return atan(a, b);
|
|
`,Mre=`
|
|
vec4 result = atan(a, b);
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+Dte+`
|
|
return result;
|
|
`,Fre=wr({opSnippet:Rre,packedOpSnippet:Mre}),$re={kernelName:Gu,backendName:"webgl",kernelFunc:Fre},Pre=Xn+`
|
|
if ((x < -1.0) || (x > 1.0)) return NAN;
|
|
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,_re=it({opSnippet:Pre}),zre={kernelName:Uu,backendName:"webgl",kernelFunc:_re},Hp=class{constructor(e,t,r,n=!1,a=!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,u=e.dilationWidth,d=e.effectiveFilterHeight,h=e.effectiveFilterWidth,p=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(${p}, ${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 < ${d};
|
|
wR += ${l}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${h};
|
|
wC += ${u}) {
|
|
int xC = xCCorner + wC;
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
float value = getX(batch, xR, xC, d);
|
|
|
|
// If a min / max value has already been found, use it. If not,
|
|
// use the current value.
|
|
float currMinMaxValue = mix(
|
|
value, minMaxValue, minMaxValueFound);
|
|
if (value ${T} currMinMaxValue) {
|
|
minMaxValue = value;
|
|
minMaxValueFound = 1.0;
|
|
minMaxPosition = ${n?a?m:g:`wR * ${h} + 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,S=`
|
|
if (${f}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${A}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec2 strides = ivec2(${i}, ${o});
|
|
const ivec2 pads = ivec2(${p}, ${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 < ${d};
|
|
wR += ${l}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${b}; wC += 4) {
|
|
int xC = xCCorner + wC * ${u};
|
|
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${u}, d),
|
|
getValue(batch, xR, xC + 2 * ${u}, d),
|
|
getValue(batch, xR, xC + 3 * ${u}, d)
|
|
);
|
|
|
|
${S}
|
|
}
|
|
|
|
int xC = xCCorner + ${b};
|
|
if (${v===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${S}
|
|
} else if (${v===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${u}, d),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${S}
|
|
} else if (${v===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${u}, d),
|
|
getValue(batch, xR, xC + 2 * ${u}, d),
|
|
initializationValue
|
|
);
|
|
|
|
${S}
|
|
}
|
|
}
|
|
setOutput(${x});
|
|
}
|
|
`}},Ab=class{constructor(e,t,r,n=!1,a=!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,u=e.dilationDepth,d=e.dilationHeight,h=e.dilationWidth,p=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 < ${p};
|
|
wD += ${u}) {
|
|
int xD = xDCorner + wD;
|
|
|
|
if (xD < 0 || xD >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${c};
|
|
wR += ${d}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${f};
|
|
wC += ${h}) {
|
|
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 = ${n?a?`(((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 S=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 < ${p};
|
|
wD += ${u}) {
|
|
int xD = xDCorner + wD;
|
|
|
|
if (xD < 0 || xD >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${c};
|
|
wR += ${d}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${S}; wC += 4) {
|
|
int xC = xCCorner + wC * ${h};
|
|
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${h}, ch),
|
|
getValue(batch, xD, xR, xC + 2 * ${h}, ch),
|
|
getValue(batch, xD, xR, xC + 3 * ${h}, ch)
|
|
);
|
|
|
|
${E}
|
|
}
|
|
|
|
int xC = xCCorner + ${S};
|
|
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 + ${h}, ch),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${E}
|
|
} else if (${T===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${h}, ch),
|
|
getValue(batch, xD, xR, xC + 2 * ${h}, ch),
|
|
initializationValue
|
|
);
|
|
|
|
${E}
|
|
}
|
|
}
|
|
setOutput(${v});
|
|
}
|
|
}
|
|
`}};function Ore(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t;vd(a,"avgPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,u=1;w.assert(N.eitherStridesOrDilationsAreOne(i,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let d=N.computePool2DInfo(a.shape,s,i,u,o,l);if(d.filterWidth===1&&d.filterHeight===1&&w.arraysEqual(d.inShape,d.outShape))return sn({inputs:{x:a},backend:r});let h=new Hp(d,"avg",!1);return r.runWebGLProgram(h,[a],"float32")}var Dre={kernelName:Zs,backendName:"webgl",kernelFunc:Ore};function Lre(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=n,d=[1,1,1],h=N.computePool3DInfo(a.shape,s,i,d,o,l,u),p=new Ab(h,"avg",!1);return r.runWebGLProgram(p,[a],"float32")}var Bre={kernelName:Kp,backendName:"webgl",kernelFunc:Lre},Wre=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterHeight,r=e.filterWidth,n=e.strideHeight,a=e.strideWidth,s=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterHeight,l=e.effectiveFilterWidth,u=o-1-e.padInfo.top,d=l-1-e.padInfo.left,h=1/(t*r);this.userCode=`
|
|
const ivec2 pads = ivec2(${u}, ${d});
|
|
const float avgMultiplier = float(${h});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
|
|
ivec2 dyRCCorner = coords.yz - pads;
|
|
int dyRCorner = dyRCCorner.x;
|
|
int dyCCorner = dyRCCorner.y;
|
|
|
|
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < ${o};
|
|
wR += ${s}) {
|
|
float dyR = float(dyRCorner + wR) / ${n}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${l};
|
|
wC+= ${i}) {
|
|
float dyC = float(dyCCorner + wC) / ${a}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(b, idyR, idyC, d);
|
|
|
|
dotProd += dyValue * avgMultiplier;
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},Vre=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterDepth,r=e.filterHeight,n=e.filterWidth,a=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,u=e.dilationWidth,d=e.effectiveFilterDepth,h=e.effectiveFilterHeight,p=e.effectiveFilterWidth,c=d-1-e.padInfo.front,f=h-1-e.padInfo.top,m=p-1-e.padInfo.left,g=1/(t*r*n);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 < ${d};
|
|
wD += ${o}) {
|
|
float dyD = float(dyDCorner + wD) / ${a}.0;
|
|
|
|
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyD = int(dyD);
|
|
|
|
for (int wR = 0; wR < ${h};
|
|
wR += ${l}) {
|
|
float dyR = float(dyRCorner + wR) / ${s}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
|
|
fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${p};
|
|
wC += ${u}) {
|
|
float dyC = float(dyCCorner + wC) / ${i}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
|
|
|
|
dotProd += dyValue * avgMultiplier;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function Ure(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s}=t,i=s,{filterSize:o,strides:l,pad:u,dimRoundingMode:d}=n,h=[1,1,1],p=N.computePool3DInfo(i.shape,o,l,h,u,d),c=new Vre(p);return r.runWebGLProgram(c,[a],i.dtype)}var Gre={kernelName:Xf,backendName:"webgl",kernelFunc:Ure};function jre(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s}=t,i=s;vd([a,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:u}=n,d=N.computePool2DInfo(i.shape,o,l,1,u),h=new Wre(d);return r.runWebGLProgram(h,[a],i.dtype)}var Hre={kernelName:Kf,backendName:"webgl",kernelFunc:jre};function qre(e){let{inputs:t,backend:r,attrs:n}=e,{a,b:s}=t,{transposeA:i,transposeB:o}=n;return Bf({a,b:s,transposeA:i,transposeB:o,backend:r})}var Kre={kernelName:Ys,backendName:"webgl",kernelFunc:qre},Xre=class{constructor(e,t,r,n,a,s){this.outputShape=[],this.variableNames=["x","mean","variance"],N.assertAndGetBroadcastShape(e,t),N.assertAndGetBroadcastShape(e,r);let i="0.0";n!=null&&(N.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="1.0";a!=null&&(N.assertAndGetBroadcastShape(e,a),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)));
|
|
}
|
|
`}},Zre=class{constructor(e,t,r,n,a,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)";n!=null&&(N.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="vec4(1.0)";a!=null&&(N.assertAndGetBroadcastShape(e,a),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);
|
|
}
|
|
`}},Yre=({inputs:e,backend:t,attrs:r})=>{let{x:n,mean:a,variance:s,offset:i,scale:o}=e;w.assert(a.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),w.assert(i==null||a.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),w.assert(o==null||a.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 u=[n,a,s],d=null;i!=null&&(d=i.shape,u.push(i));let h=null;o!=null&&(h=o.shape,u.push(o));let p=Y().getBool("WEBGL_PACK_NORMALIZATION")?new Zre(n.shape,a.shape,s.shape,d,h,l):new Xre(n.shape,a.shape,s.shape,d,h,l);return t.runWebGLProgram(p,u,u[0].dtype)},Jre={kernelName:pi,backendName:"webgl",kernelFunc:Yre},Qre=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=gt(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let r=ene(this.rank),n,a=e.map((s,i)=>`sourceLoc.${Jy[i]} = start[${i}] + coords.${Jy[i]};`);n=`
|
|
${t} sourceLoc;
|
|
${t} coords = getOutputCoords();
|
|
${a.join(`
|
|
`)}
|
|
`,this.userCode=`
|
|
void main() {
|
|
${n}
|
|
setOutput(getSource(${r}));
|
|
}
|
|
`}},Jy=["x","y","z","w","u","v"];function ene(e){if(e===1)return"sourceLoc";if(e<=6)return Jy.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}var tne=class{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let t=gt(this.rank),r=Lr("coords",this.rank),n=Lr("sourceLoc",this.rank),a=this.rank===1?"sourceLoc":`vec2(${n.slice(-2).join()})`,s=`getChannel(getSource(${n.join()}), ${a})`,i=`
|
|
result.x = ${s};
|
|
if (++${r[this.rank-1]} < ${e[this.rank-1]}) {
|
|
++${n[this.rank-1]};
|
|
result.y = ${s};
|
|
--${n[this.rank-1]};
|
|
}
|
|
`,o=this.rank===1?"":`
|
|
--${r[this.rank-1]};
|
|
if (++${r[this.rank-2]} < ${e[this.rank-2]}) {
|
|
++${n[this.rank-2]};
|
|
result.z = ${s};
|
|
if (++${r[this.rank-1]} < ${e[this.rank-1]}) {
|
|
++${n[this.rank-1]};
|
|
result.w = ${s};
|
|
}
|
|
}
|
|
`,l=this.rank<=4?`sourceLoc = coords +
|
|
${t}(${e.map((u,d)=>`start[${d}]`).join()});`:e.map((u,d)=>`${n[d]} = ${r[d]} + start[${d}];`).join(`
|
|
`);this.userCode=`
|
|
void main() {
|
|
${t} coords = getOutputCoords();
|
|
${t} sourceLoc;
|
|
${l}
|
|
vec4 result = vec4(0.);
|
|
${i}
|
|
${o}
|
|
setOutput(result);
|
|
}
|
|
`}};function rne(e,t,r,n){let a=n.texData.get(e.dataId),s=n.makeTensorInfo(r,e.dtype),i=n.texData.get(s.dataId);Object.assign(i,a),i.refCount=1,i.shape=r,i.dtype=e.dtype;let o=zt.computeFlatOffset(t,w.computeStrides(e.shape));a.slice&&(o+=a.slice.flatOffset),i.slice={flatOffset:o,origDataId:a.slice&&a.slice.origDataId||e.dataId};let l=n.dataRefCount.get(i.slice.origDataId)||1;return n.dataRefCount.set(i.slice.origDataId,l+1),s}function Nd(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{begin:s,size:i}=n,[o,l]=zt.parseSliceParams(a,s,i);if(zt.assertParamsValid(a,o,l),w.sizeFromShape(l)===0)return r.makeTensorInfo(l,a.dtype,[]);if(r.shouldExecuteOnCPU([a])||a.dtype==="string"){let h=r.texData.get(a.dataId),p=jee(h.values,o,l,a.shape,a.dtype);return r.makeTensorInfo(l,a.dtype,p)}let{isPacked:u}=r.texData.get(a.dataId),d=zt.isSliceContinous(a.shape,o,l);if(u||!d){let h=Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new tne(l):new Qre(l),p=[o];return r.runWebGLProgram(h,[a],a.dtype,p)}return r.uploadToGPU(a.dataId),rne(a,o,l,r)}var nne={kernelName:gl,backendName:"webgl",kernelFunc:Nd},ane=e=>{let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockShape:s,crops:i}=n;w.assert(a.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(a.shape,s,o),u=N.getPermuted(l.length,s.length),d=N.getReshapedPermuted(a.shape,s,o),h=N.getSliceBeginCoords(i,s.length),p=N.getSliceSize(d,i,s.length),c=[],f=ve({inputs:{x:a},backend:r,attrs:{shape:l}}),m=vr({inputs:{x:f},backend:r,attrs:{perm:u}}),g=ve({inputs:{x:m},backend:r,attrs:{shape:d}}),y=Nd({inputs:{x:g},backend:r,attrs:{begin:h,size:p}});return c.push(f),c.push(m),c.push(g),c.forEach(A=>r.disposeIntermediateTensorInfo(A)),y},sne={kernelName:Uo,backendName:"webgl",kernelFunc:ane};function ine(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,weights:s}=t,{size:i}=n,o=r.readSync(a.dataId),l=r.readSync(s.dataId),u=qS(o,l,s.dtype,s.shape,i);return r.makeTensorInfo([i],s.dtype,u)}var one={kernelName:Zf,backendName:"webgl",kernelFunc:ine};function lne(e){let{inputs:t,backend:r}=e,{s0:n,s1:a}=t,s=r.readSync(n.dataId),i=r.readSync(a.dataId),o=N.assertAndGetBroadcastShape(Array.from(s),Array.from(i));return r.makeTensorInfo([o.length],"int32",Int32Array.from(o))}var une={kernelName:Yf,backendName:"webgl",kernelFunc:lne},dne="return float(a != b);",d8=wr({opSnippet:dne,cpuKernelImpl:Bee,dtype:"bool"}),pne={kernelName:sl,backendName:"webgl",kernelFunc:d8};function Lh(e){let{inputs:t,backend:r}=e,{input:n}=t,a=r.texData.get(n.dataId);return sn({inputs:{x:a.complexTensorInfos.real},backend:r})}var hne={kernelName:ah,backendName:"webgl",kernelFunc:Lh},cne="return float(int(x));";function fne(e,t){let r=new Ka(e.shape,cne),n=t.runWebGLProgram(r,[e],"int32");return{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}function Qy(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{dtype:s}=n;if(s==="complex64"){if(a.dtype==="complex64")return sn({inputs:{x:a},backend:r});let i=Pt(a.shape),o=Qy({inputs:{x:a},backend:r,attrs:{dtype:"float32"}}),l=ji({inputs:{real:o,imag:i},backend:r});return i.dispose(),r.disposeIntermediateTensorInfo(o),l}if(a.dtype==="complex64"){let i=Lh({inputs:{input:a},backend:r}),o=Qy({inputs:{x:i},backend:r,attrs:{dtype:s}});return r.disposeIntermediateTensorInfo(i),o}if(!w.hasEncodingLoss(a.dtype,s)){let i=sn({inputs:{x:a},backend:r});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(s==="int32")return fne(a,r);if(s==="bool"){let i=r.makeTensorInfo([],"bool",w.getTypedArrayFromDType("bool",1)),o=d8({inputs:{a,b:i},backend:r});return r.disposeIntermediateTensorInfo(i),o}throw new Error(`Error in Cast: failed to cast ${a.dtype} to ${s}`)}var mne={kernelName:Js,backendName:"webgl",kernelFunc:Qy},Vv="return ceil(x);",gne=it({opSnippet:Vv,packedOpSnippet:Vv,cpuKernelImpl:vee}),yne={kernelName:Qs,backendName:"webgl",kernelFunc:gne},Ane=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));
|
|
}
|
|
`}},xne=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 bne(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{clipValueMin:s,clipValueMax:i}=n,o;Y().getBool("WEBGL_PACK_CLIP")?o=new xne(a.shape):o=new Ane(a.shape);let l=[[s],[i]];return r.runWebGLProgram(o,[a],a.dtype,l)}var vne={kernelName:Qa,backendName:"webgl",kernelFunc:bne},wne=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 Uv(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}function kne(e){let{inputs:t,backend:r}=e,{x:n}=t,a=r.texData.get(n.dataId),s=new wne(n.shape),i=[Uv(n,a.complexTensorInfos.real),Uv(n,a.complexTensorInfos.imag)];return r.runWebGLProgram(s,i,i[0].dtype)}var Ine={kernelName:Zp,backendName:"webgl",kernelFunc:kne},Sne=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 n=t.length,a=t[t.length-1];r.push(`else setOutput(getT${n}(yR, yC-${a}));`),this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int yR = coords.x;
|
|
int yC = coords.y;
|
|
|
|
${r.join(`
|
|
`)}
|
|
}
|
|
`}},Tne=class{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=N.computeOutShape(e,t);let r=this.outputShape,n=r.length,a=gt(n),s=Lr("coords",n),i=["x","y","z","w","u","v"].slice(0,n);this.variableNames=e.map((f,m)=>`T${m}`);let o=new Array(e.length-1);o[0]=e[0][t];for(let f=1;f<o.length;f++)o[f]=o[f-1]+e[f][t];let l=i[t],u=i.slice(-2),d=i.join(),h=`if (${l} < ${o[0]}) {
|
|
return getChannel(
|
|
getT0(${d}), vec2(${u.join()}));
|
|
}`;for(let f=1;f<o.length;f++){let m=o[f-1];h+=`
|
|
if (${l} < ${o[f]} && ${l} >= ${o[f-1]}) {
|
|
return getChannel(
|
|
getT${f}(${Qc(i,l,m)}),
|
|
vec2(${Qc(u,l,m)}));
|
|
}`}let p=o.length,c=o[o.length-1];h+=`
|
|
return getChannel(
|
|
getT${p}(${Qc(i,l,c)}),
|
|
vec2(${Qc(u,l,c)}));`,this.userCode=`
|
|
float getValue(${i.map(f=>"int "+f)}) {
|
|
${h}
|
|
}
|
|
|
|
void main() {
|
|
${a} coords = getOutputCoords();
|
|
vec4 result = vec4(getValue(${s}), 0., 0., 0.);
|
|
|
|
${s[n-1]} = ${s[n-1]} + 1;
|
|
if (${s[n-1]} < ${r[n-1]}) {
|
|
result.g = getValue(${s});
|
|
}
|
|
|
|
${s[n-2]} = ${s[n-2]} + 1;
|
|
if (${s[n-2]} < ${r[n-2]}) {
|
|
result.a = getValue(${s});
|
|
}
|
|
|
|
${s[n-1]} = ${s[n-1]} - 1;
|
|
if (${s[n-2]} < ${r[n-2]} &&
|
|
${s[n-1]} < ${r[n-1]}) {
|
|
result.b = getValue(${s});
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}};function Qc(e,t,r){let n=e.indexOf(t);return e.map((a,s)=>s===n?`${a} - ${r}`:a).join()}function I0(e){let{inputs:t,backend:r}=e,{input:n}=t,a=r.texData.get(n.dataId);return sn({inputs:{x:a.complexTensorInfos.imag},backend:r})}var Nne={kernelName:eh,backendName:"webgl",kernelFunc:I0};function cu(e,t,r){let n=e[0].dtype;if(n==="complex64"){let d=e.map(m=>Lh({inputs:{input:m},backend:r})),h=e.map(m=>I0({inputs:{input:m},backend:r})),p=cu(d,t,r),c=cu(h,t,r),f=ji({inputs:{real:p,imag:c},backend:r});return d.forEach(m=>r.disposeIntermediateTensorInfo(m)),h.forEach(m=>r.disposeIntermediateTensorInfo(m)),r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(c),f}let a=r.shouldExecuteOnCPU(e);if(n==="string"&&(a=!0),a){let d=e.map(y=>{let A=w.sizeFromShape(y.shape.slice(t));return ve({inputs:{x:y},backend:r,attrs:{shape:[-1,A]}})}),h=d.map(y=>({vals:r.readSync(y.dataId),shape:y.shape})),p=N.computeOutShape(d.map(y=>y.shape),1),c=d[0].shape[0]===1,f=wee(h,p,n,c),m=N.computeOutShape(e.map(y=>y.shape),t),g=r.makeTensorInfo(m,n,f);return d.forEach(y=>r.disposeIntermediateTensorInfo(y)),g}if(e.length>Y().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let d=Math.floor(e.length/2),h=cu(e.slice(0,d),t,r),p=cu(e.slice(d),t,r),c=cu([h,p],t,r);return r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(p),c}if(Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].shape.length>1){let d=new Tne(e.map(h=>h.shape),t);return r.runWebGLProgram(d,e,n)}let{tensors2D:s,outShape:i}=Cne(e,t,r),o=new Sne(s.map(d=>d.shape)),l=r.runWebGLProgram(o,s,n);s.forEach(d=>r.disposeIntermediateTensorInfo(d));let u=ve({inputs:{x:l},attrs:{shape:i},backend:r});return r.disposeIntermediateTensorInfo(l),u}function Cne(e,t,r){let n=N.computeOutShape(e.map(a=>a.shape),t);return{tensors2D:e.map(a=>ve({inputs:{x:a},attrs:{shape:[-1,w.sizeFromShape(a.shape.slice(t))]},backend:r})),outShape:n}}function p8(e){let{inputs:t,backend:r,attrs:n}=e,{axis:a}=n,s=w.parseAxisParam(a,t[0].shape)[0],i=N.computeOutShape(t.map(u=>u.shape),s);if(w.sizeFromShape(i)===0)return r.makeTensorInfo(i,t[0].dtype,[]);let o=t.filter(u=>w.sizeFromShape(u.shape)>0);if(o.length===1)return sn({inputs:{x:o[0]},backend:r});let l=o.map(u=>u.shape);return N.assertParamsConsistent(l,s),cu(o,s,r)}var Ene={kernelName:Go,backendName:"webgl",kernelFunc:p8},h8=class{constructor(e,t=!1,r=null,n=!1,a=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let s=e.padInfo.top,i=e.padInfo.left,o=e.strideHeight,l=e.strideWidth,u=e.dilationHeight,d=e.dilationWidth,h=e.filterHeight,p=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&&(n?x=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${r}
|
|
}`:a?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"),n&&this.variableNames.push("preluActivationWeights"),a&&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 < ${h}; wR++) {
|
|
int xR = xRCorner + wR * ${u};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${p}; wC++) {
|
|
int xC = xCCorner + wC * ${d};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int d1 = 0; d1 < ${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);
|
|
}
|
|
`}},Rne=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let t=e.padInfo.front,r=e.padInfo.top,n=e.padInfo.left,a=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,u=e.dilationWidth,d=e.filterDepth,h=e.filterHeight,p=e.filterWidth,c=Math.floor(e.inChannels/4)*4,f=e.inChannels%4;this.userCode=`
|
|
const ivec3 strides = ivec3(${a}, ${s}, ${i});
|
|
const ivec3 pads = ivec3(${t}, ${r}, ${n});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int d2 = coords.u;
|
|
|
|
ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
|
|
int xFCorner = xFRCCorner.x;
|
|
int xRCorner = xFRCCorner.y;
|
|
int xCCorner = xFRCCorner.z;
|
|
|
|
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
|
|
// y(yF, yR, yC, d2). ? = to be determined. : = across all
|
|
// values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wF = 0; wF < ${d}; wF++) {
|
|
int xF = xFCorner + wF * ${o};
|
|
|
|
if (xF < 0 || xF >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${h}; wR++) {
|
|
int xR = xRCorner + wR * ${l};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${p}; wC++) {
|
|
int xC = xCCorner + wC * ${u};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int d1 = 0; d1 < ${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);
|
|
}
|
|
`}},Mne=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=ln(this.outputShape.length);let{dataFormat:r}=t,n=jr(),a=r==="channelsLast",s=a?0:1,i=a?1:2,o=this.enableShapeUniforms?"if(blockIndex < outShape[1] && pos < outShape[0]) {":`if(blockIndex < ${e[1]} && pos < ${e[0]}) {`,l="";for(let u=0;u<=1;u++)for(let d=0;d<=1;d++)l+=`
|
|
blockIndex = rc.y + ${d};
|
|
pos = rc.x + ${u};
|
|
|
|
${o}
|
|
offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];
|
|
d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);
|
|
|
|
if(d0 < inputShape[${s}] && d0 >= 0) {
|
|
// Use custom imod instead mod. On Intel GPU, mod may generate
|
|
// unexpected value.
|
|
// https://github.com/tensorflow/tfjs/issues/5447
|
|
offsetX = imod(blockIndex, outWidth) * stride[1] - pad[1];
|
|
d1 = offsetX + dilation[1] * (imod(pos, itemsPerBlockRow) /
|
|
inChannels);
|
|
|
|
if(d1 < inputShape[${i}] && d1 >= 0) {
|
|
|
|
ch = imod(pos, inChannels);
|
|
|
|
if (${a}) {
|
|
innerDims = vec2(d1, ch);
|
|
result[${u*2+d}] = getChannel(
|
|
getA(d0, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
} else {
|
|
innerDims = vec2(d0, d1);
|
|
result[${u*2+d}] = 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}
|
|
|
|
${n.output} = result;
|
|
}
|
|
`}};function c8({x:e,filter:t,convInfo:r,backend:n,bias:a=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let l=e.shape,u=n.texData.get(e.dataId),d=r.inChannels,h=l[0]*l[1]*l[2],p=r.outChannels,c=r.dataFormat==="channelsLast",f=!1,m=!1,g,y=[];if(!((h===1||p===1)&&d>i8)&&u.isPacked&&c&&u.texture!=null&&l[2]%2!==0&&w.arraysEqual(u.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=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,w.assert(jp(u.shape,x.shape),()=>`packed reshape ${u.shape} to ${x.shape} isn't free`);let v=ve({inputs:{x:t},backend:n,attrs:{shape:[1,r.inChannels,r.outChannels]}});y.push(v);let S=Bf({a:x,b:v,backend:n,transposeA:f,transposeB:m,bias:a,activation:o,preluActivationWeights:s,leakyreluAlpha:i}),T=n.texData.get(S.dataId);w.assert(T.isPacked,()=>"batchMatMul result is expected to be packed"),u.shape=b,T.shape=r.outShape,g=sn({inputs:{x:S},backend:n}),g.shape=r.outShape,y.push(S)}else{let A=c?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],x=ve({inputs:{x:e},backend:n,attrs:{shape:[1,A,r.inChannels]}}),b=ve({inputs:{x:t},backend:n,attrs:{shape:[1,r.inChannels,r.outChannels]}}),v=Bf({a:x,b,transposeA:f,transposeB:m,backend:n,bias:a,activation:o,preluActivationWeights:s,leakyreluAlpha:i});g=ve({inputs:{x:v},backend:n,attrs:{shape:r.outShape}}),y.push(x),y.push(b),y.push(v)}for(let A of y)n.disposeIntermediateTensorInfo(A);return g}function f8({x:e,filter:t,convInfo:r,backend:n,bias:a=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let{filterWidth:l,filterHeight:u,inChannels:d,outWidth:h,outHeight:p,dataFormat:c}=r,f=c==="channelsLast",m=l*u*d,g=p*h,y=[m,g],A=!0,x=!1,b=[],v=ve({inputs:{x:e},backend:n,attrs:{shape:e.shape.slice(1)}}),S=ve({inputs:{x:t},backend:n,attrs:{shape:[1,m,w.sizeFromShape(t.shape)/m]}});b.push(v),b.push(S);let T=new Mne(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=n.runWebGLProgram(T,[v],"float32",E),_=ve({inputs:{x:R},backend:n,attrs:{shape:[1,y[0],y[1]]}});b.push(R),b.push(_);let M=a!=null,I=s!=null,z=o==="leakyrelu",O=o?v0(o,!0):null,j=new s8(_.shape,S.shape,[1,g,r.outChannels],A,x,M,O,I,z),X=[_,S];if(a&&X.push(a),I&&X.push(s),z){let ee=n.makeTensorInfo([],"float32",w.createScalarValue(i,"float32"));X.push(ee),b.push(ee)}let D=n.runWebGLProgram(j,X,"float32"),Q=f?[1,p,h,r.outChannels]:[1,r.outChannels,p,h],V=ve({inputs:{x:D},backend:n,attrs:{shape:Q}});b.push(D);for(let ee of b)n.disposeIntermediateTensorInfo(ee);return V}function Fne(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:d}=n,h=N.convertConv2DDataFormat(l),p=N.computeConv2DInfo(a.shape,s.shape,i,u,o,d,!1,h),c;if(p.filterHeight===1&&p.filterWidth===1&&p.dilationHeight===1&&p.dilationWidth===1&&p.strideHeight===1&&p.strideWidth===1&&(p.padInfo.type==="SAME"||p.padInfo.type==="VALID"))c=c8({x:a,filter:s,convInfo:p,backend:r});else if(Y().getBool("WEBGL_CONV_IM2COL")&&a.shape[0]===1)c=f8({x:a,filter:s,convInfo:p,backend:r});else{let m=new h8(p);c=r.runWebGLProgram(m,[a,s],"float32")}let f=ve({inputs:{x:c},backend:r,attrs:{shape:p.outShape}});return r.disposeIntermediateTensorInfo(c),f}var $ne={kernelName:ei,backendName:"webgl",kernelFunc:Fne},Pne=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,r=e.strideWidth,n=e.padInfo.top,a=e.padInfo.left,s=e.dataFormat==="channelsLast";this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int wR = coords.x;
|
|
int wC = coords.y;
|
|
int d1 = coords.z;
|
|
int d2 = coords.w;
|
|
|
|
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
|
|
for (int b = 0; b < ${e.batchSize}; b++) {
|
|
for (int yR = 0; yR < ${e.outHeight}; yR++) {
|
|
int xR = wR + yR * ${t} - ${n};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${r} - ${a};
|
|
|
|
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);
|
|
}
|
|
`}},_ne=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,r=e.filterWidth,n=e.strideHeight,a=e.strideWidth,s=e.dataFormat==="channelsLast",i=t-1-e.padInfo.top,o=r-1-e.padInfo.left,l=s?1:2,u=s?2:3,d=s?3:1;this.userCode=`
|
|
const ivec2 pads = ivec2(${i}, ${o});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d1 = coords[${d}];
|
|
|
|
ivec2 dyCorner = ivec2(coords[${l}], coords[${u}]) - pads;
|
|
int dyRCorner = dyCorner.x;
|
|
int dyCCorner = dyCorner.y;
|
|
|
|
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < ${t}; wR++) {
|
|
float dyR = float(dyRCorner + wR) / ${n}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
int wRPerm = ${t} - 1 - wR;
|
|
|
|
for (int wC = 0; wC < ${r}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${a}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
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);
|
|
}
|
|
`}},zne=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideDepth,r=e.strideHeight,n=e.strideWidth,a=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} - ${a};
|
|
|
|
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 * ${n} - ${i};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
float dyValue = getDy(b, yF, yR, yC, d2);
|
|
float xValue = getX(b, xF, xR, xC, d1);
|
|
dotProd += (xValue * dyValue);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},One=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterDepth,r=e.filterHeight,n=e.filterWidth,a=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=t-1-e.padInfo.front,l=r-1-e.padInfo.top,u=n-1-e.padInfo.left;this.userCode=`
|
|
const ivec3 pads = ivec3(${o}, ${l}, ${u});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int d1 = coords.u;
|
|
|
|
|
|
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
|
|
int dyFCorner = dyCorner.x;
|
|
int dyRCorner = dyCorner.y;
|
|
int dyCCorner = dyCorner.z;
|
|
|
|
float dotProd = 0.0;
|
|
for (int wF = 0; wF < ${t}; wF++) {
|
|
float dyF = float(dyFCorner + wF) / ${a}.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 < ${n}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${i}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
int wCPerm = ${n} - 1 - wC;
|
|
|
|
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
|
|
float xValue = getDy(batch, idyF, idyR, idyC, d2);
|
|
float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2);
|
|
dotProd += xValue * wValue;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function Dne(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,dy:s}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,filterShape:d}=n,h=N.convertConv2DDataFormat(l),p=N.computeConv2DInfo(a.shape,d,i,1,o,u,!1,h),c=new Pne(p);return r.runWebGLProgram(c,[a,s],"float32")}var Lne={kernelName:Jf,backendName:"webgl",kernelFunc:Dne};function Bne(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:u,dimRoundingMode:d}=n,h=N.convertConv2DDataFormat(u),p=N.computeConv2DInfo(i,s.shape,o,1,l,d,!1,h),c=new _ne(p);return r.runWebGLProgram(c,[a,s],"float32")}var Wne={kernelName:ti,backendName:"webgl",kernelFunc:Bne};function Vne(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dilations:l}=n,u=N.computeConv3DInfo(a.shape,s.shape,i,l,o),d=new Rne(u);return r.runWebGLProgram(d,[a,s],"float32")}var Une={kernelName:Yp,backendName:"webgl",kernelFunc:Vne};function Gne(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,dy:s}=t,{strides:i,pad:o,filterShape:l}=n,u=N.computeConv3DInfo(a.shape,l,i,1,o),d=new zne(u);return r.runWebGLProgram(d,[a,s],"float32")}var jne={kernelName:Qf,backendName:"webgl",kernelFunc:Gne};function Hne(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,filter:s}=t,{pad:i,strides:o,inputShape:l}=n,u=N.computeConv3DInfo(l,s.shape,o,1,i),d=new One(u);return r.runWebGLProgram(d,[a,s],"float32")}var qne={kernelName:em,backendName:"webgl",kernelFunc:Hne},Kne=Td+`
|
|
return cos(x);
|
|
`,Xne=it({opSnippet:Kne}),Zne={kernelName:ri,backendName:"webgl",kernelFunc:Xne},Yne=`
|
|
float e2x = exp(-x);
|
|
return (e2x + 1.0 / e2x) / 2.0;
|
|
`,Jne=it({opSnippet:Yne}),Qne={kernelName:ni,backendName:"webgl",kernelFunc:Jne},eae=class{constructor(e,t,r,n,a){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[s,i,o,l]=e,[u]=t,[d,h]=r;this.outputShape=[u,d,h,l];let p=n==="bilinear"?1:0,[c,f]=[`${i-1}.0`,`${o-1}.0`],[m,g,y]=d>1?[`${(i-1)/(d-1)}`,"(y2-y1) * height_ratio",`y1*${c} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${c}`],[A,x,b]=h>1?[`${(o-1)/(h-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(${a}));
|
|
return;
|
|
}
|
|
float in_x = ${b};
|
|
if( in_x < 0.0 || in_x > ${f} ) {
|
|
setOutput(float(${a}));
|
|
return;
|
|
}
|
|
|
|
vec2 sourceFracIndexCR = vec2(in_x,in_y);
|
|
if(${p} == 1) {
|
|
// Compute the four integer indices.
|
|
ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
|
|
ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
|
|
|
|
float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
|
|
float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
|
|
float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
|
|
float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);
|
|
|
|
vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
|
|
|
|
float top = topLeft + (topRight - topLeft) * fracCR.x;
|
|
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
|
|
float newValue = top + (bottom - top) * fracCR.y;
|
|
setOutput(newValue);
|
|
} else {
|
|
// Compute the coordinators of nearest neighbor point.
|
|
ivec2 sourceNearestCR = ivec2(floor(
|
|
sourceFracIndexCR + vec2(0.5,0.5)));
|
|
float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
|
|
setOutput(newValue);
|
|
}
|
|
}
|
|
`}},tae=e=>{let{inputs:t,backend:r,attrs:n}=e,{image:a,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=n,d=new eae(a.shape,s.shape,o,l,u);return r.runWebGLProgram(d,[a,s,i],"float32")},rae={kernelName:Ho,backendName:"webgl",kernelFunc:tae},Gv=class{constructor(e,t,r){this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}],this.outputShape=e;let n=e.length,a=t?"1.0":`getX(${jv(n,"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() {
|
|
${gt(n)} coords = getOutputCoords();
|
|
int end = ${Hv(n,"coords")};
|
|
float val = ${a};
|
|
int pow2 = int(pow(2.0, index));
|
|
if (${i}) {
|
|
int idx = ${o};
|
|
${Hv(n,"coords")} = idx;
|
|
val *= getX(${jv(n,"coords")});
|
|
}
|
|
setOutput(val);
|
|
}
|
|
`}};function jv(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 product for rank ${e} is not yet supported`)}function Hv(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 product for rank ${e} is not yet supported`)}function nae(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,exclusive:i,reverse:o}=n,l=a.shape.length,u=N.getAxesPermutation([s],l),d=a;u!=null&&(d=vr({inputs:{x:a},backend:r,attrs:{perm:u}}));let h=N.getInnerMostAxes(1,l)[0];if(h!==l-1)throw new Error(`WebGL cumprod shader expects an inner-most axis=${a.shape.length-1} but got axis=${s}`);let p=d.shape[h],c=sn({inputs:{x:d},backend:r});for(let f=0;f<=Math.ceil(Math.log2(p))-1;f++){let m=new Gv(d.shape,!1,o),g=[[f]],y=c;c=r.runWebGLProgram(m,[c],c.dtype,g),r.disposeIntermediateTensorInfo(y)}if(i){let f=new Gv(d.shape,i,o),m=c;c=r.runWebGLProgram(f,[c],c.dtype),r.disposeIntermediateTensorInfo(m)}if(u!=null){let f=N.getUndoAxesPermutation(u),m=vr({inputs:{x:c},backend:r,attrs:{perm:f}});return r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(d),m}return c}var aae={kernelName:jo,backendName:"webgl",kernelFunc:nae},qv=class{constructor(e,t,r){this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}],this.outputShape=e;let n=e.length,a=t?"0.0":`getX(${Kv(n,"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() {
|
|
${gt(n)} coords = getOutputCoords();
|
|
int end = ${Xv(n,"coords")};
|
|
float val = ${a};
|
|
int pow2 = int(pow(2.0, index));
|
|
if (${i}) {
|
|
int idx = ${o};
|
|
${Xv(n,"coords")} = idx;
|
|
val += getX(${Kv(n,"coords")});
|
|
}
|
|
setOutput(val);
|
|
}
|
|
`}};function Kv(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 Xv(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 sae(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,exclusive:i,reverse:o}=n,l=a.shape.length,u=N.getAxesPermutation([s],l),d=a;u!=null&&(d=vr({inputs:{x:a},backend:r,attrs:{perm:u}}));let h=N.getInnerMostAxes(1,l)[0];if(h!==l-1)throw new Error(`WebGL cumsum shader expects an inner-most axis=${a.shape.length-1} but got axis=${s}`);let p=d.shape[h],c=sn({inputs:{x:d},backend:r});for(let f=0;f<=Math.ceil(Math.log2(p))-1;f++){let m=new qv(d.shape,!1,o),g=[[f]],y=c;c=r.runWebGLProgram(m,[c],c.dtype,g),r.disposeIntermediateTensorInfo(y)}if(i){let f=new qv(d.shape,i,o),m=c;c=r.runWebGLProgram(f,[c],c.dtype),r.disposeIntermediateTensorInfo(m)}if(u!=null){let f=N.getUndoAxesPermutation(u),m=vr({inputs:{x:c},backend:r,attrs:{perm:f}});return r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(d),m}return c}var iae={kernelName:ai,backendName:"webgl",kernelFunc:sae};function oae(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,weights:s}=t,{size:i,binaryOutput:o}=n;if(a.shape.length===1){let l=r.readSync(a.dataId),u=r.readSync(s.dataId),d=qS(l,u,s.dtype,s.shape,i);return r.makeTensorInfo([i],s.dtype,d)}else if(a.shape.length===2){let l=r.bufferSync(a),u=r.bufferSync(s),d=bee(l,u,i,o);return r.makeTensorInfo(d.shape,s.dtype,d.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${a.shape.length}.`)}var lae={kernelName:tm,backendName:"webgl",kernelFunc:oae},uae=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 dae(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockSize:s,dataFormat:i}=n,o=a.shape[0],l=i==="NHWC"?a.shape[1]:a.shape[2],u=i==="NHWC"?a.shape[2]:a.shape[3],d=i==="NHWC"?a.shape[3]:a.shape[1],h=l*s,p=u*s,c=d/(s*s),f=i==="NHWC"?[o,h,p,c]:[o,c,h,p],m=new uae(f,s,i);return r.runWebGLProgram(m,[a],a.dtype)}var pae={kernelName:qo,backendName:"webgl",kernelFunc:dae},m8=class{constructor(e,t=!1,r=null,n=!1,a=!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=ln(this.outputShape.length);let s=e.filterHeight,i=e.filterWidth,o=e.outChannels/e.inChannels,l="",u="";r&&(n?l=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${r}
|
|
}`:a?l=`float activation(float a) {
|
|
float b = getLeakyreluAlphaAtOutCoords();
|
|
${r}
|
|
}`:l=`
|
|
float activation(float x) {
|
|
${r}
|
|
}
|
|
`,u="result = activation(result);");let d=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),a&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${l}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int d2 = coords.w;
|
|
int d1 = d2 / ${o};
|
|
int q = d2 - d1 * ${o};
|
|
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
|
|
for (int wR = 0; wR < ${s}; wR++) {
|
|
int xR = xRCorner + wR * dilations[0];
|
|
|
|
if (xR < 0 || xR >= inDims[0]) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${i}; wC++) {
|
|
int xC = xCCorner + wC * dilations[1];
|
|
|
|
if (xC < 0 || xC >= inDims[1]) {
|
|
continue;
|
|
}
|
|
|
|
float xVal = getX(batch, xR, xC, d1);
|
|
float wVal = getW(wR, wC, d1, q);
|
|
dotProd += xVal * wVal;
|
|
}
|
|
}
|
|
|
|
float result = dotProd;
|
|
${d}
|
|
${u}
|
|
setOutput(result);
|
|
}
|
|
`}},g8=class{constructor(e,t=!1,r=null,n=!1,a=!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=ln(this.outputShape.length);let s=e.outChannels/e.inChannels,i=e.padInfo.left,o=e.strideWidth,l=e.dilationWidth,u=e.filterHeight,d=e.filterWidth,h=d,p=`
|
|
int xR; int xC; int xCOffset;
|
|
vec4 wTexel; vec4 previous; vec4 final;`;for(let g=0;g<d;g++)p+=`
|
|
vec4 xTexelC${g*2};
|
|
int xTexelC${g*2}Ready;
|
|
vec4 xTexelC${g*2+1};
|
|
int xTexelC${g*2+1}Ready;
|
|
vec4 xC${g};`;p+=`
|
|
for (int r = 0; r < ${u}; r++) {
|
|
`;for(let g=0;g<d;g++)p+=`
|
|
xTexelC${g*2} = vec4(0.0);
|
|
xTexelC${g*2}Ready = 0;
|
|
xTexelC${g*2+1} = vec4(0.0);
|
|
xTexelC${g*2+1}Ready = 0;
|
|
xC${g} = vec4(0.0);`;p+=`
|
|
xR = xRCorner + r * dilations[0];
|
|
if (xR >=0 && xR < inDims[0]) {
|
|
`;for(let g=0;g<(h+1)/2;g++){let y=g*2;if(p+=`
|
|
xC = xCCorner + ${y*l};
|
|
`,o===1){if(y<d&&(i%2===1?(p+=`
|
|
xCOffset = xC + 1;
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) {
|
|
xTexelC${y} = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${y}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${y}Ready = 1;
|
|
}
|
|
`,l===1&&y>0?p+=`
|
|
xC${y} = vec4(xTexelC${y-2}.zw, xTexelC${y}.xy);
|
|
`:p+=`
|
|
xCOffset = xC + 1 - 2;
|
|
|
|
if (xCOffset >= 0 && xCOffset < inDims[1]) {
|
|
previous = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
previous.zw = vec2(0.0);
|
|
}
|
|
|
|
xC${y} = vec4(previous.zw, xTexelC${y}.xy);
|
|
} else {
|
|
xC${y} = vec4(0.0, 0.0, xTexelC${y}.xy);
|
|
}
|
|
`):p+=`
|
|
if (xC >= 0 && xC < inDims[1] && xTexelC${y}Ready == 0) {
|
|
xTexelC${y} = getX(batch, xR, xC, d1);
|
|
if (xC + 1 >= inDims[1]) {
|
|
xTexelC${y}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${y}Ready = 1;
|
|
}
|
|
|
|
xC${y} = xTexelC${y};
|
|
`,y+1<d)){let A=i%2===0?w.nearestLargerEven(l):l;l%2===0&&i%2===1||l%2!==0&&i%2!==1?(p+=`
|
|
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&&(p+=`
|
|
xCOffset -= 2;
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) {
|
|
xTexelC${y} = getX(batch, xR, xCOffset, d1);
|
|
xTexelC${y}Ready = 1;
|
|
}
|
|
`),p+=`
|
|
xC${y+1} = vec4(xTexelC${y}.zw, xTexelC${y+1}.xy);
|
|
`):A===1?p+=`
|
|
xC${y+1} = xTexelC${y};
|
|
`:p+=`
|
|
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<d&&(i%2===1?(p+=`
|
|
xCOffset = xC + 1 - strides[1];
|
|
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) {
|
|
xTexelC${y} = getX(batch, xR, xCOffset, d1);
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${y}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${y}Ready = 1;
|
|
}
|
|
|
|
if(xC + 1 >= 0 && xC + 1 < inDims[1] && xTexelC${y+1}Ready == 0) {
|
|
xTexelC${y+1} = getX(batch, xR, xC + 1, d1);
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xC + 2 >= inDims[1]) {
|
|
xTexelC${y+1}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${y+1}Ready = 1;
|
|
}
|
|
|
|
xC${y} = vec4(xTexelC${y}.zw, xTexelC${y+1}.zw);
|
|
`,y+1<d&&(p+=`
|
|
final = vec4(0.0);
|
|
xCOffset = xC + 1 + strides[1];
|
|
if(xCOffset >= 0 && xCOffset < inDims[1]) {
|
|
final = getX(batch, xR, xCOffset, d1);
|
|
}
|
|
xC${y+1} = vec4(xTexelC${y+1}.xy, final.xy);
|
|
`)):(p+=`
|
|
if(xC >= 0 && xC < inDims[1] && xTexelC${y}Ready == 0) {
|
|
xTexelC${y} = getX(batch, xR, xC, d1);
|
|
if (xC + 1 >= inDims[1]) {
|
|
xTexelC${y}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${y}Ready = 1;
|
|
}
|
|
|
|
xCOffset = xC + strides[1];
|
|
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) {
|
|
xTexelC${y+1} = getX(batch, xR, xCOffset, d1);
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${y+1}.zw = vec2(0.);
|
|
}
|
|
xTexelC${y+1}Ready = 1;
|
|
}
|
|
|
|
xC${y} = vec4(
|
|
xTexelC${y}.xy, xTexelC${y+1}.xy);
|
|
`,y+1<d&&(p+=`
|
|
xC${y+1} = vec4(xTexelC${y}.zw, xTexelC${y+1}.zw);
|
|
`)));y<d&&(p+=`
|
|
wTexel = getW(r, ${y}, d1, q);
|
|
dotProd += xC${y} * vec4(wTexel.xz, wTexel.xz);
|
|
`,y+1<d&&(p+=`
|
|
wTexel = getW(r, ${y+1}, d1, q);
|
|
dotProd += xC${y+1} * vec4(wTexel.xz, wTexel.xz);
|
|
`))}p+=`
|
|
}
|
|
`,p+=`
|
|
}
|
|
`;let c="",f="";r&&(n?c=`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${r}
|
|
}`:a?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"),n&&this.variableNames.push("preluActivationWeights"),a&&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);
|
|
|
|
${p}
|
|
|
|
vec4 result = dotProd - vec4(0.000000000000001);
|
|
${m}
|
|
${f}
|
|
setOutput(result);
|
|
}
|
|
`}};function hae(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:u}=n,d=l;d==null&&(d=[1,1]),w.assert(N.eitherStridesOrDilationsAreOne(i,d),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${d}'`);let h=N.computeConv2DInfo(a.shape,s.shape,i,d,o,u,!0),p;Y().getBool("WEBGL_PACK_DEPTHWISECONV")&&h.strideWidth<=2&&h.outChannels/h.inChannels===1?p=new g8(h):p=new m8(h);let c=[[h.padInfo.top,h.padInfo.left],[h.strideHeight,h.strideWidth],[h.dilationHeight,h.dilationWidth],[h.inHeight,h.inWidth]];return r.runWebGLProgram(p,[a,s],"float32",c)}var cae={kernelName:si,backendName:"webgl",kernelFunc:hae},fae=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,r=e.strideWidth,n=e.padInfo.top,a=e.padInfo.left,s=e.outChannels/e.inChannels;this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int wR = coords.x;
|
|
int wC = coords.y;
|
|
int d1 = coords.z;
|
|
int dm = coords.w;
|
|
int d2 = d1 * ${s} + dm;
|
|
|
|
float dotProd = 0.0;
|
|
|
|
// TO DO: Vec4 over the batch size
|
|
for (int b = 0; b < ${e.batchSize}; b++) {
|
|
for (int yR = 0; yR < ${e.outHeight}; yR++) {
|
|
int xR = wR + yR * ${t} - ${n};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${r} - ${a};
|
|
|
|
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);
|
|
}
|
|
`}},mae=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,r=e.filterWidth,n=e.strideHeight,a=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) / ${n}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
int wRPerm = ${t} - 1 - wR;
|
|
|
|
for (int wC = 0; wC < ${r}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${a}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
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 gae(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,dy:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,filterShape:d}=n,h=N.computeConv2DInfo(a.shape,d,i,o,l,u,!0),p=new fae(h);return r.runWebGLProgram(p,[a,s],"float32")}var yae={kernelName:rm,backendName:"webgl",kernelFunc:gae};function Aae(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,filter:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,inputShape:d}=n,h=N.computeConv2DInfo(d,s.shape,i,o,l,u,!0),p=new mae(h);return r.runWebGLProgram(p,[a,s],"float32")}var xae={kernelName:nm,backendName:"webgl",kernelFunc:Aae},bae=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 vae(e){let{inputs:t,backend:r}=e,{x:n}=t,a=[...n.shape,...n.shape],s=w.sizeFromShape(n.shape),i=ve({inputs:{x:n},backend:r,attrs:{shape:[s]}}),o=new bae(s),l=r.runWebGLProgram(o,[i],i.dtype),u=ve({inputs:{x:l},backend:r,attrs:{shape:a}});return r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(l),u}var wae={kernelName:am,backendName:"webgl",kernelFunc:vae},kae=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let{inHeight:t,inWidth:r,padInfo:n,strideHeight:a,strideWidth:s,filterHeight:i,filterWidth:o,dilationHeight:l,dilationWidth:u}=e,{top:d,left:h}=n;this.userCode=`
|
|
const ivec2 strides = ivec2(${a}, ${s});
|
|
const ivec2 pads = ivec2(${d}, ${h});
|
|
const float neg_infinity = -3.4e38;
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int d1 = coords.w;
|
|
ivec2 outTopLeftCorner =
|
|
coords.yz * strides - pads;
|
|
int hBeg = outTopLeftCorner.x;
|
|
int wBeg = outTopLeftCorner.y;
|
|
|
|
float curVal = neg_infinity;
|
|
for (int h = 0; h < ${i}; h++) {
|
|
int hIn = hBeg + h * ${l};
|
|
|
|
if (hIn >= 0 && hIn < ${t}) {
|
|
for (int w = 0; w < ${o}; w++) {
|
|
int wIn = wBeg + w * ${u};
|
|
|
|
if (wIn >= 0 && wIn < ${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 Iae(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dilations:l}=n,u=N.computeDilation2DInfo(a.shape,s.shape,i,o,"NHWC",l),d,h=new kae(u);d=r.runWebGLProgram(h,[a,s],"float32");let p=ve({inputs:{x:d},backend:r,attrs:{shape:u.outShape}});return r.disposeIntermediateTensorInfo(d),p}var Sae={kernelName:Jp,backendName:"webgl",kernelFunc:Iae};function Tae(e){let{inputs:t,backend:r,attrs:n}=e,{equation:a}=n,s=t,{allDims:i,summedDims:o,idDims:l}=N.decodeEinsumEquation(a,s.length);N.checkEinsumDimSizes(i.length,l,s);let{path:u,steps:d}=N.getEinsumComputePath(o,l),h=d.length,p=null,c=i.length,f=[];for(let m=0;m<h;++m){for(let g of d[m]){let{permutationIndices:y,expandDims:A}=N.getEinsumPermutation(c,l[g]),x;N.isIdentityPermutation(y)?x=s[g]:(x=vr({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)),p===null?p=x:(p=yb({inputs:{a:x,b:p},backend:r}),f.push(p))}m<h-1&&(u[m]>=0&&(p=k0({inputs:{x:p},backend:r,attrs:{axis:u[m]-(i.length-c),keepDims:!1}}),f.push(p)),c--)}for(let m of f)m!==p&&r.disposeIntermediateTensorInfo(m);return p}var Nae={kernelName:Qp,backendName:"webgl",kernelFunc:Tae},Cae="return (x >= 0.0) ? x : (exp(x) - 1.0);",Eae=`
|
|
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;
|
|
`,Rae=it({opSnippet:Cae,packedOpSnippet:Eae}),Mae={kernelName:oi,backendName:"webgl",kernelFunc:Rae},Fae="return (b >= 1.0) ? a : a * (b + 1.0);",$ae=`
|
|
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
|
|
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
|
|
`,Pae=e=>{let{inputs:t,backend:r}=e,{dy:n,y:a}=t,s=Y().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Dh($ae,n.shape,a.shape):new Fu(Fae,n.shape,a.shape);return r.runWebGLProgram(s,[n,a],n.dtype)},_ae={kernelName:sm,backendName:"webgl",kernelFunc:Pae},zae=`
|
|
return vec4(equal(a, b));
|
|
`,Oae="return float(a == b);",Dae=wr({opSnippet:Oae,packedOpSnippet:zae,dtype:"bool",cpuKernelImpl:kee}),Lae={kernelName:Ko,backendName:"webgl",kernelFunc:Dae},Bae=`
|
|
// 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));
|
|
`,Wae=it({opSnippet:Bae}),Vae={kernelName:ju,backendName:"webgl",kernelFunc:Wae},Uae=Td+`
|
|
return exp(x);
|
|
`,Gae=`
|
|
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;
|
|
`,y8=it({opSnippet:Uae,packedOpSnippet:Gae,cpuKernelImpl:Iee,dtype:"float32"}),jae={kernelName:li,backendName:"webgl",kernelFunc:y8};function e2(e){let{inputs:t,attrs:r,backend:n}=e,{dim:a}=r,{input:s}=t,i=s.shape.length,o=s.shape.slice(),l=a;return a<0&&(w.assert(-(i+1)<=a,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+a+1),o.splice(l,0,1),ve({inputs:{x:s},backend:n,attrs:{shape:o}})}var Hae={kernelName:Xo,backendName:"webgl",kernelFunc:e2},Zv="return exp(x) - 1.0;",qae=it({opSnippet:Zv,packedOpSnippet:Zv,cpuKernelImpl:See}),Kae={kernelName:Zo,backendName:"webgl",kernelFunc:qae},Yv=class{constructor(e,t,r){this.variableNames=["real","imag"];let n=t[1];this.outputShape=t;let a=r?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,s=r?`${n}.0`:"1.0",i;if(e==="real")i="return real * expR - imag * expI;";else if(e==="imag")i="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);this.userCode=`
|
|
const float exponentMultiplier = ${a};
|
|
|
|
float unaryOpComplex(float real, float expR, float imag, float expI) {
|
|
${i}
|
|
}
|
|
|
|
float mulMatDFT(int batch, int index) {
|
|
float indexRatio = float(index) / float(${n});
|
|
float exponentMultiplierTimesIndexRatio =
|
|
exponentMultiplier * indexRatio;
|
|
|
|
float result = 0.0;
|
|
|
|
for (int i = 0; i < ${n}; i++) {
|
|
// x = (-2|2 * PI / N) * index * i;
|
|
float x = exponentMultiplierTimesIndexRatio * float(i);
|
|
float expR = cos(x);
|
|
float expI = sin(x);
|
|
float real = getReal(batch, i);
|
|
float imag = getImag(batch, i);
|
|
|
|
result +=
|
|
unaryOpComplex(real, expR, imag, expI) / ${s};
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
setOutput(mulMatDFT(coords[0], coords[1]));
|
|
}
|
|
`}};function A8(e,t,r){let n=r.texData.get(e.dataId),a=w.sizeFromShape(e.shape),s=e.shape[e.shape.length-1],i=a/s,o=ve({inputs:{x:e},backend:r,attrs:{shape:[i,s]}}),l=o.shape,u=new Yv("real",l,t),d=new Yv("imag",l,t),h=[{dataId:n.complexTensorInfos.real.dataId,dtype:n.complexTensorInfos.real.dtype,shape:l},{dataId:n.complexTensorInfos.imag.dataId,dtype:n.complexTensorInfos.imag.dtype,shape:l}],p=r.runWebGLProgram(u,h,"float32"),c=r.runWebGLProgram(d,h,"float32"),f=ji({inputs:{real:p,imag:c},backend:r});r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(c);let m=ve({inputs:{x:f},backend:r,attrs:{shape:e.shape}});return r.disposeIntermediateTensorInfo(o),r.disposeIntermediateTensorInfo(f),m}function Xae(e){let{inputs:t,backend:r}=e,{input:n}=t;return A8(n,!1,r)}var Zae={kernelName:im,backendName:"webgl",kernelFunc:Xae},Yae=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 Bh(e){let{backend:t,attrs:r}=e,{shape:n,value:a}=r,{dtype:s}=r;if(s=s||w.inferDtype(a),s==="string"){let i=w.getArrayFromDType(s,w.sizeFromShape(n));return i.fill(a),t.makeTensorInfo(n,s,i)}else{let i=new Yae(n,a),o=[[a]];return t.runWebGLProgram(i,[],s,o)}}var Jae={kernelName:Hu,backendName:"webgl",kernelFunc:Bh},Qae=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);
|
|
}
|
|
`}},ese={kernelName:Yo,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{let{image:r}=e,n=t,a=new Qae(r.shape);return n.runWebGLProgram(a,[r],r.dtype)}},Jv="return floor(x);",tse=it({opSnippet:Jv,packedOpSnippet:Jv,cpuKernelImpl:Tee}),rse={kernelName:ui,backendName:"webgl",kernelFunc:tse},nse=`
|
|
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;
|
|
}
|
|
`,ase=`
|
|
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);
|
|
`,sse=wr({opSnippet:nse,packedOpSnippet:ase,dtype:"int32"}),ise={kernelName:di,backendName:"webgl",kernelFunc:sse},ose=class{constructor(e){this.variableNames=["A"];let t=jr(),[r,n]=e;this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
int texR = coords[0];
|
|
int texC = coords[1];
|
|
int depth = coords[2];
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${n}.0, ${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));
|
|
}
|
|
`}},lse=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=jr(),[r,n]=e;this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
int texR = coords[0];
|
|
int texC = coords[1];
|
|
int depth = coords[2];
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
for(int row=0; row<=1; row++) {
|
|
for(int col=0; col<=1; col++) {
|
|
texC = coords[1] + row;
|
|
depth = coords[2] + col;
|
|
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${n}.0, ${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;
|
|
}
|
|
`}},use={kernelName:Pp,backendName:"webgl",kernelFunc:dse},lu;function dse(e){let{inputs:t,backend:r,attrs:n}=e,{pixels:a}=t,{numChannels:s}=n,i=typeof HTMLVideoElement!="undefined"&&a instanceof HTMLVideoElement,o=typeof HTMLImageElement!="undefined"&&a instanceof HTMLImageElement,[l,u]=i?[a.videoWidth,a.videoHeight]:[a.width,a.height],d=[u,l],h=[u,l,s];(o||i)&&(lu==null&&(lu=document.createElement("canvas").getContext("2d")),lu.canvas.width=l,lu.canvas.height=u,lu.drawImage(a,0,0,l,u),a=lu.canvas);let p=r.makeTensorInfo(d,"int32");r.texData.get(p.dataId).usage=2,r.gpgpu.uploadPixelDataToTexture(r.getTexture(p.dataId),a);let c=Y().getBool("WEBGL_PACK")?new lse(h):new ose(h),f=r.runWebGLProgram(c,[p],"int32");return r.disposeData(p.dataId),f}function pse(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:d,dilations:h,dimRoundingMode:p,activation:c,leakyreluAlpha:f}=n,m=N.convertConv2DDataFormat(d),g=N.computeConv2DInfo(a.shape,s.shape,l,h,u,p,!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=c8({x:a,filter:s,convInfo:g,backend:r,bias:i,activation:c,preluActivationWeights:o,leakyreluAlpha:f});else if(Y().getBool("WEBGL_CONV_IM2COL")&&a.shape[0]===1)y=f8({x:a,filter:s,convInfo:g,backend:r,bias:i,activation:c,preluActivationWeights:o,leakyreluAlpha:f});else{let b=i!=null,v=o!=null,S=c==="leakyrelu",T=c?v0(c,!1):null,E=new h8(g,b,T,v,S),R=[a,s];if(i&&R.push(i),o&&R.push(o),S){let _=r.makeTensorInfo([],"float32",w.createScalarValue(f,"float32"));R.push(_),A.push(_)}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 hse={kernelName:$s,backendName:"webgl",kernelFunc:pse};function cse(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:d,dimRoundingMode:h,activation:p,leakyreluAlpha:c}=n,f=[],m=d;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(a.shape,s.shape,l,m,u,h,!0),y=Y().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels===1,A=p?v0(p,y):null,x=[a,s],b=i!=null,v=o!=null,S=p==="leakyrelu";if(b&&x.push(i),v&&x.push(o),S){let _=r.makeTensorInfo([],"float32",w.createScalarValue(c,"float32"));x.push(_),f.push(_)}let T;y?T=new g8(g,b,A,v,S):T=new m8(g,b,A,v,S);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(_=>r.disposeIntermediateTensorInfo(_)),R}var fse={kernelName:Ps,backendName:"webgl",kernelFunc:cse},mse=class{constructor(e,t,r){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=r;let n=gt(t.length),a=gt(r.length),s=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
|
|
${n} strides = ${n}(${this.strides});
|
|
void main() {
|
|
${a} 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 gse(e){let{inputs:t,backend:r}=e,{params:n,indices:a}=t,s=a.shape,i=s[s.length-1],o=w.sizeFromShape(n.shape),[l,u,d,h]=N.prepareAndValidate(n,a),p=ve({inputs:{x:a},backend:r,attrs:{shape:[u,i]}}),c=ve({inputs:{x:n},backend:r,attrs:{shape:[w.sizeFromShape(n.shape)/d,d]}});if(r.shouldExecuteOnCPU([n,a])||n.dtype==="string"){let y=r.readSync(a.dataId),A=r.bufferSync(n),x=Nee(y,A,n.dtype,u,i,d,h,n.shape,o);return r.makeTensorInfo(l,n.dtype,x.values)}let f=new mse(i,h,[u,d]),m=r.runWebGLProgram(f,[c,p],c.dtype),g=ve({inputs:{x:m},backend:r,attrs:{shape:l}});return r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(c),r.disposeIntermediateTensorInfo(m),g}var yse={kernelName:Qo,backendName:"webgl",kernelFunc:gse},Ase=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let r=gt(this.rank),n=xse(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(${n}));
|
|
}
|
|
`}};function xse(e,t){let r=["resRC.x","resRC.y","resRC.z","resRC.w"],n=[];for(let a=0;a<e.length;a++)a===2?n.push("index"):n.push(`${r[a]}`);return n.join()}function x8(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,indices:s}=t,{axis:i,batchDims:o}=n,l=w.parseAxisParam(i,a.shape)[0];if(Y().get("DEBUG")){let A=r.readSync(s.dataId),x=a.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 u=N.segment_util.collectGatherOpShapeInfo(a,s,l,o),d=w.sizeFromShape(s.shape),h=[],p=ve({inputs:{x:a},backend:r,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),c=ve({inputs:{x:s},backend:r,attrs:{shape:[u.batchSize,d/u.batchSize]}});h.push(p),h.push(c);let f=[u.batchSize,u.outerSize,d/u.batchSize,u.sliceSize];if(r.shouldExecuteOnCPU([a,s])||a.dtype==="string"){let A=r.bufferSync(c),x=r.bufferSync(p),b=Cee(x,A,f);return h.forEach(v=>r.disposeIntermediateTensorInfo(v)),r.makeTensorInfo(u.outputShape,b.dtype,b.values)}let m=new Ase(p.shape,f),g=r.runWebGLProgram(m,[p,c],p.dtype);h.push(g);let y=ve({inputs:{x:g},backend:r,attrs:{shape:u.outputShape}});return h.forEach(A=>r.disposeIntermediateTensorInfo(A)),y}var bse={kernelName:Jo,backendName:"webgl",kernelFunc:x8},vse="return float(a > b);",wse=`
|
|
return vec4(greaterThan(a, b));
|
|
`,kse=wr({opSnippet:vse,packedOpSnippet:wse,cpuKernelImpl:Eee,dtype:"bool"}),Ise={kernelName:el,backendName:"webgl",kernelFunc:kse},Sse="return float(a >= b);",Tse=`
|
|
return vec4(greaterThanEqual(a, b));
|
|
`,Nse=wr({opSnippet:Sse,packedOpSnippet:Tse,dtype:"bool",cpuKernelImpl:Ree}),Cse={kernelName:hi,backendName:"webgl",kernelFunc:Nse};function Ese(e){let{inputs:t,backend:r}=e,{input:n}=t;return A8(n,!0,r)}var Rse={kernelName:om,backendName:"webgl",kernelFunc:Ese},Mse="return float(!isnan(x) && !isinf(x));",Fse=it({opSnippet:Mse,dtype:"bool"}),$se={kernelName:qu,backendName:"webgl",kernelFunc:Fse},Pse="return float(isinf(x));",_se=it({opSnippet:Pse,dtype:"bool"}),zse={kernelName:Ku,backendName:"webgl",kernelFunc:_se},Ose="return float(isnan(x));",Dse=it({opSnippet:Ose,dtype:"bool"}),Lse={kernelName:Xu,backendName:"webgl",kernelFunc:Dse},Bse="return float(a < b);",Wse=`
|
|
return vec4(lessThan(a, b));
|
|
`,Vse=wr({opSnippet:Bse,packedOpSnippet:Wse,cpuKernelImpl:Mee,dtype:"bool"}),Use={kernelName:tl,backendName:"webgl",kernelFunc:Vse},Gse="return float(a <= b);",jse=`
|
|
return vec4(lessThanEqual(a, b));
|
|
`,Hse=wr({opSnippet:Gse,packedOpSnippet:jse,cpuKernelImpl:Fee,dtype:"bool"}),qse={kernelName:rl,backendName:"webgl",kernelFunc:Hse};function Kse(e){let{backend:t,attrs:r}=e,{start:n,stop:a,num:s}=r,i=$ee(n,a,s);return t.makeTensorInfo([i.length],"float32",i)}var Xse={kernelName:lm,backendName:"webgl",kernelFunc:Kse},Zse=Td+`
|
|
return x < 0.0 ? 0./0. : log(x);
|
|
`,Yse=`
|
|
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;
|
|
`,Jse=it({opSnippet:Zse,packedOpSnippet:Yse,cpuKernelImpl:Pee}),Qse={kernelName:mi,backendName:"webgl",kernelFunc:Jse},eie=Td+`
|
|
return log(1.0 + x);
|
|
`,tie=it({opSnippet:eie}),rie={kernelName:Zu,backendName:"webgl",kernelFunc:tie},nie="return float(a >= 1.0 && b >= 1.0);",aie=`
|
|
return vec4(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) *
|
|
vec4(greaterThanEqual(b, vec4(1.0))));
|
|
`,sie=wr({opSnippet:nie,packedOpSnippet:aie,dtype:"bool"}),iie={kernelName:nl,backendName:"webgl",kernelFunc:sie},oie="return float(!(x >= 1.0));",lie=it({opSnippet:oie}),uie={kernelName:Yu,backendName:"webgl",kernelFunc:lie},die="return float(a >= 1.0 || b >= 1.0);",pie=`
|
|
return min(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) +
|
|
vec4(greaterThanEqual(b, vec4(1.0))),
|
|
vec4(1.0));
|
|
`,hie=wr({opSnippet:die,packedOpSnippet:pie,dtype:"bool"}),cie={kernelName:th,backendName:"webgl",kernelFunc:hie},fie=class{constructor(e,t,r,n,a){this.variableNames=["x"],this.outputShape=[];let s=t,i=e[3]-1;this.outputShape=e;let o,l=`float(${r}) + float(${n}) * sum`;a===.5?o=`inversesqrt(${l})`:a===1?o=`1.0/(${l})`:o=`exp(log(${l}) * float(-${a}));`,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);
|
|
}
|
|
`}},mie=class{constructor(e,t,r,n,a){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(${n}) * sum`;a===.5?o=`inversesqrt(${l})`:a===1?o=`1.0/(${l})`:o=`exp(log(${l}) * float(-${a}));`,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);
|
|
}
|
|
`}},gie=e=>{let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=n,u=Y().getBool("WEBGL_PACK_NORMALIZATION")?new mie(a.shape,s,i,o,l):new fie(a.shape,s,i,o,l);return r.runWebGLProgram(u,[a],a.dtype)},yie={kernelName:rh,backendName:"webgl",kernelFunc:gie},Aie=class{constructor(e,t,r,n,a){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=r,this.alpha=n,this.beta=a,this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int r = coords[1];
|
|
int c = coords[2];
|
|
|
|
float result = 0.0;
|
|
for (int d = 0; d < ${this.depth}; ++d) {
|
|
int depthBegin = int(max(0.0, float(d - ${t})));
|
|
int depthEnd = int(min(float(${this.depth}),
|
|
float(d + ${t} + 1)));
|
|
|
|
const int MIN_DEPTH_BEGIN = 0;
|
|
const int MAX_DEPTH_END = ${this.depth};
|
|
|
|
float norm = 0.0;
|
|
for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) {
|
|
if (k < depthBegin){
|
|
continue;
|
|
}
|
|
else if (k >= depthBegin && k < depthEnd) {
|
|
norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k);
|
|
}
|
|
else {
|
|
break;
|
|
}
|
|
}
|
|
|
|
norm = float(${n}) * norm + float(${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(${n})
|
|
* float(${a})
|
|
* getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)
|
|
/ norm;
|
|
if (k == d) {
|
|
dyi += pow(norm, -1.0 * ${a});
|
|
}
|
|
if (k == coords[3]) {
|
|
dyi *= getDy(b, r, c, d);
|
|
result += dyi;
|
|
}
|
|
}
|
|
else {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}},xie=e=>{let{inputs:t,backend:r,attrs:n}=e,{x:a,y:s,dy:i}=t,{depthRadius:o,bias:l,alpha:u,beta:d}=n,h=new Aie(a.shape,o,l,u,d);return r.runWebGLProgram(h,[a,s,i],a.dtype)},bie={kernelName:um,backendName:"webgl",kernelFunc:xie};function vie(e,t,r,n){let a=w.sizeFromShape(t),s=w.sizeFromShape(e.shape)/a,i=ve({inputs:{x:e},attrs:{shape:[s,a]},backend:n}),o=Ol(i,e.dtype,"max",n),l=ve({inputs:{x:o},attrs:{shape:r},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}function b8(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{reductionIndices:s,keepDims:i}=n,o=a.shape.length,l=w.parseAxisParam(s,a.shape),u=l,d=N.getAxesPermutation(u,o),h=d!=null,p=r.shouldExecuteOnCPU([a]),c=a;if(h){if(p){let A=r.texData.get(c.dataId).values,x=new Array(o);for(let S=0;S<x.length;S++)x[S]=a.shape[d[S]];let b=gb(A,a.shape,a.dtype,d,x);c=r.makeTensorInfo(x,a.dtype);let v=r.texData.get(c.dataId);v.values=b}else c=w0(a,d,r);u=N.getInnerMostAxes(u.length,o)}N.assertAxesAreInnerMostDims("max",u,o);let[f,m]=N.computeOutAndReduceShapes(c.shape,u),g=f;i&&(g=N.expandShapeToKeepDim(f,l));let y;if(p){let A=r.texData.get(c.dataId).values,x=_ee(A,w.sizeFromShape(m),g,a.dtype);y=r.makeTensorInfo(g,a.dtype);let b=r.texData.get(y.dataId);b.values=x}else y=vie(c,m,g,r);return h&&r.disposeIntermediateTensorInfo(c),y}var wie={kernelName:gi,backendName:"webgl",kernelFunc:b8},kie=e8+`
|
|
return max(a, b);
|
|
`,Iie=`
|
|
vec4 result = vec4(max(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+b0+`
|
|
return result;
|
|
`,Sie=wr({opSnippet:kie,packedOpSnippet:Iie,cpuKernelImpl:zee}),Tie={kernelName:yi,backendName:"webgl",kernelFunc:Sie};function Nie(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t;vd(a,"maxPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,u=1;w.assert(N.eitherStridesOrDilationsAreOne(i,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let d=N.computePool2DInfo(a.shape,s,i,u,o,l);if(d.filterWidth===1&&d.filterHeight===1&&w.arraysEqual(d.inShape,d.outShape))return sn({inputs:{x:a},backend:r});let h=new Hp(d,"max",!1);return r.runWebGLProgram(h,[a],a.dtype)}var Cie={kernelName:Ai,backendName:"webgl",kernelFunc:Nie};function Eie(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{filterSize:s,strides:i,pad:o,dataFormat:l,dimRoundingMode:u}=n,d=[1,1,1],h=N.computePool3DInfo(a.shape,s,i,d,o,u,l),p=new Ab(h,"max",!1);return r.runWebGLProgram(p,[a],a.dtype)}var Rie={kernelName:nh,backendName:"webgl",kernelFunc:Eie},Mie=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideHeight,r=e.strideWidth,n=e.dilationHeight,a=e.effectiveFilterHeight,s=e.effectiveFilterWidth,i=a-1-e.padInfo.top,o=s-1-e.padInfo.left,l=a*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 < ${a};
|
|
wR += ${n}) {
|
|
float dyR = float(dyRCorner + wR) / ${t}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${s}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${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);
|
|
}
|
|
`}},Fie=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideDepth,r=e.strideHeight,n=e.strideWidth,a=e.dilationDepth,s=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterDepth,l=e.effectiveFilterHeight,u=e.effectiveFilterWidth,d=o-1-e.padInfo.front,h=l-1-e.padInfo.top,p=u-1-e.padInfo.left,c=o*l*u-1;this.userCode=`
|
|
const ivec3 pads = ivec3(${d}, ${h}, ${p});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
|
|
int dyDCorner = dyCorner.x;
|
|
int dyRCorner = dyCorner.y;
|
|
int dyCCorner = dyCorner.z;
|
|
|
|
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
|
|
// dx(xD, xR, xC, ch).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
|
|
for (int wD = 0; wD < ${o};
|
|
wD += ${a}) {
|
|
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 < ${u};
|
|
wC += ${i}) {
|
|
float dyC = float(dyCCorner + wC) / ${n}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
|
|
int maxPosValue = ${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} * ${u} +
|
|
wR * ${u} + wC;
|
|
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
|
|
|
|
dotProd += dyValue * mask;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function $ie(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s}=t,i=s,{filterSize:o,strides:l,pad:u,dimRoundingMode:d}=n,h=[1,1,1],p=N.computePool3DInfo(i.shape,o,l,h,u,d),c=new Ab(p,"max",!0),f=r.runWebGLProgram(c,[i],i.dtype),m=new Fie(p),g=r.runWebGLProgram(m,[a,f],i.dtype);return r.disposeIntermediateTensorInfo(f),g}var Pie={kernelName:pm,backendName:"webgl",kernelFunc:$ie};function _ie(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,input:s,output:i}=t,o=s;vd([s,i],"maxPoolGrad");let{filterSize:l,strides:u,pad:d,dimRoundingMode:h}=n,p=N.computePool2DInfo(o.shape,l,u,1,d,h),c=!0,f=new Hp(p,"max",c),m=r.runWebGLProgram(f,[o],o.dtype),g=new Mie(p),y=r.runWebGLProgram(g,[a,m],o.dtype);return r.disposeIntermediateTensorInfo(m),y}var zie={kernelName:dm,backendName:"webgl",kernelFunc:_ie};function Oie(e,t,r,n){let a=new Hp(r,"max",!1),s=n.runWebGLProgram(a,[e],"float32");a=new Hp(r,"max",!0,!0,t);let i=n.runWebGLProgram(a,[e],"float32");return[s,i]}var Die={kernelName:hm,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{x:n}=e,{filterSize:a,strides:s,pad:i,includeBatchInIndex:o}=t,l=r;w.assert(n.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${n.shape.length}.`);let u=[1,1];w.assert(N.eitherStridesOrDilationsAreOne(s,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${u}'`);let d=N.computePool2DInfo(n.shape,a,s,u,i),[h,p]=Oie(n,o,d,l);return[h,p]}};function Lie(e,t,r,n){let a=w.sizeFromShape(t),s=w.sizeFromShape(e.shape)/a,i=ve({inputs:{x:e},attrs:{shape:[s,a]},backend:n}),o=Ol(i,"float32","mean",n),l=ve({inputs:{x:o},attrs:{shape:r},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}var Bie={kernelName:xi,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{x:n}=e,{keepDims:a,axis:s}=t,i=r,o=n.shape.length,l=w.parseAxisParam(s,n.shape),u=l,d=N.getAxesPermutation(u,o),h=d!=null,p=i.shouldExecuteOnCPU([n]),c=[],f=n;if(h){if(p){let x=i.texData.get(f.dataId).values,b=new Array(o);for(let T=0;T<b.length;T++)b[T]=n.shape[d[T]];let v=gb(x,n.shape,n.dtype,d,b);f=i.makeTensorInfo(b,n.dtype);let S=i.texData.get(f.dataId);S.values=v}else f=w0(n,d,i);c.push(f),u=N.getInnerMostAxes(u.length,o)}N.assertAxesAreInnerMostDims("sum",u,o);let[m,g]=N.computeOutAndReduceShapes(f.shape,u),y=m;a&&(y=N.expandShapeToKeepDim(m,l));let A=Lie(f,g,y,i);for(let x of c)i.disposeIntermediateTensorInfo(x);return A}};function Wie(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n,o=a.shape.length,l=w.parseAxisParam(s,a.shape),u=l,d=N.getAxesPermutation(u,o),h=a;d!=null&&(h=vr({inputs:{x:a},backend:r,attrs:{perm:d}}),u=N.getInnerMostAxes(u.length,a.shape.length)),N.assertAxesAreInnerMostDims("min",u,o);let[p,c]=N.computeOutAndReduceShapes(h.shape,u),f=w.sizeFromShape(c),m=ve({inputs:{x:h},backend:r,attrs:{shape:[-1,f]}}),g=Ol(m,m.dtype,"min",r),y;if(i){let A=N.expandShapeToKeepDim(p,l);y=ve({inputs:{x:g},backend:r,attrs:{shape:A}})}else y=ve({inputs:{x:g},backend:r,attrs:{shape:p}});return r.disposeIntermediateTensorInfo(m),r.disposeIntermediateTensorInfo(g),d!=null&&r.disposeIntermediateTensorInfo(h),y}var Vie={kernelName:bi,backendName:"webgl",kernelFunc:Wie},Uie=e8+`
|
|
return min(a, b);
|
|
`,Gie=`
|
|
vec4 result = vec4(min(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+b0+`
|
|
return result;
|
|
`,jie=wr({opSnippet:Uie,packedOpSnippet:Gie,cpuKernelImpl:Oee}),Hie={kernelName:vi,backendName:"webgl",kernelFunc:jie},qie=class{constructor(e,t,r){this.variableNames=["x"],this.outputShape=t.map((u,d)=>u[0]+e[d]+u[1]);let n=e.length,a=gt(n),s=t.map(u=>u[0]).join(","),i=t.map((u,d)=>u[0]+e[d]).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,n),l=r==="reflect"?0:1;if(n===1){this.userCode=`
|
|
int start = ${s};
|
|
int end = ${i};
|
|
|
|
void main() {
|
|
int outC = getOutputCoords();
|
|
if (outC < start) {
|
|
outC = start * 2 - outC - ${l};
|
|
} else if(outC >= end) {
|
|
outC = (end - 1) * 2 - outC + ${l};
|
|
}
|
|
setOutput(getX(outC - start));
|
|
}
|
|
`;return}this.userCode=`
|
|
${a} start = ${a}(${s});
|
|
${a} end = ${a}(${i});
|
|
|
|
void main() {
|
|
${a} outC = getOutputCoords();
|
|
for (int i = 0; i < ${n}; i++) {
|
|
if (outC[i] < start[i]) {
|
|
outC[i] = start[i] * 2 - outC[i] - ${l};
|
|
} else if(outC[i] >= end[i]) {
|
|
outC[i] = (end[i] - 1) * 2 - outC[i] + ${l};
|
|
}
|
|
}
|
|
${a} coords = outC - start;
|
|
setOutput(getX(${o}));
|
|
}
|
|
`}},Kie=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 n=e.length,a=gt(n),s=t.map(c=>c[0]).join(","),i=t.map((c,f)=>c[0]+e[f]).join(","),o=Lr("rc",n),l=Lr("source",n),u=`${o[n-1]} < ${this.outputShape[n-1]}`,d=n===1?"source":`vec2(${l.slice(-2).join()})`,h=r==="reflect"?0:1,p="";if(n===1){let c=`
|
|
${a} source = rc;
|
|
if (source < start) {
|
|
source = start * 2 - source - ${h};
|
|
} else if (source >= end) {
|
|
source = (end - 1) * 2 - source + ${h};
|
|
}
|
|
source -= start;
|
|
`;p=`
|
|
${a} rc = outputLoc;
|
|
${c}
|
|
result[0] = getChannel(getX(${l.join()}), ${d});
|
|
${o[n-1]} += 1;
|
|
if(${u}) {
|
|
${c}
|
|
result[1] = getChannel(getX(${l.join()}), ${d});
|
|
}
|
|
`}else{let c=`
|
|
${a} source = rc;
|
|
${a} lt = ${a}(lessThan(source, start));
|
|
${a} gte = ${a}(greaterThanEqual(source, end));
|
|
${a} orig = 1 - (lt + gte);
|
|
source = orig * source +
|
|
lt * (start * 2 - source - ${h}) +
|
|
gte * ((end - 1) * 2 - source + ${h});
|
|
source -= start;
|
|
`;p=`
|
|
${a} rc = outputLoc;
|
|
${c}
|
|
result[0] = getChannel(getX(${l.join()}), ${d});
|
|
${o[n-1]} += 1;
|
|
if(${u}) {
|
|
${c}
|
|
result[1] = getChannel(getX(${l.join()}), ${d});
|
|
}
|
|
rc = outputLoc;
|
|
${o[n-2]} += 1;
|
|
if(${o[n-2]} < ${this.outputShape[n-2]}) {
|
|
${c}
|
|
result[2] = getChannel(getX(${l.join()}), ${d});
|
|
${o[n-1]} += 1;
|
|
if(${u}) {
|
|
${c}
|
|
result[3] = getChannel(getX(${l.join()}), ${d});
|
|
}
|
|
}
|
|
`}this.userCode=`
|
|
const ${a} start = ${a}(${s});
|
|
const ${a} end = ${a}(${i});
|
|
|
|
void main() {
|
|
${a} outputLoc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
${p}
|
|
setOutput(result);
|
|
}
|
|
`}},Xie=({inputs:e,backend:t,attrs:r})=>{let{x:n}=e,{paddings:a,mode:s}=r,i=Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Kie(n.shape,a,s):new qie(n.shape,a,s);return t.runWebGLProgram(i,[n],n.dtype)},Zie={kernelName:wi,backendName:"webgl",kernelFunc:Xie},Yie=`if (b == 0.0) return NAN;
|
|
return mod(a, b);`,Jie=`
|
|
vec4 result = mod(a, b);
|
|
vec4 isNaN = vec4(equal(b, vec4(0.0)));
|
|
`+b0+`
|
|
return result;
|
|
`,Qie=wr({opSnippet:Yie,packedOpSnippet:Jie}),eoe={kernelName:Ju,backendName:"webgl",kernelFunc:Qie},toe=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}));
|
|
}
|
|
`}},roe=`
|
|
if (a == b) {
|
|
return 1.0;
|
|
};
|
|
return a / b;`,noe=`
|
|
// 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;
|
|
`,v8=wr({opSnippet:roe,packedOpSnippet:noe,checkOutOfBounds:!0}),aoe={kernelName:ii,backendName:"webgl",kernelFunc:v8},Qv="return a - b;",w8=wr({opSnippet:Qv,packedOpSnippet:Qv,supportsComplex:!0,cpuKernelImpl:Qee}),soe={kernelName:Di,backendName:"webgl",kernelFunc:w8};function k8(e){let{inputs:t,backend:r,attrs:n}=e,{logits:a}=t,{dim:s}=n,i=w.parseAxisParam([s],a.shape),o=b8({inputs:{x:a},backend:r,attrs:{reductionIndices:i,keepDims:!1}}),l=N.expandShapeToKeepDim(o.shape,i),u=ve({inputs:{x:o},backend:r,attrs:{shape:l}}),d=w8({inputs:{a,b:u},backend:r}),h=y8({inputs:{x:d},backend:r}),p=k0({inputs:{x:h},backend:r,attrs:{axis:i,keepDims:!1}}),c=ve({inputs:{x:p},backend:r,attrs:{shape:l}}),f=v8({inputs:{a:h,b:c},backend:r});return r.disposeIntermediateTensorInfo(o),r.disposeIntermediateTensorInfo(u),r.disposeIntermediateTensorInfo(d),r.disposeIntermediateTensorInfo(h),r.disposeIntermediateTensorInfo(p),r.disposeIntermediateTensorInfo(c),f}var ioe={kernelName:zi,backendName:"webgl",kernelFunc:k8};function ooe(e){let{inputs:t,backend:r,attrs:n}=e,{logits:a}=t,{numSamples:s,seed:i,normalized:o}=n,l=o?a:k8({inputs:{logits:a},backend:r,attrs:{dim:a.shape.length-1}}),u=l.shape[0],d=l.shape[1],h=new toe(u,d,s),p=[[i]],c=r.runWebGLProgram(h,[l],"int32",p);return o||r.disposeIntermediateTensorInfo(l),c}var loe={kernelName:cm,backendName:"webgl",kernelFunc:ooe},uoe=Xn+`
|
|
return -x;
|
|
`,doe=`
|
|
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 poe(e){let{inputs:t,backend:r}=e,{x:n}=t;if(r.shouldExecuteOnCPU([n])){let s=r.texData.get(n.dataId),[i,o]=Lee(s.values,n.shape,n.dtype);return r.makeTensorInfo(o,n.dtype,i)}let a;return Y().getBool("WEBGL_PACK_UNARY_OPERATIONS")?a=new Io(n.shape,doe):a=new Ka(n.shape,uoe),r.runWebGLProgram(a,[n],n.dtype)}var hoe={kernelName:al,backendName:"webgl",kernelFunc:poe},coe=qn.nonMaxSuppressionV3Impl;function foe(e){N.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:r,attrs:n}=e,{boxes:a,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=n,u=r.readSync(a.dataId),d=r.readSync(s.dataId),{selectedIndices:h}=coe(u,d,i,o,l);return r.makeTensorInfo([h.length],"int32",new Int32Array(h))}var moe={kernelName:il,backendName:"webgl",kernelFunc:foe},goe=qn.nonMaxSuppressionV4Impl;function yoe(e){N.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:r,attrs:n}=e,{boxes:a,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:u}=n,d=r.readSync(a.dataId),h=r.readSync(s.dataId),{selectedIndices:p,validOutputs:c}=goe(d,h,i,o,l,u);return[r.makeTensorInfo([p.length],"int32",new Int32Array(p)),r.makeTensorInfo([],"int32",new Int32Array([c]))]}var Aoe={kernelName:Qu,backendName:"webgl",kernelFunc:yoe},xoe=qn.nonMaxSuppressionV5Impl;function boe(e){N.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:r,attrs:n}=e,{boxes:a,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=n,d=r.readSync(a.dataId),h=r.readSync(s.dataId),p=i,c=o,f=l,m=u,{selectedIndices:g,selectedScores:y}=xoe(d,h,p,c,f,m);return[r.makeTensorInfo([g.length],"int32",new Int32Array(g)),r.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var voe={kernelName:ol,backendName:"webgl",kernelFunc:boe},woe=class{constructor(e,t,r,n){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int index = round(getIndices(coords.x));
|
|
setOutput(mix(float(${n}), float(${r}),
|
|
float(index == coords.y)));
|
|
}
|
|
`}},koe=e=>{let{inputs:t,backend:r,attrs:n}=e,{indices:a}=t,{depth:s,onValue:i,offValue:o}=n,l=w.sizeFromShape(a.shape),u=new woe(l,s,i,o),d=ve({inputs:{x:a},backend:r,attrs:{shape:[l]}}),h=r.runWebGLProgram(u,[d],a.dtype);r.disposeIntermediateTensorInfo(d);let p=[...a.shape,s],c=ve({inputs:{x:h},backend:r,attrs:{shape:p}});return r.disposeIntermediateTensorInfo(h),c},Ioe={kernelName:ul,backendName:"webgl",kernelFunc:koe};function Wf(e){let{inputs:t,backend:r}=e,{x:n}=t;if(n.dtype==="complex64"){let a=Lh({inputs:{input:n},backend:r}),s=Wf({inputs:{x:a},backend:r}),i=I0({inputs:{input:n},backend:r}),o=Wf({inputs:{x:i},backend:r}),l=ji({inputs:{real:s,imag:o},backend:r});return r.disposeIntermediateTensorInfo(a),r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(o),l}else return Bh({attrs:{shape:n.shape,dtype:n.dtype,value:n.dtype==="string"?"":0},backend:r})}var Soe={kernelName:Sl,backendName:"webgl",kernelFunc:Wf};function I8(e){let{inputs:t,backend:r}=e,{x:n}=t;if(n.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(n.dtype==="complex64"){let a=Lh({inputs:{input:n},backend:r}),s=I8({inputs:{x:a},backend:r}),i=I0({inputs:{input:n},backend:r}),o=Wf({inputs:{x:i},backend:r}),l=ji({inputs:{real:s,imag:o},backend:r});return r.disposeIntermediateTensorInfo(a),r.disposeIntermediateTensorInfo(s),r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(o),l}else return Bh({attrs:{shape:n.shape,dtype:n.dtype,value:1},backend:r})}var Toe={kernelName:ll,backendName:"webgl",kernelFunc:I8};function Noe(e){let{inputs:t,backend:r,attrs:n}=e,{axis:a}=n;if(t.length===1)return e2({inputs:{input:t[0]},backend:r,attrs:{dim:a}});let s=t[0].shape,i=t[0].dtype;t.forEach(d=>{w.assertShapesMatch(s,d.shape,"All tensors passed to stack must have matching shapes"),w.assert(i===d.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(d=>{let h=e2({inputs:{input:d},backend:r,attrs:{dim:a}});return o.push(h),h}),u=p8({inputs:l,backend:r,attrs:{axis:a}});return o.forEach(d=>r.disposeIntermediateTensorInfo(d)),u}var Coe={kernelName:dl,backendName:"webgl",kernelFunc:Noe},Eoe=class{constructor(e,t,r){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((l,u)=>l[0]+e[u]+l[1]);let n=e.length,a=gt(n),s=t.map(l=>l[0]).join(","),i=t.map((l,u)=>l[0]+e[u]).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,n);if(n===1){this.userCode=`
|
|
int start = ${s};
|
|
int end = ${i};
|
|
|
|
void main() {
|
|
int outC = getOutputCoords();
|
|
if (outC < start || outC >= end) {
|
|
setOutput(value);
|
|
} else {
|
|
setOutput(getX(outC - start));
|
|
}
|
|
}
|
|
`;return}this.userCode=`
|
|
${a} start = ${a}(${s});
|
|
${a} end = ${a}(${i});
|
|
|
|
void main() {
|
|
${a} outC = getOutputCoords();
|
|
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
|
|
setOutput(value);
|
|
} else {
|
|
${a} coords = outC - start;
|
|
setOutput(getX(${o}));
|
|
}
|
|
}
|
|
`}},Roe=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 n=e.length,a=gt(n),s=t.map(f=>f[0]).join(","),i=t.map((f,m)=>f[0]+e[m]).join(","),o=Lr("rc",n),l=Lr("source",n),u=`${o[n-1]} < ${this.outputShape[n-1]}`,d=n===1?"source":`vec2(${l.slice(-2).join()})`,h=[`${a} rc = outputLoc;`,`${o[n-1]} += 1;
|
|
if(${u}) {
|
|
`,n===1?"":`}
|
|
rc = outputLoc;
|
|
${o[n-2]} += 1;
|
|
if(${o[n-2]} < ${this.outputShape[n-2]}) {`,n===1?"":` ${o[n-1]} += 1;
|
|
if(${u}) {`],p=n===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",c="";for(let f=0,m=n===1?2:4;f<m;f++)c+=`
|
|
${h[f]}
|
|
if (${p}) {
|
|
result[${f}] = float(value);
|
|
} else {
|
|
${a} source = rc - start;
|
|
result[${f}] = getChannel(getX(${l.join()}), ${d});
|
|
}
|
|
`;c+=n===1?"} ":"}}",this.userCode=`
|
|
const ${a} start = ${a}(${s});
|
|
const ${a} end = ${a}(${i});
|
|
|
|
void main() {
|
|
${a} outputLoc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
${c}
|
|
setOutput(result);
|
|
}
|
|
`}},S8=e=>{let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{paddings:s,constantValue:i}=n;if(w.sizeFromShape(a.shape)===0){let u=s.map((d,h)=>d[0]+a.shape[h]+d[1]);return Bh({backend:r,attrs:{shape:u,value:i,dtype:a.dtype}})}let o=Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Roe(a.shape,s,i):new Eoe(a.shape,s,i),l=[[i]];return r.runWebGLProgram(o,[a],a.dtype,l)},Moe={kernelName:Ii,backendName:"webgl",kernelFunc:S8},Foe=`
|
|
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);
|
|
`,$oe=`
|
|
// 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));
|
|
`+b0+`
|
|
return result;
|
|
`,Poe=wr({opSnippet:Foe,packedOpSnippet:$oe}),_oe={kernelName:Si,backendName:"webgl",kernelFunc:Poe};function zoe(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n,o=a.shape.length,l=[],u=w.parseAxisParam(s,a.shape),d=u,h=N.getAxesPermutation(d,o),p=a;h!=null&&(p=vr({inputs:{x:a},backend:r,attrs:{perm:h}}),d=N.getInnerMostAxes(d.length,o),l.push(p)),N.assertAxesAreInnerMostDims("prod",d,o);let c;if(r.shouldExecuteOnCPU([p])){let f=r.texData.get(p.dataId).values,{outVals:m,outShape:g,outDtype:y}=Wee(p.shape,p.dtype,f,d);c=r.makeTensorInfo(g,y,m)}else{let[f,m]=N.computeOutAndReduceShapes(p.shape,d),g=w.sizeFromShape(m),y=ve({inputs:{x:p},backend:r,attrs:{shape:[-1,g]}}),A=ch(a.dtype),x=Ol(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,u);c=ve({inputs:{x:c},backend:r,attrs:{shape:f}})}return l.forEach(f=>r.disposeIntermediateTensorInfo(f)),c}var Ooe={kernelName:Ni,backendName:"webgl",kernelFunc:zoe},T8=e=>{let{backend:t,attrs:r}=e,{start:n,stop:a,step:s,dtype:i}=r,o=Vee(n,a,s,i);return t.makeTensorInfo([o.length],i,o)},Doe={kernelName:ed,backendName:"webgl",kernelFunc:T8},Loe="return 1.0 / x;",Boe=it({opSnippet:Loe}),Woe={kernelName:td,backendName:"webgl",kernelFunc:Boe},Voe=Xn+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,Uoe=`
|
|
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;
|
|
`,Goe=it({opSnippet:Voe,packedOpSnippet:Uoe}),joe={kernelName:Ci,backendName:"webgl",kernelFunc:Goe},Hoe=Xn+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,qoe=`
|
|
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;
|
|
`,Koe=it({opSnippet:Hoe,packedOpSnippet:qoe}),Xoe={kernelName:Ri,backendName:"webgl",kernelFunc:Koe},Zoe=class{constructor(e,t,r,n,a){this.variableNames=["A"],this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,r,l];let u=[n&&t>1?i-1:i,n&&r>1?o-1:o],d=[n&&t>1?t-1:t,n&&r>1?r-1:r],h;a?h="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":h="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec2 effectiveInputOverOutputRatioRC = vec2(
|
|
${u[0]/d[0]},
|
|
${u[1]/d[1]});
|
|
const vec2 inputShapeRC = vec2(${i}.0, ${o}.0);
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
ivec2 yRC = coords.yz;
|
|
|
|
// Fractional source index.
|
|
vec2 sourceFracIndexRC = ${h};
|
|
|
|
// 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);
|
|
}
|
|
`}},Yoe=class{constructor(e,t,r,n,a){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,r,l];let u=[n&&t>1?i-1:i,n&&r>1?o-1:o],d=[n&&t>1?t-1:t,n&&r>1?r-1:r],h;a?h="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":h="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec3 effectiveInputOverOutputRatioRC = vec3(
|
|
${u[0]/d[0]},
|
|
${u[1]/d[1]},
|
|
${u[1]/d[1]});
|
|
const vec3 inputShapeRC = vec3(${i}.0, ${o}.0,
|
|
${o}.0);
|
|
|
|
float getAValue(int b, int r, int c, int d) {
|
|
return getChannel(getA(b, r, c, d), vec2(c, d));
|
|
}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
// Calculate values for next column in yRC.z.
|
|
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
|
|
|
|
// Fractional source index.
|
|
vec3 sourceFracIndexRC = ${h};
|
|
|
|
// 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 Joe(e){let{inputs:t,backend:r,attrs:n}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:i,size:o}=n,[l,u]=o,d=Y().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new Yoe(a.shape,l,u,s,i):new Zoe(a.shape,l,u,s,i);return r.runWebGLProgram(d,[a],"float32")}var Qoe={kernelName:Ei,backendName:"webgl",kernelFunc:Joe},ele=class{constructor(e,t,r){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,n,a]=t,[,s,i]=e,o=[r&&s>1?n-1:n,r&&i>1?a-1:a],l=[r&&s>1?s-1:s,r&&i>1?i-1:i],u=o[0]/l[0],d=o[1]/l[1],h=1/u,p=1/d,c=Math.ceil(h)*2+2,f=Math.ceil(p)*2+2;this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
int r = coords[1];
|
|
int c = coords[2];
|
|
|
|
float accumulator = 0.0;
|
|
|
|
const float heightScale = float(${u});
|
|
const float widthScale = float(${d});
|
|
|
|
const float invHeightScale = float(${h});
|
|
const float invWidthScale = float(${p});
|
|
|
|
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), ${n-1}.0));
|
|
float dxRLerp = dxR - float(topDxRIndex);
|
|
float inverseDxRLerp = 1.0 - dxRLerp;
|
|
|
|
float dxC = float(dyC) * widthScale;
|
|
int leftDxCIndex = int(floor(dxC));
|
|
int rightDxCIndex = int(min(ceil(dxC), ${a-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 tle(e){let{inputs:t,backend:r,attrs:n}=e,{images:a,dy:s}=t,{alignCorners:i}=n,o=new ele(s.shape,a.shape,i);return r.runWebGLProgram(o,[s],s.dtype)}var rle={kernelName:mm,backendName:"webgl",kernelFunc:tle},nle=class{constructor(e,t,r,n,a){this.variableNames=["A"],this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,r,l];let u=[n&&t>1?i-1:i,n&&r>1?o-1:o],d=[n&&t>1?t-1:t,n&&r>1?r-1:r],h=n?"0.5":"0.0",p;a?p="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":p="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec2 effectiveInputOverOutputRatioRC = vec2(
|
|
${u[0]/d[0]},
|
|
${u[1]/d[1]});
|
|
const vec2 inputShapeRC = vec2(${i}.0, ${o}.0);
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
ivec2 yRC = coords.yz;
|
|
|
|
// Fractional source index.
|
|
vec2 sourceFracIndexRC = ${p};
|
|
|
|
// Compute the coordinators of nearest neighbor point.
|
|
ivec2 sourceNearestRC = ivec2(
|
|
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${h})));
|
|
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
|
|
|
|
setOutput(newValue);
|
|
}
|
|
`}},ale=class{constructor(e,t,r,n,a){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,r,l];let u=[n&&t>1?i-1:i,n&&r>1?o-1:o],d=[n&&t>1?t-1:t,n&&r>1?r-1:r],h=n?"0.5":"0.0",p;a?p="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":p="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec3 effectiveInputOverOutputRatioRC = vec3(
|
|
${u[0]/d[0]},
|
|
${u[1]/d[1]},
|
|
${u[1]/d[1]});
|
|
const vec3 inputShapeRC = vec3(${i}.0, ${o}.0,
|
|
${o}.0);
|
|
|
|
float getAValue(int b, int r, int c, int d) {
|
|
return getChannel(getA(b, r, c, d), vec2(c, d));
|
|
}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
// Calculate values for next column in yRC.z.
|
|
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
|
|
|
|
// Fractional source index.
|
|
vec3 sourceFracIndexRC = ${p};
|
|
|
|
// Compute the coordinators of nearest neighbor point.
|
|
ivec3 sourceNearestRC = ivec3(
|
|
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${h})));
|
|
|
|
// 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 sle(e){let{inputs:t,backend:r,attrs:n}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:i,size:o}=n,[l,u]=o,d=Y().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new ale(a.shape,l,u,s,i):new nle(a.shape,l,u,s,i);return r.runWebGLProgram(d,[a],a.dtype)}var ile={kernelName:rd,backendName:"webgl",kernelFunc:sle},ole=class{constructor(e,t,r){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,n,a]=t,[,s,i]=e,o=[r&&s>1?n-1:n,r&&i>1?a-1:a],l=[r&&s>1?s-1:s,r&&i>1?i-1:i],u=o[0]/l[0],d=o[1]/l[1],h=1/u,p=1/d,c=Math.ceil(h)*2+2,f=Math.ceil(p)*2+2;this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
int r = coords[1];
|
|
int c = coords[2];
|
|
|
|
float accumulator = 0.0;
|
|
|
|
const float heightScale = float(${u});
|
|
const float widthScale = float(${d});
|
|
|
|
const float invHeightScale = float(${h});
|
|
const float invWidthScale = float(${p});
|
|
|
|
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(${n}) - 1),
|
|
${r} ? float(round(sourceFracRow)) :
|
|
float(floor(sourceFracRow))));
|
|
|
|
int sourceNearestCol = int(min(
|
|
float(int(${a}) - 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 lle(e){let{inputs:t,backend:r,attrs:n}=e,{images:a,dy:s}=t,{alignCorners:i}=n,o=new ole(s.shape,a.shape,i);return r.runWebGLProgram(o,[s],s.dtype)}var ule={kernelName:fm,backendName:"webgl",kernelFunc:lle},dle=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 n=i=>t.indexOf(i)!==-1&&e[i]!==1?`${e[i]} - coords[${i}] - 1`:`coords[${i}]`,a=e.map((i,o)=>n(o)).join(","),s=gt(r);this.userCode=`
|
|
void main() {
|
|
${s} coords = getOutputCoords();
|
|
setOutput(getX(${a}));
|
|
}
|
|
`}},ple=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 n=Lr("rc",r),a=`${n[r-1]} + 1 < ${this.outputShape[r-1]}`,s=`${n[r-2]} + 1 < ${this.outputShape[r-2]}`,i=gt(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(${a}){
|
|
result.g = getChannel(getX(${e[0]} - (rc + 1) - 1),
|
|
${e[0]} - (rc + 1) - 1);
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`:this.userCode=`
|
|
void main() {
|
|
${i} rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result.r = ${o(n.slice())};
|
|
if(${a}){
|
|
result.g = ${l(n.slice())};
|
|
}
|
|
if(${s}) {
|
|
result.b = ${u(n.slice())};
|
|
if(${a}) {
|
|
result.a = ${d(n.slice())};
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`;function o(c){return h(c)}function l(c){return c[r-1]="("+c[r-1]+" + 1)",h(c)}function u(c){return c[r-2]="("+c[r-2]+" + 1)",h(c)}function d(c){return c[r-1]="("+c[r-1]+" + 1)",c[r-2]="("+c[r-2]+" + 1)",h(c)}function h(c){let f=e.map((y,A)=>p(A,c)),m=f.join(","),g=f.slice(-2).join(",");return`getChannel(getX(${m}), vec2(${g}))`}function p(c,f){return t.indexOf(c)!==-1&&e[c]!==1?`${e[c]} - ${f[c]} - 1`:`${f[c]}`}}};function hle(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{dims:s}=n,i=a.shape.length,o=w.parseAxisParam(s,a.shape);if(i===0)return sn({inputs:{x:a},backend:r});let l=Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new ple(a.shape,o):new dle(a.shape,o);return r.runWebGLProgram(l,[a],a.dtype)}var cle={kernelName:hl,backendName:"webgl",kernelFunc:hle},fle=class{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];let r=e[1],n=e[2];this.outputShape=e;let a="";typeof t=="number"?a=`float outputValue = ${t.toFixed(2)};`:a=`
|
|
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]));
|
|
${a}
|
|
if(coordX >= 0 && coordX < ${n} && coordY >= 0 && coordY < ${r}) {
|
|
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
|
|
}
|
|
setOutput(outputValue);
|
|
}
|
|
`}},mle={kernelName:Tl,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{image:n}=e,{radians:a,fillValue:s,center:i}=t,o=r,l=new fle(n.shape,s),[u,d]=N.getImageCenter(i,n.shape[1],n.shape[2]),h=[[u,d,Math.sin(a),Math.cos(a)]];return o.runWebGLProgram(l,[n],n.dtype,h)}},gle=`
|
|
// 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;
|
|
}
|
|
}
|
|
`,yle=it({opSnippet:gle}),Ale={kernelName:cl,backendName:"webgl",kernelFunc:yle},xle="return inversesqrt(x);",ble=it({opSnippet:xle,cpuKernelImpl:Uee}),vle={kernelName:Mi,backendName:"webgl",kernelFunc:ble},N8=class{constructor(e,t,r,n,a,s,i=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=s;let o=gt(a.length),l=gt(s.length),u="";r===1?u="i":r===2&&(u="i, j");let d=`getIndices(${u})`,h="";n===1?h="i":n===2&&(h="i, coords[1]");let p=`getUpdates(${h})`,c=t>1?"strides[j]":"strides";this.userCode=`
|
|
${o} strides = ${o}(${a});
|
|
|
|
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(${d});
|
|
flattenedIndex += index * ${c};
|
|
}
|
|
if (flattenedIndex == coords[0]) {
|
|
sum += ${p};
|
|
found = true;
|
|
}
|
|
}
|
|
setOutput(mix(getDefaultValue(), sum, float(found)));
|
|
}
|
|
`}};function wle(e){let{inputs:t,backend:r,attrs:n}=e,{indices:a,updates:s}=t,{shape:i}=n,{sliceRank:o,numUpdates:l,sliceSize:u,strides:d,outputSize:h}=N.calculateShapes(s,a,i),p=[h/u,u];if(h===0)return r.makeTensorInfo(i,a.dtype);let c=ve({inputs:{x:a},backend:r,attrs:{shape:[l,o]}}),f=ve({inputs:{x:s},backend:r,attrs:{shape:[l,u]}}),m=r.makeTensorInfo([],"float32",new Float32Array([0])),g=new N8(l,o,c.shape.length,f.shape.length,d,p),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 kle={kernelName:fl,backendName:"webgl",kernelFunc:wle},Ile=class{constructor(e,t,r){this.variableNames=["c","a","b"],this.outputShape=t;let n,a;if(r>4)throw Error(`Where for rank ${r} is not yet supported`);if(r===1)a="resRC",n="resRC";else{let i=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],l=[];for(let u=0;u<t.length;u++)l.push(`${i[u]}`),u<e&&o.push(`${i[u]}`);n=o.join(),a=l.join()}let s=gt(r);this.userCode=`
|
|
void main() {
|
|
${s} resRC = getOutputCoords();
|
|
float cVal = getC(${n});
|
|
if (cVal >= 1.0) {
|
|
setOutput(getA(${a}));
|
|
} else {
|
|
setOutput(getB(${a}));
|
|
}
|
|
}
|
|
`}};function Sle(e){let{inputs:t,backend:r}=e,{condition:n,t:a,e:s}=t,i=new Ile(n.shape.length,a.shape,a.shape.length);return r.runWebGLProgram(i,[n,a,s],Cr(a.dtype,s.dtype))}var Tle={kernelName:ml,backendName:"webgl",kernelFunc:Sle},Nle=`
|
|
// 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);
|
|
`,Cle=it({opSnippet:Nle}),Ele={kernelName:nd,backendName:"webgl",kernelFunc:Cle},Rle=Td+`
|
|
return 1.0 / (1.0 + exp(-1.0 * x));
|
|
`,Mle=`
|
|
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;
|
|
`,Fle=it({opSnippet:Rle,packedOpSnippet:Mle,cpuKernelImpl:Gee}),$le={kernelName:$i,backendName:"webgl",kernelFunc:Fle},Ple=`
|
|
if (isnan(x)) { return 0.0; }
|
|
return sign(x);
|
|
`,_le=it({opSnippet:Ple}),zle={kernelName:ad,backendName:"webgl",kernelFunc:_le},Ole=Td+`
|
|
return sin(x);
|
|
`,Dle=it({opSnippet:Ole}),Lle={kernelName:Fi,backendName:"webgl",kernelFunc:Dle},Ble=`
|
|
float e2x = exp(x);
|
|
return (e2x - 1.0 / e2x) / 2.0;
|
|
`,Wle=it({opSnippet:Ble}),Vle={kernelName:yl,backendName:"webgl",kernelFunc:Wle},Ule=`
|
|
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;
|
|
`,Gle=it({opSnippet:Ule}),jle={kernelName:sd,backendName:"webgl",kernelFunc:Gle},Hle=e=>{let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockShape:s,paddings:i}=n;w.assert(a.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<a.shape.length;++y)l.push([0,0]);let u=[],d=S8({inputs:{x:a},backend:r,attrs:{paddings:l,constantValue:0}}),h=N.getReshaped(d.shape,s,o,!1),p=N.getPermuted(h.length,s.length,!1),c=N.getReshapedPermuted(d.shape,s,o,!1),f=ve({inputs:{x:d},backend:r,attrs:{shape:h}}),m=vr({inputs:{x:f},backend:r,attrs:{perm:p}}),g=ve({inputs:{x:m},backend:r,attrs:{shape:c}});return u.push(d),u.push(f),u.push(m),u.forEach(y=>r.disposeIntermediateTensorInfo(y)),g},qle={kernelName:Al,backendName:"webgl",kernelFunc:Hle};function Kle(e){let{inputs:t,backend:r}=e,{indices:n,values:a,denseShape:s,defaultValue:i}=t;if(s.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
|
|
${s.shape}`);if(n.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
|
|
${n.shape}`);if(a.shape.length!==1)throw new Error(`Values must be a vector, saw:
|
|
${a.shape}`);if(i.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
|
|
${i.shape}`);let o=r.readSync(n.dataId),l=r.readSync(a.dataId),u=r.readSync(s.dataId),d=r.readSync(i.dataId)[0],[h,p,c,f,m]=Hee(o,n.shape,n.dtype,l,a.dtype,u,d);return[r.makeTensorInfo(p,n.dtype,h),r.makeTensorInfo([p[0]],a.dtype,c),r.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),r.makeTensorInfo([m.length],n.dtype,new Int32Array(m))]}var Xle={kernelName:sh,backendName:"webgl",kernelFunc:Kle};function Zle(e){let{inputs:t,backend:r}=e,{inputIndices:n,inputShape:a,newShape:s}=t;if(n.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape ${n.shape}`);if(a.shape.length!==1)throw new Error(`Input shape should be a vector but received shape ${a.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(a.dataId)),o=r.readSync(n.dataId),l=Array.from(r.readSync(s.dataId)),[u,d,h]=qee(o,n.shape,n.dtype,i,l);return[r.makeTensorInfo(d,n.dtype,u),r.makeTensorInfo([h.length],s.dtype,new Int32Array(h))]}var Yle={kernelName:id,backendName:"webgl",kernelFunc:Zle};function Jle(e){let{inputs:t,backend:r}=e,{data:n,indices:a,segmentIds:s}=t;if(n.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(a.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${a.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${s.shape}`);let i=r.readSync(n.dataId),o=r.readSync(a.dataId),l=r.readSync(s.dataId),[u,d]=XS(i,n.shape,n.dtype,o,l,!0);return r.makeTensorInfo(d,n.dtype,u)}var Qle={kernelName:ih,backendName:"webgl",kernelFunc:Jle};function eue(e){let{inputs:t,backend:r}=e,{data:n,indices:a,segmentIds:s}=t;if(n.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(a.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${a.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${s.shape}`);let i=r.readSync(n.dataId),o=r.readSync(a.dataId),l=r.readSync(s.dataId),[u,d]=XS(i,n.shape,n.dtype,o,l);return r.makeTensorInfo(d,n.dtype,u)}var tue={kernelName:oh,backendName:"webgl",kernelFunc:eue};function rue(e){let{inputs:t,backend:r,attrs:n}=e,{sparseIndices:a,sparseValues:s,defaultValue:i}=t,{outputShape:o}=n,{sliceRank:l,numUpdates:u,strides:d,outputSize:h}=N.calculateShapes(s,a,o),p=!1,c=new N8(u,l,a.shape.length,s.shape.length,d,[h,1],p),f=r.runWebGLProgram(c,[s,a,i],s.dtype),m=ve({inputs:{x:f},backend:r,attrs:{shape:o}});return r.disposeIntermediateTensorInfo(f),m}var nue={kernelName:lh,backendName:"webgl",kernelFunc:rue};function aue(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{numOrSizeSplits:s,axis:i}=n,o=w.parseAxisParam(i,a.shape)[0],l=N.prepareSplitSize(a,s,o),u=a.shape.length,d=new Array(u).fill(0),h=a.shape.slice();return l.map(p=>{let c=[...h];c[o]=p;let f=Nd({inputs:{x:a},backend:r,attrs:{begin:d,size:c}});return d[o]+=p,f})}var sue={kernelName:xl,backendName:"webgl",kernelFunc:aue},ew="return sqrt(x);",iue=it({opSnippet:ew,packedOpSnippet:ew,cpuKernelImpl:Kee}),oue={kernelName:Pi,backendName:"webgl",kernelFunc:iue},lue="return x * x;",uue=it({opSnippet:lue}),due={kernelName:od,backendName:"webgl",kernelFunc:uue},tw="return (a - b) * (a - b);",pue=wr({opSnippet:tw,packedOpSnippet:tw}),hue={kernelName:Oi,backendName:"webgl",kernelFunc:pue};function cue({inputs:e,attrs:t,backend:r}){let{x:n}=e,a=Xn+`
|
|
return x > 0.0 ? 1.0 : float(${t.alpha});
|
|
`,s=new Ka(n.shape,a);return r.runWebGLProgram(s,[n],n.dtype)}var fue={kernelName:Wi,backendName:"webgl",kernelFunc:cue},mue=class{constructor(e,t,r){this.variableNames=["x"],this.outputShape=r;let n=r.length,a=gt(r.length),s=gt(r.length),i="";if(n===1)i="coords * strides + begin";else{let o=0;i=r.map((l,u)=>(o++,r.length===1?`coords * strides[${u}] + begin[${u}]`:`coords[${o-1}] * strides[${u}] + begin[${u}]`)).join(",")}this.userCode=`
|
|
${a} begin = ${a}(${e});
|
|
${a} strides = ${a}(${t});
|
|
|
|
void main() {
|
|
${s} coords = getOutputCoords();
|
|
setOutput(getX(${i}));
|
|
}
|
|
`}};function gue(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:d,newAxisMask:h,shrinkAxisMask:p}=n,{finalShapeSparse:c,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:A,end:x,strides:b}=zt.sliceInfo(a.shape,s,i,o,l,u,d,h,p),v;if(m)v=ve({inputs:{x:a},backend:r,attrs:{shape:f}});else if(g||y){w.assert(a.shape.length>=1,()=>`Input must have rank at least 1, got: ${a.shape.length}`);let T=zt.computeOutShape(A,x,b),E=Nd({inputs:{x:a},backend:r,attrs:{begin:A,size:T}});v=ve({inputs:{x:E},backend:r,attrs:{shape:f}}),r.disposeIntermediateTensorInfo(E)}else if(r.shouldExecuteOnCPU([a])){let T=r.readSync(a.dataId),E=We(a.shape,a.dtype,T),R=Xee(c,E,b,A);v=r.makeTensorInfo(f,a.dtype,R.values)}else{let T=new mue(A,b,c);v=r.runWebGLProgram(T,[a],a.dtype)}let S=ve({inputs:{x:v},backend:r,attrs:{shape:f}});return r.disposeIntermediateTensorInfo(v),S}var yue={kernelName:bl,backendName:"webgl",kernelFunc:gue};function Aue(e){let{inputs:t,backend:r,attrs:n}=e,{separator:a,nGramWidths:s,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=n,{data:d,dataSplits:h}=t,p=r.readSync(d.dataId),c=r.readSync(h.dataId),[f,m]=Zee(p,c,a,s,i,o,l,u);return[r.makeTensorInfo([f.length],"string",f),r.makeTensorInfo(h.shape,"int32",m)]}var xue={kernelName:uh,backendName:"webgl",kernelFunc:Aue};function bue(e){let{inputs:t,backend:r,attrs:n}=e,{skipEmpty:a}=n,{input:s,delimiter:i}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(s.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${s.shape}`);if(i.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);let o=r.readSync(s.dataId),l=r.readSync(i.dataId)[0],[u,d,h]=Yee(o,l,a),p=d.length;return[r.makeTensorInfo([p,2],"int32",u),r.makeTensorInfo([p],"string",d),r.makeTensorInfo([2],"int32",new Int32Array(h))]}var vue={kernelName:gm,backendName:"webgl",kernelFunc:bue};function wue(e){let{inputs:t,backend:r,attrs:n}=e,{numBuckets:a}=n,{input:s}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(a<=0)throw new Error("Number of buckets must be at least 1");let i=r.readSync(s.dataId),o=Jee(i,a);return r.makeTensorInfo(s.shape,"int32",o)}var kue={kernelName:ym,backendName:"webgl",kernelFunc:wue},Iue="return tan(x);",Sue=it({opSnippet:Iue}),Tue={kernelName:vl,backendName:"webgl",kernelFunc:Sue},Nue=`
|
|
float e2x = exp(-2.0 * abs(x));
|
|
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
|
|
`,Cue=it({opSnippet:Nue}),Eue={kernelName:Li,backendName:"webgl",kernelFunc:Cue},Rue=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 n=gt(this.rank),a=Mue(e);this.userCode=`
|
|
void main() {
|
|
${n} resRC = getOutputCoords();
|
|
setOutput(getA(${a}));
|
|
}
|
|
`}};function Mue(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"],n=[];for(let a=0;a<e.length;a++)n.push(`imod(${r[a]}, ${e[a]})`);return n.join()}function C8(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{reps:s}=n;if(a.dtype==="string"||a.shape.length>5){let o=r.readSync(a.dataId),l=a.dtype==="string"?o.map(h=>w.decodeString(h)):o,u=We(a.shape,a.dtype,l),d=ete(u,s);return r.makeTensorInfo(d.shape,d.dtype,d.values)}let i=new Rue(a.shape,s);return r.runWebGLProgram(i,[a],a.dtype)}var Fue={kernelName:es,backendName:"webgl",kernelFunc:C8},$ue=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));
|
|
}
|
|
}
|
|
`}},Pue=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 fo(e,t){t!==null&&e.disposeIntermediateTensorInfo(t)}function rw(e){let t=1;for(;t<e;)t*=2;return t}function _ue(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{k:s,sorted:i}=n,o=Y().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),l=Y().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),u=a.shape,d=u[u.length-1];if(r.shouldExecuteOnCPU([a])||d<o||s>l){let R=r.readSync(a.dataId),[_,M]=tte(R,u,a.dtype,s,i);return[r.makeTensorInfo(_.shape,_.dtype,_.values),r.makeTensorInfo(M.shape,M.dtype,M.values)]}if(s===0)return u[u.length-1]=0,[r.makeTensorInfo(u,a.dtype,[]),r.makeTensorInfo(u,"int32",[])];if(d===1)return[a,Bh({attrs:{shape:u,dtype:"int32",value:0},backend:r})];let h=r.texData.get(a.dataId),p=h!==null&&h.isPacked,c=p?r.unpackTensor(a):a,f=w.sizeFromShape(u)/d,m=ve({inputs:{x:c},attrs:{shape:[f,d]},backend:r});p&&fo(r,c);let g=rw(s),y=rw(d),A=null,x=()=>A===null?[m,m]:[m,A],b=(R,_,M)=>{let I=x(),z=new $ue(M),O=[[d],[A===null?1:0],[Number.NEGATIVE_INFINITY],[R],[_]],j=A;A=r.runWebGLProgram(z,I,"int32",O),fo(r,j)};for(let R=1;R<g;R*=2){let _=R*2;for(let M=R;M>=1;M/=2)b(_,M,[f,y])}for(let R=y;R>g;R/=2){let _=x(),M=new Pue([f,R/2]),I=[[d],[A===null?1:0],[g]],z=A;A=r.runWebGLProgram(M,_,"int32",I),fo(r,z);let O=g/2,j=O*2;for(let X=O;X>=1;X/=2)b(j,X,A.shape)}let v=A;A=Nd({inputs:{x:A},backend:r,attrs:{begin:0,size:[f,s]}}),fo(r,v);let S=x8({inputs:{x:m,indices:A},backend:r,attrs:{axis:1,batchDims:1}});fo(r,m);let T=u.slice(0,-1);T.push(s),v=A,A=ve({inputs:{x:A},attrs:{shape:T},backend:r}),fo(r,v);let E=S;return S=ve({inputs:{x:S},attrs:{shape:T},backend:r}),fo(r,E),[S,A]}var zue={kernelName:wl,backendName:"webgl",kernelFunc:_ue},Oue=class{constructor(e,t,r,n,a,s){this.variableNames=["Image","Transforms"],this.outputShape=s;let i=r==="nearest"?1:2,o;switch(n){case"constant":o=1;break;case"reflect":o=2;break;case"wrap":o=3;break;case"nearest":o=4;break;default:o=1;break}this.userCode=`
|
|
float mapCoord(float outCoord, float len) {
|
|
float inCoord = outCoord;
|
|
if(${o} == 2) {
|
|
if (inCoord < 0.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz2 = 2.0 * len;
|
|
if (inCoord < sz2) {
|
|
inCoord = sz2 * float(int(float(-inCoord / sz2))) +
|
|
inCoord;
|
|
}
|
|
inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;
|
|
}
|
|
} else if (inCoord > len - 1.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz2 = 2.0 * len;
|
|
inCoord -= sz2 * float(int(float(inCoord / sz2)));
|
|
if (inCoord >= len) {
|
|
inCoord = sz2 - inCoord - 1.0;
|
|
}
|
|
}
|
|
}
|
|
return clamp(inCoord, 0.0, len - 1.0);
|
|
} else if (${o} == 3) {
|
|
if (inCoord < 0.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz = len - 1.0;
|
|
inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);
|
|
}
|
|
} else if (inCoord > len - 1.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz = len - 1.0;
|
|
inCoord -= len * float(int(float(inCoord / sz)));
|
|
}
|
|
}
|
|
return clamp(inCoord, 0.0, len - 1.0);
|
|
} else if (${o} == 4) {
|
|
return clamp(outCoord, 0.0, len - 1.0);
|
|
} else {
|
|
return outCoord;
|
|
}
|
|
}
|
|
|
|
float readWithFillValue(int batch, int coordY, int coordX,
|
|
int channel) {
|
|
float outputValue;
|
|
if (0 <= coordY && coordY < ${e} && 0 <= coordX && coordX < ${t}) {
|
|
outputValue = getImage(batch, coordY, coordX, channel);
|
|
} else {
|
|
outputValue = float(${a});
|
|
}
|
|
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(${a});
|
|
} 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 Due(e){let{inputs:t,backend:r,attrs:n}=e,{image:a,transforms:s}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=n,[d,h,p,c]=a.shape,[f,m]=u!=null?u:[h,p],g=[d,f,m,c],y=new Oue(h,p,i,o,l,g);return r.runWebGLProgram(y,[a,s],"float32")}var Lue={kernelName:kl,backendName:"webgl",kernelFunc:Due};function Bue(e){let{inputs:t,attrs:r,backend:n}=e,{axis:a}=r,{x:s}=t;vd(s,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let i=n.readSync(s.dataId),{outputValues:o,outputShape:l,indices:u}=rte(i,a,s.shape,s.dtype);return[n.makeTensorInfo(l,s.dtype,o),n.makeTensorInfo([u.length],"int32",u)]}var Wue={kernelName:Am,backendName:"webgl",kernelFunc:Bue};function Vue(e){let{inputs:t,backend:r,attrs:n}=e,{value:a}=t,{axis:s}=n;s<0&&(s+=a.shape.length);let i=a,o=i.shape.length,l=a.shape[s],u=new Array(o-1),d=0;for(let m=0;m<o;m++)m!==s&&(u[d++]=i.shape[m]);let h=[],p=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++){p[s]=m;let g=Nd({inputs:{x:i},backend:r,attrs:{begin:p,size:c}}),y=ve({inputs:{x:g},backend:r,attrs:{shape:u}});f[m]=y,h.push(g)}return h.forEach(m=>r.disposeIntermediateTensorInfo(m)),f}var Uue={kernelName:Il,backendName:"webgl",kernelFunc:Vue},Gue=class{constructor(e,t){this.variableNames=["x","segmentIds"];let r=e.windowSize,n=e.batchSize,a=e.inSize,s=e.numSegments,i=s*Math.ceil(a/r);this.outputShape=[n,i];let o="0.0",l="sumValue",u=Math.floor(r/4)*4,d=r%4,h=`
|
|
sumValue += dot(values, segFilter);
|
|
`,p="";a%r>0&&(p=`
|
|
if (inIdx < 0 || inIdx >= ${a}) {
|
|
return initializationValue;
|
|
}
|
|
`);let c="";a%r>0&&(c=`
|
|
if (inIdx < 0 || inIdx >= ${a}) {
|
|
return -1.0;
|
|
}
|
|
`),this.userCode=`
|
|
const float initializationValue = ${o};
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
${p}
|
|
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 < ${u}; i += 4) {
|
|
int inIdx = inOffset + i;
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
|
|
);
|
|
|
|
${h}
|
|
}
|
|
|
|
int inIdx = inOffset + ${u};
|
|
if (${d===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
int inIdxSeg = int(getSegmentIdAtIndex(inIdx));
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
0,
|
|
0,
|
|
0
|
|
);
|
|
|
|
${h}
|
|
} else if (${d===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
|
|
0,
|
|
0
|
|
);
|
|
|
|
${h}
|
|
} else if (${d===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
initializationValue
|
|
);
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
|
|
0
|
|
);
|
|
|
|
${h}
|
|
}
|
|
setOutput(${l});
|
|
}
|
|
`}};function jue(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,segmentIds:s}=t,{numSegments:i}=n,o=a.shape.length,l=[],u=0,d=N.getAxesPermutation([u],o),h=a;d!=null&&(h=vr({inputs:{x:a},backend:r,attrs:{perm:d}}),l.push(h),u=N.getInnerMostAxes(1,o)[0]);let p=N.segment_util.computeOutShape(h.shape,u,i),c=w.sizeFromShape([h.shape[u]]),f=ve({inputs:{x:h},backend:r,attrs:{shape:[-1,c]}});l.push(f);let m=ch(a.dtype),g=(b,v,S,T,E)=>{let R=b.shape[0],_=b.shape[1],M=N.segment_util.segOpComputeOptimalWindowSize(_,E),I={windowSize:M,inSize:_,batchSize:R,numSegments:E},z=new Gue(I,v),O=r.compileAndRun(z,[b,S],T);if(l.push(O),O.shape[1]===E)return O;let j=T8({backend:r,attrs:{start:0,stop:E,step:1,dtype:"float32"}}),X=C8({inputs:{x:j},backend:r,attrs:{reps:[_/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:p}}),x=A;if(d!=null){l.push(A);let b=N.getUndoAxesPermutation(d);x=vr({inputs:{x},backend:r,attrs:{perm:b}})}return l.forEach(b=>r.disposeIntermediateTensorInfo(b)),x}var Hue={kernelName:dh,backendName:"webgl",kernelFunc:jue},que=[Yte,Qte,rre,sre,ore,dre,hre,fre,Are,bre,kre,Tre,Ere,$re,zre,Dre,Bre,Gre,Hre,Kre,Jre,sne,one,une,mne,yne,vne,Fte,Ine,Ene,$ne,Lne,Wne,Une,jne,qne,Zne,Qne,rae,aae,iae,lae,pae,cae,yae,xae,wae,Sae,Nae,Mae,_ae,Lae,Vae,jae,Hae,Kae,Zae,Jae,ese,rse,ise,use,hse,fse,yse,bse,Ise,Cse,Mte,Rse,Nne,$se,zse,Lse,Pte,Use,qse,Xse,Qse,rie,iie,uie,cie,yie,bie,wie,Tie,Cie,Rie,Pie,zie,Die,Bie,Vie,Hie,Zie,eoe,loe,Lte,hoe,moe,Aoe,voe,pne,Ioe,Toe,Coe,Moe,_oe,zte,Ooe,Doe,hne,aoe,Woe,joe,Xoe,Wte,Qoe,rle,ile,ule,cle,mle,Ale,vle,kle,Tle,Ele,$le,zle,Lle,Vle,nne,ioe,jle,qle,Xle,Yle,Qle,tue,nue,sue,oue,due,hue,fue,yue,xue,vue,kue,soe,Kte,Tue,Eue,Fue,zue,Lue,Xte,Wue,Uue,Hue,Soe];for(let e of que)jn(e);var za=Y();za.registerFlag("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE",()=>15);za.registerFlag("WEBGPU_CPU_FORWARD",()=>!0);za.registerFlag("WEBGPU_MATMUL_WORK_PER_THREAD",()=>4);za.registerFlag("WEBGPU_USE_NAIVE_CONV2D",()=>!1);za.registerFlag("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE",()=>!1);za.registerFlag("WEBGPU_CONV_SEPARATE_IM2COL_SHADER",()=>!1);za.registerFlag("WEBGPU_USE_LOW_POWER_GPU",()=>!1);za.registerFlag("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e3);za.registerFlag("WEBGPU_USE_PROFILE_TOOL",()=>!1);za.registerFlag("WEBGPU_USE_IMPORT",()=>!1);var Kue="return a + b;",Xue="return areal * breal - aimag * bimag;",Zue="return areal * bimag + aimag * breal;",Yue="return a / b;",Jue="return a * b;",Que="return (a - b) * (a - b);",ede="return a - b;",tde="return f32(a == b);",rde="return vec4<f32>(a == b);",nde="return f32(a > b);",ade="return vec4<f32>(a > b);",sde="return f32(a >= b);",ide="return vec4<f32>(a >= b);",ode="return f32(a < b);",lde="return vec4<f32>(a < b);",ude="return f32(a <= b);",dde="return vec4<f32>(a <= b);",pde="return f32(f32(a) >= 1.0 && f32(b) >= 1.0);",hde=`return (vec4<f32>(a >= vec4<f32>(1.0)) *
|
|
vec4<f32>(b >= vec4<f32>(1.0)));`,cde=`
|
|
if (isnan(a)) { return a; }
|
|
if (isnan(b)) { return b; }
|
|
`,E8=`
|
|
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;
|
|
}
|
|
`,fde=`
|
|
let s = sign(a) * sign(b);
|
|
let ia = i32(round(a));
|
|
let ib = i32(round(b));
|
|
return f32(idiv(ia, ib, s));
|
|
`,mde=`
|
|
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);
|
|
`,gde="return f32(a != b);",yde="return vec4<f32>(a != b);",Ade=`
|
|
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);
|
|
`,xde=`
|
|
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;
|
|
${E8}
|
|
return resultTemp;
|
|
`,bde="if (a < 0.0) { return b * a; } return a;",vde=`
|
|
let aLessThanZero = vec4<f32>(a < vec4<f32>(0.0));
|
|
return (aLessThanZero * (b * a)) + ((vec4<f32>(1.0) - aLessThanZero) * a);
|
|
`;function nw(e,t){let r=t?E8:cde;return t?`
|
|
var resultTemp = vec4<f32>(${e}(a, b));
|
|
let isNaN = isnanVec4(a) | isnanVec4(b);
|
|
`+r+`
|
|
return resultTemp;
|
|
`:r+`
|
|
return ${e}(a, b);
|
|
`}function Wh(e,t){switch(e){case 0:return Jue;case 1:return Kue;case 2:return ede;case 3:return Yue;case 4:return t?rde:tde;case 5:return t?ade:nde;case 6:return t?ide:sde;case 7:return t?lde:ode;case 8:return t?dde:ude;case 9:return t?hde:pde;case 10:return t?yde:gde;case 11:return Que;case 12:return t?mde:fde;case 14:return t?vde:bde;case 15:return nw("max",t);case 16:return nw("min",t);case 13:return t?xde:Ade;case 17:return Xue;case 18:return Zue;default:throw new Error(`BinaryType ${e} is not implemented!`)}}var wde="return abs(a);",kde="return ceil(a);",Ide="return cos(a);",Sde=`
|
|
let e2x = exp(-a);
|
|
return (e2x + 1.0 / e2x) / 2.0;
|
|
`,Tde="return exp(a) - 1.0;",Nde="if (a >= 0.0) { return a; } return (exp(a) - 1.0);",Cde=`
|
|
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;
|
|
`,Ede="return exp(a);",Rde="return floor(a);",Mde="return a;",Fde=`if (a < 0.0) { return 1.0/0.0; }
|
|
return log(a);`,$de="return f32(!(a >= 1.0));",Pde="return -a;",_de="if (a < 0.0) { return uniforms.alpha * a; } return a;",zde=`
|
|
let aLessThanZero = vec4<f32>(a < vec4<f32>(0.0));
|
|
return (aLessThanZero * (uniforms.alpha * a)) + ((vec4<f32>(1.0) - aLessThanZero) * a);
|
|
`,Ode="if(a < 0.0) { return 0.0; } return a;",Dde="return clamp(a, 0.0, 6.0);",Lde="return clamp(a, vec4<f32>(0.0, 0.0, 0.0, 0.0), vec4<f32>(6.0, 6.0, 6.0, 6.0));",Bde=`
|
|
var resFloat = a * vec4<f32>(a >= vec4<f32>(0.0));
|
|
let isNaN = isnanVec4(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;
|
|
`,Wde="return 1.0/sqrt(a);",Vde="return 1.0 / (1.0 + exp(-1.0 * a));",Ude="return sin(a);",Gde=`
|
|
let e2x = exp(a);
|
|
return (e2x - 1.0 / e2x) / 2.0;
|
|
`,jde="return sqrt(a);",Hde="return a * a;",qde=`
|
|
let e2x = exp(-2.0 * abs(a));
|
|
return sign(a) * (1.0 - e2x) / (1.0 + e2x);
|
|
`,Kde="return f32(i32((a)));";function yo(e,t){switch(e){case 0:return wde;case 2:return Ide;case 3:return Sde;case 1:return kde;case 4:return t?Cde:Nde;case 5:return Ede;case 6:return Tde;case 7:return Rde;case 8:return Mde;case 9:return Fde;case 10:return $de;case 11:return Pde;case 14:return t?zde:_de;case 12:return t?Bde:Ode;case 13:return t?Lde:Dde;case 15:return Wde;case 18:return Vde;case 16:return Ude;case 17:return Gde;case 19:return jde;case 20:return Hde;case 21:return qde;case 22:return Kde;default:throw new Error(`BinaryType ${e} is not implemented!`)}}function is(e,t=!1){if(e===null)return null;if(e==="linear")return yo(8);if(e==="relu")return yo(12,t);if(e==="elu")return yo(4,t);if(e==="relu6")return yo(13,t);if(e==="prelu")return Wh(14,t);if(e==="sigmoid")return yo(18,t);if(e==="leakyrelu")return yo(14,t);throw new Error(`Activation ${e} has not been implemented for the WebGPU backend.`)}function Xde(e,t){if(Math.max(...e)>3)throw new Error("Cannot symbolically compute strides for rank > 4 tensor.");let r=e.length,n=e.map(s=>`${t}[${s}]`),a=new Array(r-1);a[r-2]=n[r-1];for(let s=r-3;s>=0;--s)a[s]=`(${a[s+1]} * ${n[s+1]})`;return a}function yr(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 pf(e,t){return e==="float32"?t?"vec4<f32>":"f32":e==="int32"||e==="bool"?t?"vec4<i32>":"i32":e}function xb(){return`
|
|
@stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)
|
|
`}function Hi(){return`
|
|
${xb()}
|
|
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 et(){return`
|
|
${Hi()}
|
|
let index = getGlobalIndex();
|
|
`}function Zde(e,t,r,n=!1){let a=[];if(a.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);
|
|
}
|
|
`),n===!0)return a.push(`
|
|
struct Uniform {
|
|
size : i32,
|
|
numChannels : i32,
|
|
outShapeStrides : vec2<i32>,
|
|
dispatchSize : vec3<u32>,
|
|
};
|
|
|
|
@group(0) @binding(0) var<storage, write> result: array<${pf(t.dtype,r.isVec4)}>;
|
|
@group(0) @binding(2) var<uniform> uniforms: Uniform;
|
|
`),[aw,a.join(`
|
|
`),sw(t.shape),r.getUserCode()].join(`
|
|
`);let s="struct Uniforms { NAN : f32, ";r.variableNames.forEach((d,h)=>{s+=`${d.charAt(0).toLowerCase()+d.slice(1)}Shape : ${yr(e[h].shape.length)}, `}),s+=`outShape : ${yr(t.shape.length)}, `;let i=t.shape.length-1;s+=`
|
|
outShapeStrides: ${yr(i)}, `,r.size&&(s+="size : i32, "),r.uniforms&&(s+=r.uniforms),s+="};",a.push(s),r.atomic?a.push(`
|
|
@group(0) @binding(0) var<storage, read_write> result: array<atomic<i32>>;
|
|
`):a.push(`
|
|
@group(0) @binding(0) var<storage, write> result: array<${pf(t.dtype,r.isVec4)}>;
|
|
`),r.variableNames.forEach((d,h)=>{a.push(`
|
|
@group(0) @binding(${1+h}) var<storage, read> ${d}: array<${pf(e[h].dtype,r.isVec4)}>;
|
|
`)}),s!==""&&a.push(`
|
|
@group(0) @binding(${1+r.variableNames.length}) var<uniform> uniforms: Uniforms;
|
|
`);let[o,l]=rpe(t.shape,r.dispatchLayout),u=[aw,a.join(`
|
|
`),sw(t.shape),o,Yde(t.shape.length)];if(r.atomic||u.push(Jde(t.shape,t.dtype,r.isVec4)),l===t.shape.length){let d=e.map(h=>Qde(h,t.shape,r.isVec4,r.dispatchLayout.x.length===t.shape.length)).join(`
|
|
`);u.push(d)}return u.push(r.getUserCode()),u.join(`
|
|
`)}var aw=`
|
|
// 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;
|
|
}
|
|
|
|
// NaN defination in IEEE 754-1985 is :
|
|
// - sign = either 0 or 1.
|
|
// - biased exponent = all 1 bits.
|
|
// - fraction = anything except all 0 bits (since all 0 bits represents infinity).
|
|
// https://en.wikipedia.org/wiki/IEEE_754-1985#Representation_of_non-numbers
|
|
fn isnan(val: f32) -> bool {
|
|
let floatToUint: u32 = bitcast<u32>(val);
|
|
return (floatToUint & 0x7fffffffu) > 0x7f800000u;
|
|
}
|
|
fn isnanVec4(val : vec4<f32>) -> vec4<bool> {
|
|
return vec4<bool>(isnan(val[0]), isnan(val[1]), isnan(val[2]), isnan(val[3]));
|
|
}
|
|
`;function Yde(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 Jde(e,t,r){let n=e.length,a=pf(t,r),s;if(r?s=`fn setOutputAtIndex(flatIndex : i32, value : vec4<f32>) {
|
|
result[flatIndex] = ${a}(value);
|
|
}
|
|
fn setOutputAtIndexI32(flatIndex : i32, value : vec4<i32>) {
|
|
result[flatIndex] = ${a}(value);
|
|
}`:s=`fn setOutputAtIndex(flatIndex : i32, value : f32) {
|
|
result[flatIndex] = ${a}(value);
|
|
}
|
|
fn setOutputAtIndexI32(flatIndex : i32, value : i32) {
|
|
result[flatIndex] = ${a}(value);
|
|
}`,n>=2){let i=["d0","d1","d2","d3"].slice(0,n),o=yr(n);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 Qde(e,t,r,n){let a=epe(e,r);return e.shape.length<=t.length&&(a+=tpe(e,t,r,n)),a}function epe(e,t){let r=e.name,n=e.shape.length,a=yr(n),s="get"+r.charAt(0).toUpperCase()+r.slice(1),i=["d0","d1","d2","d3"].slice(0,n),o=i.map(d=>`${d} : i32`).join(", ");if(n<1)return t?`
|
|
fn ${s}() -> vec4<f32> {
|
|
return vec4<f32>(${r}[0]);
|
|
}
|
|
`:`
|
|
fn ${s}() ->f32 {
|
|
return f32(${r}[0]);
|
|
}
|
|
`;let l=`uniforms.${r.charAt(0).toLowerCase()+r.slice(1)}Shape`,u=`${n}D`;return n===0&&(u="1D"),t?`
|
|
fn ${s}(${o}) -> vec4<f32> {
|
|
return vec4<f32>(${r}[getIndexFromCoords${u}(${a}(${i.join(",")}),
|
|
${l}) / 4]);
|
|
}
|
|
`:`
|
|
fn ${s}(${o}) -> f32 {
|
|
return f32(${r}[getIndexFromCoords${u}(${a}(${i.join(",")}),
|
|
${l})]);
|
|
}
|
|
`}function tpe(e,t,r,n){let a=e.name,s=a.charAt(0).toUpperCase()+a.slice(1),i="get"+s+"ByOutput",o=e.shape.length,l=t.length,u=yr(l);if(w.arraysEqual(e.shape,t)&&n)return r?`
|
|
fn ${i}Index(globalIndex : i32) -> vec4<f32> {
|
|
return vec4<f32>(${a}[globalIndex]);
|
|
}
|
|
|
|
fn ${i}Coords(coords : ${u}) -> vec4<f32> {
|
|
return vec4<f32>(${a}[${l>1?"getOutputIndexFromCoords(coords)":"coords"} / 4]);
|
|
}
|
|
`:`
|
|
fn ${i}Index(globalIndex : i32) -> f32 {
|
|
return f32(${a}[globalIndex]);
|
|
}
|
|
|
|
fn ${i}Coords(coords : ${u}) -> f32 {
|
|
return f32(${a}[${l>1?"getOutputIndexFromCoords(coords)":"coords"}]);
|
|
}
|
|
`;let d=N.getBroadcastDims(e.shape,t),h=l-o,p="";if(o===0)return r?`
|
|
fn ${i}Index(globalIndex : i32) -> vec4<f32> {
|
|
return get${s}();
|
|
}
|
|
|
|
fn ${i}Coords(coords : ${u}) -> vec4<f32> {
|
|
return get${s}();
|
|
}
|
|
`:`
|
|
fn ${i}Index(globalIndex : i32) -> f32{
|
|
return get${s}();
|
|
}
|
|
|
|
fn ${i}Coords(coords : ${u}) -> f32{
|
|
return get${s}();
|
|
}
|
|
`;l<2&&d.length>=1?p="coords = 0;":p=d.map(g=>`coords[${g+h}] = 0;`).join(`
|
|
`);let c="";if(l<2&&o>0)c="coords";else if(l>1){let g=yr(o),y=e.shape.map((A,x)=>`coords[${x+h}]`).join(", ");c=`${g}(${y})`}else c="coords";let f=`uniforms.${a.charAt(0).toLowerCase()+a.slice(1)}Shape`,m=`${o}D`;return r?`
|
|
fn ${i}Index(globalIndex : i32) -> vec4<f32> {
|
|
var coords = getCoordsFromIndex(globalIndex);
|
|
${p}
|
|
return ${a}[getIndexFromCoords${m}(${c}, ${f}) / 4];
|
|
}
|
|
|
|
fn ${i}Coords(coordsIn : ${u}) -> vec4<f32> {
|
|
var coords = coordsIn;
|
|
${p}
|
|
return ${a}[getIndexFromCoords${m}(${c}, ${f}) / 4];
|
|
}
|
|
`:`
|
|
fn ${i}Index(globalIndex : i32) -> f32 {
|
|
var coords = getCoordsFromIndex(globalIndex);
|
|
${p}
|
|
return f32(${a}[getIndexFromCoords${m}(${c}, ${f})]);
|
|
}
|
|
|
|
fn ${i}Coords(coordsIn : ${u}) -> f32 {
|
|
var coords = coordsIn;
|
|
${p}
|
|
return f32(${a}[getIndexFromCoords${m}(${c}, ${f})]);
|
|
}
|
|
`}function rpe(e,t){let{x:r,y:n=[],z:a=[]}=t,s=e.length;if(r.length===s)return[`fn getOutputCoords() -> ${yr(s)}{
|
|
let globalIndex = getGlobalIndex();
|
|
return getCoordsFromIndex(globalIndex);
|
|
}
|
|
`,s];let i="",o=[r,n,a],l=0;for(let p=0;p<o.length;p++){let c=o[p];if(c.length!==0)if(l+=c.length,c.length===1)i+=`let d${c[0]} = i32(globalId[${p}]);`;else{let f=Xde(c,"uniforms.outShape");i+=`var index${p} = i32(globalId[${p}]);`;for(let m=0;m<f.length;m++)i+=`let d${c[m]} = index${p} / ${f[m]};`,m===f.length-1?i+=`let d${c[m+1]} = index${p} - d${c[m]} * ${f[m]};`:i+=`index${p} = index${p} - d${c[m]} * ${f[m]};`}}let u=[];for(let p=0;p<l;p++)u.push(`d${p}`);let d=yr(l),h=`fn getOutputCoords() -> ${d} {
|
|
${i}
|
|
`;return u.length===0?h+=`return ${d}(0); }`:h+=`return ${d}(${u.join(",")}); }`,[h,l]}function sw(e){let t=e.length;if(t<=1)return"fn getCoordsFromIndex(index : i32) -> i32 { return index; }";let r=w.computeStrides(e),n=yr(t),a=[];for(let i=0;i<t;i++)a.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 ${a[o]} = index2 / uniforms.outShapeStrides[${o}]`,u=o===r.length-1?`let ${a[o+1]} = index2 - ${a[o]} * uniforms.outShapeStrides[${o}]`:`index2 = index2 - ${a[o]} * uniforms.outShapeStrides[${o}]`;return`${l}; ${u};`}).join("");return`
|
|
fn getCoordsFromIndex(index : i32) -> ${n} {
|
|
${s}
|
|
return ${n}(${a.join(",")});
|
|
}
|
|
`}var R8={};Le(R8,{ArrayBufferToTypedArray:()=>F8,GPUBytesPerElement:()=>t2,computeDispatch:()=>ze,computeWorkGroupSizeForConv2d:()=>bb,computeWorkGroupSizeForMatMul:()=>M8,computeWorkPerThreadForConv2d:()=>vb,flatDispatchLayout:()=>Ke,isWebGPUSupported:()=>wb,tilesFitEvenlyIntoShape:()=>Za});var Co=e=>{let t=1;for(let r=0;r<e.length;r++)t*=e[r];return t};function Za(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,n)=>r%e[n]===0)}function ze(e,t,r=[1,1,1],n=[1,1,1]){let[a,s,i]=[Math.ceil(Co(e.x.map(o=>t[o]))/(r[0]*n[0])),e.y?Math.ceil(Co(e.y.map(o=>t[o]))/(r[1]*n[1])):1,e.z?Math.ceil(Co(e.z.map(o=>t[o]))/(r[2]*n[2])):1];return[a,s,i]}function bb(e,t){let r=Co(e.x.map(a=>t[a])),n=Co(e.y.map(a=>t[a]));return r<=4?[4,16,1]:n<=4?[16,4,1]:[16,16,1]}function M8(e,t,r){return e===1?[32,1,1]:r===1?[1,32,1]:[8,8,1]}function vb(e,t){let r=Co(e.x.map(a=>t[a])),n=Co(e.y.map(a=>t[a]));return r<=4?[1,2,1]:n<=4?[2,1,1]:[2,2,1]}function Ke(e){return{x:e.map((t,r)=>r)}}function t2(e){if(e==="float32"||e==="int32"||e==="bool"||e==="string")return 4;if(e==="complex64")return 8;throw new Error(`Unknown dtype ${e}`)}function F8(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 wb(){return(typeof window!="undefined"||typeof WorkerGlobalScope!="undefined")&&!!navigator.gpu}function $8(e,t,r,n){return w.assert(n%4===0&&e[0]===4,()=>"tileInner must be divisible by 4. And ColPerThread must be 4"),`
|
|
var<workgroup> mm_Asub : array<array<vec4<f32>, ${n/e[0]}>, ${t}>;
|
|
var<workgroup> mm_Bsub : array<array<vec4<f32>, ${r/e[0]}>, ${n}>;
|
|
|
|
let RowPerThread = ${e[1]};
|
|
let ColPerThread = ${e[0]};
|
|
let TileInner = ${n};
|
|
|
|
${Hi()}
|
|
|
|
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 npe=class{constructor(e,t,r,n=null,a=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=n!=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=a,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],n=[this.tileAOuter,this.tileInner],a=[this.tileInner,this.tileBOuter];return[Za(n,this.aShape.slice(1)),Za(a,r.slice(1))]}getUserCode(){let e=this.fitA?"return A[batch * batchASize + row * uniforms.dimInner / 4 + col]":`if (coordsInBounds2D(vec2<i32>(row, col * 4), vec2<i32>(uniforms.dimAOuter, uniforms.dimInner))) {
|
|
return A[batch * batchASize + row * uniforms.dimInner / 4 + col];
|
|
}
|
|
return vec4<f32>(0.0)`,t=this.fitB?"return B[batch * batchBSize + row * uniforms.dimBOuter / 4 + col]":`if(coordsInBounds2D(vec2<i32>(row, col * 4), vec2<i32>(uniforms.dimInner, uniforms.dimBOuter))) {
|
|
return B[batch * batchBSize + row * uniforms.dimBOuter / 4 + col];
|
|
}
|
|
return vec4<f32>(0.0)`,r="",n="";if(this.activation){let s=is(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}
|
|
}`,n="value = activation(value, outCoord);"}let a=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);
|
|
${a}
|
|
${n}
|
|
setOutputAtCoords(outCoord[0], outCoord[1], outCoord[2], value);
|
|
}
|
|
}
|
|
${$8(this.elementsPerThread,this.tileAOuter,this.tileBOuter,this.tileInner)}
|
|
`}};function kb(e,t){let r=t[1]*e[1],n=t[0]*e[0],a=r>n?r:n;return`
|
|
var<workgroup> mm_Asub : array<array<f32, ${a}>, ${r}>;
|
|
var<workgroup> mm_Bsub : array<array<f32, ${n}>, ${a}>;
|
|
${Hi()}
|
|
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) / ${a} + 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 = ${a} / ${t[0]};
|
|
let tileColA = i32(localId.x) * ColPerThreadA;
|
|
let RowPerThreadB = ${a} / ${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 * ${a} + 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 * ${a} + inputRow,
|
|
globalCol + innerCol, globalId);
|
|
}
|
|
}
|
|
|
|
workgroupBarrier();
|
|
|
|
// Compute acc values for a single thread.
|
|
for (var k = 0; k < ${a}; 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 ape(e){return`
|
|
let TileSize = ${e[0]*4};
|
|
var<workgroup> mm_Asub : array<vec4<f32>, ${e[0]}>;
|
|
|
|
${Hi()}
|
|
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 P8=class{constructor(e,t,r,n=!1,a=!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=n?e[1]:e[2];this.workGroupSize=M8(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 u=s!=null,d=o!=null;u&&this.variableNames.push("bias"),d&&this.variableNames.push("preluActivationWeights"),this.workPerThread=r,this.aShape=e,this.transposeA=n,this.transposeB=a,this.addBias=u,this.activation=i,this.hasPreluActivationWeights=d;let h=this.outputShape[2],p=this.transposeB?[this.outputShape[0],h,l]:[this.outputShape[0],l,h];[this.fitA,this.fitB]=this.getShapeFit(p),this.shaderKey=`matMulPacked_${this.workPerThread}_${n}_${a}_${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,n=t>r?t:r;this.outputShape[1]===1&&(n*=4),w.assert(n%this.workGroupSize[0]===0&&n%this.workGroupSize[1]===0,()=>"tileInner must be multiple of workgroupsize.x and workgroupsize.y");let a=[t,n],s=[n,r];return[Za(a,this.aShape.slice(1)),Za(s,e.slice(1))]}getUserCode(){let e;this.transposeA===!1?e=this.fitA?"return A[batch * batchASize + row * uniforms.dimInner + col];":`if(coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimAOuter, uniforms.dimInner))) {
|
|
return A[batch * batchASize + row * uniforms.dimInner + col];
|
|
}
|
|
return 0.0;`:e=this.fitA?"return A[batch * batchASize + col * uniforms.dimAOuter + row];":`if(coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimAOuter, uniforms.dimInner))) {
|
|
return A[batch* batchASize + col * uniforms.dimAOuter + row];
|
|
}
|
|
return 0.0;`;let t;this.transposeB===!1?t=this.fitB?"return B[batch * batchBSize + row * uniforms.dimBOuter + col];":`if(coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimInner, uniforms.dimBOuter))) {
|
|
return B[batch * batchBSize + row * uniforms.dimBOuter + col];
|
|
}
|
|
return 0.0;`:t=this.fitB?"return B[batch * batchBSize + col * uniforms.dimInner + row];":`if(coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimInner, uniforms.dimBOuter))) {
|
|
return B[batch * batchBSize + col * uniforms.dimInner + row];
|
|
}
|
|
return 0.0;`;let r="",n="";if(this.activation){let s=is(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}
|
|
}
|
|
`,n="value = activation(value, outCoord);"}let a=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);
|
|
${a}
|
|
${n}
|
|
setOutputAtCoords(batch, row, col, value);
|
|
}
|
|
${this.outputShape[1]>1?kb([this.workPerThread,this.workPerThread,1],this.workGroupSize):ape(this.workGroupSize)}
|
|
`}};function spe(){return`
|
|
var<workgroup> sumValues : array<f32, workGroupSizeX>;
|
|
${Hi()}
|
|
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 ipe=class{constructor(e,t=!1,r=!1,n=null,a=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=n!=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=a,this.hasPreluActivationWeights=o,this.shaderKey=`matMulReduce_${this.activation}_${t}_${r}`}getUserCode(){let e;this.transposeA===!1?e="return A[batch * batchASize + row * uniforms.dimInner + col];":e="return A[batch * batchASize + col * uniforms.dimAOuter + row];";let t;this.transposeB===!1?t="return B[batch * batchBSize + row * uniforms.dimBOuter + col];":t="return B[batch * batchBSize + col * uniforms.dimInner + row];";let r="",n="";if(this.activation){let s=is(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}
|
|
}
|
|
`,n="value = activation(value, outCoord);"}let a=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);
|
|
${a}
|
|
${n}
|
|
setOutputAtCoords(batch, row, col, value);
|
|
}
|
|
${spe()}
|
|
`}};function ope(e){let t=e[1]/2,r=e[0],n=t>r?t:r;return`
|
|
var<workgroup> mm_Asub1 : array<array<f32, ${n}>, ${t}>;
|
|
var<workgroup> mm_Bsub1 : array<array<f32, ${r}>, ${n}>;
|
|
var<workgroup> mm_Asub2 : array<array<f32, ${n}>, ${t}>;
|
|
var<workgroup> mm_Bsub2 : array<array<f32, ${r}>, ${n}>;
|
|
|
|
// If the output size is small for matrix multiplication, avoid to use vec4
|
|
// and handle some elements per thread to optimally utilize the ALU.
|
|
// 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.
|
|
${Hi()}
|
|
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) / ${n} + 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 + ${n};
|
|
mm_Bsub1[tileRow][tileCol] = mm_readB(globalRowB, globalCol, globalId);
|
|
globalRowB = globalRowB + ${n};
|
|
}
|
|
} 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 + ${n};
|
|
mm_Bsub1[tileRow][tileCol] = mm_readB(globalRowB, globalCol, globalId);
|
|
globalRowB = globalRowB + ${n};
|
|
} else {
|
|
// Compute acc values for a single thread.
|
|
for (var k = 0; k < ${n}; 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 + ${n};
|
|
mm_Bsub2[tileRow][tileCol] = mm_readB(globalRowB, globalCol, globalId);
|
|
globalRowB = globalRowB + ${n};
|
|
} else {
|
|
// Compute acc values for a single thread.
|
|
for (var k = 0; k < ${n}; 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 lpe=class{constructor(e,t,r,n=null,a=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=n!=null;i&&this.variableNames.push("bias");let o=s!=null;o&&this.variableNames.push("preluActivationWeights"),this.addBias=i,this.activation=a,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[batch * batchASize + row * uniforms.dimInner + col];
|
|
}
|
|
return 0.0;`,t=`if (coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimInner, uniforms.dimBOuter))) {
|
|
return B[batch * batchBSize + row * uniforms.dimBOuter + col];
|
|
}
|
|
return 0.0;`,r="",n="";if(this.activation){let s=is(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}
|
|
}`,n="value = activation(value, outCoord);"}let a=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;
|
|
${a}
|
|
${n}
|
|
setOutputAtCoords(batch, row, col, value);
|
|
}
|
|
}
|
|
${ope(this.workGroupSize)}
|
|
`}};function qe(e){let{inputs:t,attrs:r}=e,{x:n}=t,{shape:a}=r,s=w.sizeFromShape(n.shape),i=w.inferFromImplicitShape(a,s),o=w.sizeFromShape(i);return w.assert(s===o,()=>`The new shape (${i}) has ${o} elements and the old shape (${n.shape}) has ${s} elements. The new shape and old shape must have the same number of elements.`),e.backend.incRef(n.dataId),{dataId:n.dataId,shape:i,dtype:n.dtype}}var upe={kernelName:pl,backendName:"webgpu",kernelFunc:qe};function Ib({a:e,b:t,transposeA:r,transposeB:n,backend:a,bias:s=null,preluActivationWeights:i=null,leakyreluAlpha:o=0,activation:l=null}){let u=e.shape.length,d=t.shape.length,h=r?e.shape[u-2]:e.shape[u-1],p=n?t.shape[d-1]:t.shape[d-2],c=r?e.shape[u-1]:e.shape[u-2],f=n?t.shape[d-2]:t.shape[d-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),y=w.sizeFromShape(m),A=w.sizeFromShape(g),x=Nl.assertAndGetBroadcastShape(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([c,f]);w.assert(h===p,()=>`Error in matMul: inner shapes (${h}) and (${p}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${r} and transposeB=${n} must match.`);let b=r?[y,h,c]:[y,c,h],v=n?[A,f,p]:[A,p,f],S=qe({inputs:{x:e},backend:a,attrs:{shape:b}}),T=qe({inputs:{x:t},backend:a,attrs:{shape:v}}),E=[S,T],R=Math.max(y,A),_=h%4===0&&f%4===0&&!r&&!n&&f>=32,M;c*f<=32?M=new ipe([R,c,f],r,n,s,l,i):!r&&!n&&(c<=16&&(f<=512||p>=2*f)||f<=16&&(c<=512||h>=2*c))?M=new lpe(b,v,[R,c,f],s,l,i):_?M=new npe(b,[R,c,f],Y().get("WEBGPU_MATMUL_WORK_PER_THREAD"),s,l,i):M=new P8(b,[R,c,f],Y().get("WEBGPU_MATMUL_WORK_PER_THREAD"),r,n,s,l,i);let I=[S,T];s&&I.push(s),i&&I.push(i);let z=[{type:"int32",data:[c]},{type:"int32",data:[f]},{type:"int32",data:[h]}];l==="leakyrelu"&&(z.push({type:"float32",data:[o]}),M.uniforms+=" alpha : f32,");let O=a.runWebGPUProgram(M,I,e.dtype,z),j=qe({inputs:{x:O},backend:a,attrs:{shape:x}});E.push(O);for(let X of E)a.disposeData(X.dataId);return j}function dpe(e){let{inputs:t,backend:r,attrs:n}=e,{a,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:u,activation:d,leakyreluAlpha:h}=n;return Ib({a,b:s,transposeA:l,transposeB:u,backend:r,bias:i,preluActivationWeights:o,leakyreluAlpha:h,activation:d})}var ppe={kernelName:Fs,backendName:"webgpu",kernelFunc:dpe},iw=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=Ke(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 {
|
|
${Wh(this.op,!1)}
|
|
}
|
|
|
|
${et()}
|
|
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));
|
|
}
|
|
}
|
|
`}},hpe=class{constructor(e,t,r,n){this.variableNames=["A","B"],this.size=!0;let a=256;this.workGroupSize=[a,1,1],this.outputShape=N.assertAndGetBroadcastShape(t,r),this.dispatchLayout=Ke(this.outputShape),this.lastDimensionSize=n?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=n,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 {
|
|
${Wh(this.op,!1)}
|
|
}
|
|
var<workgroup> sharedBuf : array<f32, ${this.lastDimensionSize}>;
|
|
${et()}
|
|
|
|
// 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"}[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));
|
|
}
|
|
}
|
|
}
|
|
`}},cpe=class{constructor(e,t,r){this.variableNames=["A","B"],this.workPerThread=4,this.isVec4=!0,this.size=!0;let n=128;this.workGroupSize=[n,1,1],this.outputShape=N.assertAndGetBroadcastShape(t,r),this.dispatchLayout=Ke(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> {
|
|
${Wh(this.op,this.isVec4)}
|
|
}
|
|
${et()}
|
|
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 n=128;this.workGroupSize=[n,1,1],this.outputShape=N.assertAndGetBroadcastShape(t,r),this.dispatchLayout=Ke(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 {
|
|
${Wh(this.op,!1)}
|
|
}
|
|
${et()}
|
|
if (index < uniforms.size) {
|
|
let a = getAByOutputIndex(index);
|
|
let b = getBByOutputIndex(index);
|
|
setOutputAtIndex(index, binaryOperation(a, b));
|
|
}
|
|
}
|
|
`}};function ow(e,t,r){if(w.arraysEqual(t,r)&&w.sizeFromShape(t)%4===0)return new cpe(e,t,r);let n=t.length===1&&r.length>1&&t[0]<1024,a=r.length===1&&t.length>1&&r[0]<1024;return n||a?new hpe(e,t,r,a):new _8(e,t,r)}function Pn(e){let{inputs:t}=e,{x:r}=t;return e.backend.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}var fpe={kernelName:ci,backendName:"webgpu",kernelFunc:Pn};function Cd(e){let{inputs:t,backend:r}=e,{real:n,imag:a}=t,s=r.makeTensorInfo(n.shape,"complex64"),i=r.tensorMap.get(s.dataId),o=Pn({inputs:{x:n},backend:r}),l=Pn({inputs:{x:a},backend:r});return i.complexTensorInfos={real:o,imag:l},s}var mpe={kernelName:Xp,backendName:"webgpu",kernelFunc:Cd},Vh=class{constructor(e,t){this.variableNames=["A"],this.size=!0;let r=128;this.workGroupSize=[r,1,1],this.outputShape=e,this.dispatchLayout=Ke(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 {
|
|
${yo(this.op,!1)}
|
|
}
|
|
${et()}
|
|
if (index < uniforms.size) {
|
|
let a = getAByOutputIndex(index);
|
|
setOutputAtIndex(index, unaryOperation(a));
|
|
}
|
|
}
|
|
`}};function kr({opType:e,cpuKernelImpl:t,dtype:r}){return({inputs:n,backend:a})=>{let{x:s}=n,i=a,o=r||s.dtype;if(i.shouldExecuteOnCPU([s])&&t!=null){let u=i.tensorMap.get(s.dataId),d=t(u.values,o);return i.makeTensorInfo(s.shape,o,d)}let l=new Vh(s.shape,e);return i.runWebGPUProgram(l,[s],o)}}function Hr({opSnippet:e,cpuKernelImpl:t,supportsComplex:r=!1,dtype:n}){return({inputs:a,backend:s})=>{let{a:i,b:o}=a,l=s;if(r&&i.dtype==="complex64"){let h=l.tensorMap.get(i.dataId),p=l.tensorMap.get(o.dataId),c,f;if(e!==0)[c,f]=[[h.complexTensorInfos.real,p.complexTensorInfos.real],[h.complexTensorInfos.imag,p.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=ow(e,i.shape,o.shape);return l.runWebGPUProgram(v,[x,b],Cr(y.dtype,A.dtype))});else{let g=new iw(17,i.shape,o.shape),y=new iw(18,i.shape,o.shape),A=[{dataId:h.complexTensorInfos.real.dataId,dtype:h.complexTensorInfos.real.dtype,shape:i.shape},{dataId:h.complexTensorInfos.imag.dataId,dtype:h.complexTensorInfos.imag.dtype,shape:i.shape},{dataId:p.complexTensorInfos.real.dataId,dtype:p.complexTensorInfos.real.dtype,shape:o.shape},{dataId:p.complexTensorInfos.imag.dataId,dtype:p.complexTensorInfos.imag.dtype,shape:o.shape}];c=l.runWebGPUProgram(g,A,"float32"),f=l.runWebGPUProgram(y,A,"float32")}let m=Cd({inputs:{real:c,imag:f},backend:l});return l.disposeData(c.dataId),l.disposeData(f.dataId),m}let u=n||Cr(i.dtype,o.dtype);if((i.dtype==="string"||o.dtype==="string"||l.shouldExecuteOnCPU([i,o]))&&t!=null){let h=l.tensorMap.get(i.dataId).values,p=l.tensorMap.get(o.dataId).values,c=i.dtype==="string"?N.fromUint8ToStringArray(h):h,f=i.dtype==="string"?N.fromUint8ToStringArray(p):p,[m,g]=t(i.shape,o.shape,c,f,u);return l.makeTensorInfo(g,u,m)}let d=ow(e,i.shape,o.shape);return l.runWebGPUProgram(d,[i,o],u)}}var{addImpl:gpe,ceilImpl:ype,concatImpl:Ape,equalImpl:xpe,expImpl:bpe,expm1Impl:vpe,floorImpl:wpe,gatherNdImpl:kpe,gatherV2Impl:Ipe,greaterEqualImpl:Spe,greaterImpl:Tpe,lessEqualImpl:Npe,lessImpl:Cpe,logImpl:Epe,maxImpl:Rpe,maximumImpl:Mpe,minimumImpl:Fpe,multiplyImpl:$pe,negImpl:Ppe,notEqualImpl:_pe,prodImpl:zpe,rangeImpl:Ope,rsqrtImpl:Dpe,simpleAbsImpl:Lpe,sliceImpl:Bpe,stridedSliceImpl:Wpe,stringNGramsImpl:Vpe,subImpl:Upe,tileImpl:Gpe,topKImpl:jpe,transposeImpl:Hpe,uniqueImpl:txe}=g0,qpe=kr({opType:0,cpuKernelImpl:Lpe}),Kpe={kernelName:Vo,backendName:"webgpu",kernelFunc:qpe},Xpe=Hr({opSnippet:1,cpuKernelImpl:gpe,supportsComplex:!0}),Zpe={kernelName:Ja,backendName:"webgpu",kernelFunc:Xpe},Ype=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=Ke(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`
|
|
${et()}
|
|
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 Jpe(e){let{inputs:t,backend:r}=e,n=t;if(n.length===1)return Pn({inputs:{x:n[0]},backend:r});let a=n.map(o=>o.dtype).reduce((o,l)=>Cr(o,l)),s=n.map(o=>o.shape),i=new Ype(s);return r.runWebGPUProgram(i,n,a)}var Qpe={kernelName:Ks,backendName:"webgpu",kernelFunc:Jpe},z8=class{constructor(e,t,r){this.workGroupSize=[64,1,1],this.variableNames=["x"],this.uniforms="axis : i32, infinityValue : f32,",this.size=!0;let n=[t];N.assertAxesAreInnerMostDims("arg"+r.charAt(0).toUpperCase()+r.slice(1),n,e.length),this.op=r==="min"?"<":">";let[a]=N.computeOutAndReduceShapes(e,n);this.outputShape=a.length===0?[1]:a,this.dispatchLayout=Ke(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=(n,a)=>this.outputShape.length===1?n:`${n}[${a}]`,r=n=>this.inputShape.length===1?"uniforms.xShape":`uniforms.xShape[${n}]`;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;
|
|
}
|
|
|
|
${et()}
|
|
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[getInputIndex(coordInfo, k)]);
|
|
if (!isnan(candidate) && candidate ${this.op} bestValue) {
|
|
bestValue = candidate;
|
|
bestIndex = k;
|
|
}
|
|
}
|
|
xBestValues[localId.x] = bestValue;
|
|
xBestIndices[localId.x] = bestIndex;
|
|
workgroupBarrier();
|
|
|
|
var reduceSize = min(u32(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]);
|
|
}
|
|
}
|
|
`}},ehe=class{constructor(e,t){this.variableNames=["A"],this.workGroupSize=[16,16,1];let r=new Array(e.length);for(let n=0;n<r.length;n++)r[n]=e[t[n]];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]}>;
|
|
${xb()}
|
|
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[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]);
|
|
}
|
|
}
|
|
`}},the=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 n=0;n<r.length;n++)r[n]=e[t[n]];this.outputShape=r,this.dispatchLayout=Ke(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=yr(this.outputShape.length),t=rhe(this.newDim);return`
|
|
${et()}
|
|
|
|
for(var i = 0; i < ${this.workPerThread}; i = i + 1) {
|
|
let flatIndex = index * ${this.workPerThread} + i;
|
|
if(flatIndex < uniforms.size) {
|
|
let resRC = getCoordsFromIndex(flatIndex);
|
|
setOutputAtIndex(flatIndex, A[getIndexFromCoords${this.outputShape.length}D(
|
|
${e}(${t}), uniforms.aShape)]);
|
|
}
|
|
}
|
|
}
|
|
`}};function rhe(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 n=0;n<e.length;n++)r[e[n]]=`resRC[${n}]`;return r.join()}function Ya(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{perm:s}=n,i=r,o=a.shape.length,l=new Array(o);for(let d=0;d<l.length;d++)l[d]=a.shape[s[d]];if(r.shouldExecuteOnCPU([a])){let d=i.tensorMap.get(a.dataId).values,h=Hpe(d,a.shape,a.dtype,s,l);return r.makeTensorInfo(l,a.dtype,h)}if(a.shape.length===2&&w.arraysEqual(s,[1,0])){let d=new ehe(a.shape,s);return i.runWebGPUProgram(d,[a],a.dtype)}let u=new the(a.shape,s);return i.runWebGPUProgram(u,[a],a.dtype)}var nhe={kernelName:Bi,backendName:"webgpu",kernelFunc:Ya};function ahe(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s}=n,i=w.parseAxisParam(s,a.shape),o=N.getAxesPermutation(i,a.shape.length),l=a,u=[];o!=null&&(l=Ya({inputs:{x:a},backend:r,attrs:{perm:o}}),u.push(l),i=N.getInnerMostAxes(i.length,l.shape.length)),N.assertAxesAreInnerMostDims("argMax",[i[0]],l.shape.length);let d=new z8(l.shape,i[0],"max"),h=[{type:"int32",data:[i[0]]},{type:"float32",data:[Number.NEGATIVE_INFINITY]}],p=r.runWebGPUProgram(d,[l],"int32",h);return u.forEach(c=>r.disposeData(c.dataId)),p}var she={kernelName:Xs,backendName:"webgpu",kernelFunc:ahe};function ihe(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s}=n,i=w.parseAxisParam(s,a.shape),o=N.getAxesPermutation(i,a.shape.length),l=a,u=[];o!=null&&(l=Ya({inputs:{x:a},backend:r,attrs:{perm:o}}),u.push(l),i=N.getInnerMostAxes(i.length,l.shape.length)),N.assertAxesAreInnerMostDims("argMin",[i[0]],l.shape.length);let d=new z8(l.shape,i[0],"min"),h=[{type:"int32",data:[i[0]]},{type:"float32",data:[Number.POSITIVE_INFINITY]}],p=r.runWebGPUProgram(d,[l],"int32",h);return u.forEach(c=>r.disposeData(c.dataId)),p}var ohe={kernelName:Lu,backendName:"webgpu",kernelFunc:ihe},O8=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=Ke(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"),`
|
|
${et()}
|
|
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});
|
|
}
|
|
}
|
|
`}},D8=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=Ke(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="poolWithFilterSizeEqualsOne"}getUserCode(){return`
|
|
${et()}
|
|
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 lhe(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,u=1,d=N.computePool2DInfo(a.shape,s,i,u,o,l);if(d.filterWidth===1&&d.filterHeight===1&&w.arraysEqual(d.inShape,d.outShape))return Pn({inputs:{x:a},backend:r});let h,p=[{type:"int32",data:[d.strideHeight,d.strideWidth]}];return d.filterHeight===1&&d.filterWidth===1?h=new D8(d):(h=new O8(d,"avg"),p.push({type:"int32",data:[d.padInfo.top,d.padInfo.left]},{type:"int32",data:[d.dilationHeight,d.dilationWidth]},{type:"int32",data:[d.inHeight,d.inWidth]},{type:"int32",data:[d.effectiveFilterHeight,d.effectiveFilterWidth]})),r.runWebGPUProgram(h,[a],a.dtype,p)}var uhe={kernelName:Zs,backendName:"webgpu",kernelFunc:lhe};function dhe(e){let{inputs:t,backend:r,attrs:n}=e,{a,b:s}=t,{transposeA:i,transposeB:o}=n;return Ib({a,b:s,transposeA:i,transposeB:o,backend:r})}var phe={kernelName:Ys,backendName:"webgpu",kernelFunc:dhe},hhe=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=Ke(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.start=e,this.uniforms=`start : ${yr(e.length)}, `,this.shaderKey="slice"}getUserCode(){let e=yr(this.rank),t=che(this.rank),r;return this.start.length===1?r=this.outputShape.map((n,a)=>"sourceLoc = uniforms.start + coords;"):r=this.outputShape.map((n,a)=>`sourceLoc.${r2[a]} = uniforms.start[${a}] + coords.${r2[a]};`),`
|
|
${et()}
|
|
if (index < uniforms.size) {
|
|
var sourceLoc : ${e};
|
|
let coords = getCoordsFromIndex(index);
|
|
${r.join(`
|
|
`)}
|
|
setOutputAtIndex(index, getSource(${t}));
|
|
}
|
|
}
|
|
`}},r2=["x","y","z","w","u","v"];function che(e){if(e===1)return"sourceLoc";if(e<=6)return r2.slice(0,e).map(t=>`sourceLoc.${t}`).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}function Ed(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{begin:s,size:i}=n,[o,l]=zt.parseSliceParams(a,s,i);if(zt.assertParamsValid(a,o,l),r.shouldExecuteOnCPU([a])||a.dtype==="string"){let h=r.tensorMap.get(a.dataId),p=Bpe(h.values,o,l,a.shape,a.dtype);return r.makeTensorInfo(l,a.dtype,p)}if(w.sizeFromShape(l)===0)return r.makeTensorInfo(l,a.dtype,[]);let u=new hhe(o,l),d=[{type:"int32",data:o}];return r.runWebGPUProgram(u,[a],a.dtype,d)}var fhe={kernelName:gl,backendName:"webgpu",kernelFunc:Ed},mhe=e=>{let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockShape:s,crops:i}=n;w.assert(a.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(a.shape,s,o),u=N.getPermuted(l.length,s.length),d=N.getReshapedPermuted(a.shape,s,o),h=N.getSliceBeginCoords(i,s.length),p=N.getSliceSize(d,i,s.length),c=[],f=qe({inputs:{x:a},backend:r,attrs:{shape:l}}),m=Ya({inputs:{x:f},backend:r,attrs:{perm:u}}),g=qe({inputs:{x:m},backend:r,attrs:{shape:d}}),y=Ed({inputs:{x:g},backend:r,attrs:{begin:h,size:p}});return c.push(f),c.push(m),c.push(g),c.forEach(A=>r.disposeData(A.dataId)),y},ghe={kernelName:Uo,backendName:"webgpu",kernelFunc:mhe},L8=Hr({opSnippet:10,dtype:"bool",cpuKernelImpl:_pe}),yhe={kernelName:sl,backendName:"webgpu",kernelFunc:L8};function Uh(e){let{inputs:t,backend:r}=e,{input:n}=t,a=r.tensorMap.get(n.dataId);return Pn({inputs:{x:a.complexTensorInfos.real},backend:r})}var Ahe={kernelName:ah,backendName:"webgpu",kernelFunc:Uh};function xhe(e,t){let r=new Vh(e.shape,22),n=t.runWebGPUProgram(r,[e],"int32");return{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}function n2(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{dtype:s}=n;if(s==="complex64"){if(a.dtype==="complex64")return Pn({inputs:{x:a},backend:r});let i=Pt(a.shape),o=n2({inputs:{x:a},backend:r,attrs:{dtype:"float32"}}),l=Cd({inputs:{real:o,imag:i},backend:r});return i.dispose(),r.disposeData(o.dataId),l}if(a.dtype==="complex64"){let i=Uh({inputs:{input:a},backend:r}),o=n2({inputs:{x:i},backend:r,attrs:{dtype:s}});return r.disposeData(i.dataId),o}if(!w.hasEncodingLoss(a.dtype,s)){let i=Pn({inputs:{x:a},backend:r});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(s==="int32")return xhe(a,r);if(s==="bool"){let i=r.makeTensorInfo([],"bool",w.getTypedArrayFromDType("bool",1)),o=L8({inputs:{a,b:i},backend:r});return r.disposeData(i.dataId),o}throw new Error(`Error in Cast: failed to cast ${a.dtype} to ${s}`)}var bhe={kernelName:Js,backendName:"webgpu",kernelFunc:n2},vhe=kr({opType:1,cpuKernelImpl:ype}),whe={kernelName:Qs,backendName:"webgpu",kernelFunc:vhe},khe=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=Ke(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.shaderKey="clipVec4"}getUserCode(){return`
|
|
${et()}
|
|
if(index < uniforms.size) {
|
|
let value = getAByOutputIndex(index);
|
|
var clampedValue : vec4<f32>;
|
|
for (var i = 0; i < 4; i = i + 1) {
|
|
if (isnan(value[i])) {
|
|
clampedValue[i] = value[i];
|
|
} else {
|
|
clampedValue[i] = clamp(value[i], uniforms.minVal, uniforms.maxVal);
|
|
}
|
|
}
|
|
|
|
setOutputAtIndex(index, clampedValue);
|
|
}
|
|
}
|
|
`}},Ihe=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=Ke(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="clip"}getUserCode(){return`
|
|
${et()}
|
|
if(index < uniforms.size) {
|
|
let value = getAByOutputIndex(index);
|
|
if (isnan(value)) {
|
|
setOutputAtIndex(index, value);
|
|
return;
|
|
}
|
|
setOutputAtIndex(index, clamp(value, uniforms.minVal, uniforms.maxVal));
|
|
}
|
|
}
|
|
`}};function She(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{clipValueMin:s,clipValueMax:i}=n,o,l=[{type:"float32",data:[s]},{type:"float32",data:[i]}];return w.sizeFromShape(a.shape)%4===0?o=new khe(a.shape):o=new Ihe(a.shape),r.runWebGPUProgram(o,[a],a.dtype,l)}var The={kernelName:Qa,backendName:"webgpu",kernelFunc:She},Nhe=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=Ke(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 n=1;n<this.offsetLength;n++)e.push(`else if (yC < uniforms.offset${[n]}){ setOutputAtCoords(coords.x, coords.y, getT${n}(yR, yC - uniforms.offset${n-1})); }`);let t=this.offsetLength,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`
|
|
${et()}
|
|
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 S0(e){let{inputs:t,backend:r}=e,{input:n}=t,a=r.tensorMap.get(n.dataId);return Pn({inputs:{x:a.complexTensorInfos.imag},backend:r})}var Che={kernelName:eh,backendName:"webgpu",kernelFunc:S0};function a2(e,t,r){let n=e[0].dtype;if(n==="complex64"){let c=e.map(A=>Uh({inputs:{input:A},backend:r})),f=e.map(A=>S0({inputs:{input:A},backend:r})),m=a2(c,t,r),g=a2(f,t,r),y=Cd({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 a=r.shouldExecuteOnCPU(e);if(n==="string"&&(a=!0),a){let c=e.map(b=>{let v=w.sizeFromShape(b.shape.slice(t));return qe({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=Ape(f,m,n,g),A=N.computeOutShape(e.map(b=>b.shape),t),x=r.makeTensorInfo(A,n,y);return c.forEach(b=>r.disposeData(b.dataId)),x}let{tensors2D:s,outShape:i}=Ehe(e,t,r),o=s.map(c=>c.shape),l=new Nhe(o),u=[],d=new Array(o.length-1);if(d.length>0){d[0]=o[0][1],u.push({type:"int32",data:[d[0]]});for(let c=1;c<d.length;c++)d[c]=d[c-1]+o[c][1],u.push({type:"int32",data:[d[c]]})}let h=r.runWebGPUProgram(l,s,s[0].dtype,u);s.forEach(c=>r.disposeData(c.dataId));let p=qe({inputs:{x:h},backend:r,attrs:{shape:i}});return r.disposeData(h.dataId),p}function Ehe(e,t,r){let n=N.computeOutShape(e.map(a=>a.shape),t);return{tensors2D:e.map(a=>qe({inputs:{x:a},backend:r,attrs:{shape:[w.sizeFromShape(a.shape.slice(0,t)),w.sizeFromShape(a.shape.slice(t))]}})),outShape:n}}function B8(e){let{inputs:t,backend:r,attrs:n}=e,{axis:a}=n,s=w.parseAxisParam(a,t[0].shape)[0],i=N.computeOutShape(t.map(u=>u.shape),s);if(w.sizeFromShape(i)===0)return r.makeTensorInfo(i,t[0].dtype,[]);let o=t.filter(u=>w.sizeFromShape(u.shape)>0);if(o.length===1)return Pn({inputs:{x:o[0]},backend:r});let l=o.map(u=>u.shape);return N.assertParamsConsistent(l,s),a2(o,s,r)}var Rhe={kernelName:Go,backendName:"webgpu",kernelFunc:B8},Mhe=class{constructor(e,t=!1,r=null,n=!1,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.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=n,this.hasLeakyreluAlpha=a,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],n=this.outputShape[3],a=this.convInfo.filterHeight*this.convInfo.filterWidth*this.convInfo.inChannels;return[Za(e,[r,a]),Za(t,[a,n])]}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[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[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=$8(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[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);
|
|
`,n=this.fitB?"return W[row * uniforms.dimBOuter / 4 + col];":`if(coordsInBounds2D(vec2<i32>(row, col * 4), vec2<i32>(uniforms.dimInner, uniforms.dimBOuter))) {
|
|
return W[row * uniforms.dimBOuter / 4 + col];
|
|
}
|
|
return vec4<f32>(0.0);
|
|
`,a="",s="";if(this.activation){let o=is(this.activation,this.isVec4);if(this.hasPreluActivationWeights)a=`fn activation(a : vec4<f32>, outCoord : vec4<i32>) -> vec4<f32> {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${o}
|
|
}`;else{if(this.hasLeakyreluAlpha)throw a=`fn activation(outCoord: vec4<f32>) -> vec4<f32> {
|
|
let b = getLeakyreluAlphaByOutputCoords(outCoord);
|
|
${o}
|
|
}`,new Error("Leakyrelu is not supported.");a=`
|
|
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`
|
|
${a}
|
|
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> {
|
|
${n}
|
|
}
|
|
|
|
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}
|
|
`}},Fhe=class{constructor(e,t=!1,r=null,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.outputShape=e.outShape,w.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),this.dispatchLayout={x:[3],y:[1,2],z:[0]},this.workGroupSize=bb(this.dispatchLayout,this.outputShape),this.elementsPerThread=vb(this.dispatchLayout,this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize,this.elementsPerThread),t&&this.variableNames.push("bias"),n&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=r,this.hasPreluActivationWeights=n,[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 n=[e,r],a=[r,t],s=this.outputShape[1]*this.outputShape[2],i=this.outputShape[3],o=this.convInfo.filterHeight*this.convInfo.filterWidth*this.convInfo.inChannels;return[Za(n,[s,o]),Za(a,[o,i])]}getUserCode(){let e=kb(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[getIndexFromCoords4D(coord, uniforms.xShape)];
|
|
}
|
|
return 0.0;`,r=this.fitA?`${t}`:`if (row < uniforms.dimAOuter && col < uniforms.dimInner) {
|
|
${t}
|
|
}
|
|
return 0.0;
|
|
`,n=this.fitB?"return W[row * uniforms.dimBOuter + col];":`if(coordsInBounds2D(vec2<i32>(row, col), vec2<i32>(uniforms.dimInner, uniforms.dimBOuter))) {
|
|
return W[row * uniforms.dimBOuter + col];
|
|
}
|
|
return 0.0;
|
|
`,a="",s="";if(this.activation){let o=is(this.activation,!1);this.hasPreluActivationWeights?a=`fn activation(a: f32, outCoord : vec4<i32>) -> f32 {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${o}
|
|
}`:a=`
|
|
fn activation(a : f32, outCoord : vec4<i32>) -> f32 {
|
|
${o}
|
|
}
|
|
`,s="value = activation(value, outCoord);"}let i=this.addBias?"value = value + getBiasByOutputCoords(outCoord);":"";return`
|
|
${a}
|
|
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 {
|
|
${n}
|
|
}
|
|
|
|
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[getIndexFromCoords4D(outCoord, uniforms.outShape)] = value;
|
|
}
|
|
${e}
|
|
`}},$he=class{constructor(e,t=!1,r=null,n=!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=Ke(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"),n&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=r,this.hasPreluActivationWeights=n,this.shaderKey=`conv2DNaive_${this.activation}`}getUserCode(){let e="",t="";if(this.activation){let n=is(this.activation);this.hasPreluActivationWeights?e=`fn activation(a : f32, outCoord : vec4<i32>) -> f32{
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${n}
|
|
}`:e=`
|
|
fn activation(a : f32, outCoord : vec4<i32>) -> f32{
|
|
${n}
|
|
}
|
|
`,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);
|
|
}
|
|
}
|
|
|
|
${Hi()}
|
|
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);
|
|
}
|
|
`}},Phe=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=Ke(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`
|
|
${et()}
|
|
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
`}};function _he({x:e,filter:t,convInfo:r,backend:n,bias:a=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let l=e.shape,u=r.dataFormat==="channelsLast",d=!1,h=!1,p=r.filterHeight===r.inHeight&&r.filterWidth===r.inWidth&&r.padInfo.type==="VALID",c,f;if(p){let y=r.inHeight*r.inWidth*r.inChannels;c=qe({inputs:{x:e},backend:n,attrs:{shape:[1,r.batchSize,y]}}),f=qe({inputs:{x:t},backend:n,attrs:{shape:[1,y,r.outChannels]}})}else{let y=u?l[0]*l[1]*l[2]:l[0]*l[2]*l[3];c=qe({inputs:{x:e},backend:n,attrs:{shape:[1,y,r.inChannels]}}),f=qe({inputs:{x:t},backend:n,attrs:{shape:[1,r.inChannels,r.outChannels]}})}let m=Ib({a:c,b:f,transposeA:d,transposeB:h,backend:n,bias:a,activation:o,preluActivationWeights:s,leakyreluAlpha:i}),g=qe({inputs:{x:m},backend:n,attrs:{shape:r.outShape}});return n.disposeData(c.dataId),n.disposeData(f.dataId),n.disposeData(m.dataId),g}function zhe({x:e,filter:t,convInfo:r,backend:n,bias:a=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let{filterWidth:l,filterHeight:u,inChannels:d,strideWidth:h,strideHeight:p,padInfo:c,outWidth:f,outHeight:m,dilationWidth:g,dilationHeight:y,dataFormat:A}=r,x=A==="channelsLast",b=l*u*d,v=m*f,S=[v,b],T=!1,E=!1,R=[],_=qe({inputs:{x:e},backend:n,attrs:{shape:e.shape.slice(1)}}),M=qe({inputs:{x:t},backend:n,attrs:{shape:[1,b,-1]}});R.push(_),R.push(M);let I=new Phe(S,x),z=[{type:"int32",data:[c.left,c.top]},{type:"int32",data:[h,p]},{type:"int32",data:[g,y]},{type:"int32",data:[f]},{type:"int32",data:[d*l]},{type:"int32",data:[d]}],O=n.runWebGPUProgram(I,[_],_.dtype,z),j=qe({inputs:{x:O},backend:n,attrs:{shape:[1,S[0],S[1]]}});R.push(O),R.push(j);let X=[1,S[0],S[1]],D=new P8(X,[1,v,r.outChannels],Y().get("WEBGPU_MATMUL_WORK_PER_THREAD"),T,E,a,o,s),Q=X[1],V=X[2],ee=r.outChannels,J=[{type:"int32",data:[Q]},{type:"int32",data:[ee]},{type:"int32",data:[V]}],ie=[j,M];a&&ie.push(a),s&&ie.push(s),o==="leakyrelu"&&(z.push({type:"float32",data:[i]}),D.uniforms+=" alpha : f32,");let Z=n.runWebGPUProgram(D,ie,j.dtype,J),ae=x?[1,m,f,r.outChannels]:[1,r.outChannels,m,f],de=qe({inputs:{x:Z},backend:n,attrs:{shape:ae}});R.push(Z);for(let Ae of R)n.disposeData(Ae.dataId);return de}function W8({x:e,filter:t,convInfo:r,backend:n,bias:a=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let l=a!=null,u=s!=null,d;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 _he({x:e,filter:t,convInfo:r,backend:n,bias:a,activation:o,preluActivationWeights:s,leakyreluAlpha:i});if(Y().getBool("WEBGPU_CONV_SEPARATE_IM2COL_SHADER")&&e.shape[0]===1)return zhe({x:e,filter:t,convInfo:r,backend:n,bias:a,preluActivationWeights:s,leakyreluAlpha:i,activation:o});let h=Y().getBool("WEBGPU_USE_NAIVE_CONV2D"),p=(r.inChannels%4===0||r.inChannels===3&&r.padInfo.type==="VALID")&&r.outChannels%4===0,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(h)d=new $he(r,l,o,u);else{p?d=new Mhe(r,l,o,u):d=new Fhe(r,l,o,u);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(a),u&&m.push(s),o==="leakyrelu"&&(f.push({type:"float32",data:[i]}),d.uniforms+=" alpha : f32,"),n.runWebGPUProgram(d,m,e.dtype,f)}function Ohe(e){let{inputs:t,attrs:r,backend:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:d}=r,h=N.convertConv2DDataFormat(l),p=N.computeConv2DInfo(a.shape,s.shape,i,u,o,d,!1,h);return W8({x:a,filter:s,convInfo:p,backend:n})}var Dhe={kernelName:ei,backendName:"webgpu",kernelFunc:Ohe},Lhe=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=bb(this.dispatchLayout,this.outputShape),this.elementsPerThread=vb(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[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[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[getIndexFromCoords4D(outCoord, uniforms.outShape)] = value;
|
|
}
|
|
|
|
${kb(this.elementsPerThread,this.workGroupSize)}
|
|
`}},Bhe=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=Ke(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`
|
|
${et()} {
|
|
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 Whe(e){let{inputs:t,backend:r,attrs:n}=e,{dy:a,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:u,dimRoundingMode:d}=n,h=N.convertConv2DDataFormat(u),p=N.computeConv2DInfo(i,s.shape,o,1,l,d,!1,h),c=[{type:"int32",data:[p.filterHeight,p.filterWidth]},{type:"int32",data:[p.filterHeight-1-p.padInfo.top,p.filterWidth-1-p.padInfo.left]},{type:"int32",data:[p.strideHeight,p.strideWidth]},{type:"int32",data:[p.batchSize,p.outHeight,p.outWidth,p.outChannels]}],f;if(Y().getBool("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE"))f=new Bhe(p);else{f=new Lhe(p);let m=p.inShape[1]*p.inShape[2],g=p.inShape[3],y=p.filterHeight*p.filterWidth*p.outChannels;c.push({type:"uint32",data:[m]},{type:"uint32",data:[g]},{type:"uint32",data:[y]})}return r.runWebGPUProgram(f,[a,s],"float32",c)}var Vhe={kernelName:ti,backendName:"webgpu",kernelFunc:Whe},Uhe=kr({opType:2}),Ghe={kernelName:ri,backendName:"webgpu",kernelFunc:Uhe},jhe=kr({opType:3}),Hhe={kernelName:ni,backendName:"webgpu",kernelFunc:jhe},qhe=class{constructor(e,t,r,n){this.variableNames=["Image","Boxes","BoxInd"],this.uniforms="extrapolationValue : f32,",this.workGroupSize=[64,1,1],this.size=!0;let[a]=t;this.outputShape=[a,r[0],r[1],e],this.dispatchLayout=Ke(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.methodId=n==="bilinear"?1:0,this.cropHeightBiggerThan1=this.outputShape[1]>1,this.cropWidthBiggerThan1=this.outputShape[2]>1,this.shaderKey=`cropAndResize_${this.methodId}_${this.cropHeightBiggerThan1}_${this.cropWidthBiggerThan1}`}getUserCode(){let[e,t]=["f32(uniforms.imageShape[1] - 1)","f32(uniforms.imageShape[2] - 1)"],[r,n,a]=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`
|
|
${et()}
|
|
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 = ${n};
|
|
let width_scale = ${i};
|
|
let in_y = ${a};
|
|
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);
|
|
}
|
|
}
|
|
}
|
|
`}},Khe=e=>{let{inputs:t,backend:r,attrs:n}=e,{image:a,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=n,d=new qhe(a.shape[3],s.shape,o,l),h=[{type:"float32",data:[u]}];return r.runWebGPUProgram(d,[a,s,i],"float32",h)},Xhe={kernelName:Ho,backendName:"webgpu",kernelFunc:Khe},lw=class{constructor(e,t,r,n){this.variableNames=["x"],this.uniforms="index : f32,",this.size=!0;let a=128;this.workGroupSize=[a,1,1],this.outputShape=t,this.dispatchLayout=Ke(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.exclusive=r,this.reverse=n,this.op=e,this.shaderKey=`cum_${this.op}_${this.exclusive}_${this.reverse}`}getUserCode(){let e=this.outputShape.length,t=this.op==="*"?"1.0":"0.0",r=this.exclusive?t:`getX(${uw(e,"coords",this.op)})`,n=this.outputShape[this.outputShape.length-1],a="",s="";return this.exclusive?(a=this.reverse?`end != ${n-1}`:"end != 0",s=this.reverse?"end + 1":"end - 1"):(a=this.reverse?`end + pow2 < ${n}`:"end >= pow2",s=this.reverse?"end + pow2":"end - pow2"),`
|
|
${et()}
|
|
if (index < uniforms.size) {
|
|
var coords = getCoordsFromIndex(index);
|
|
|
|
let end = ${dw(e,"coords",this.op)};
|
|
var val = ${r};
|
|
let pow2 = i32(pow(2.0, uniforms.index));
|
|
if (${a}) {
|
|
let idx = ${s};
|
|
${dw(e,"coords",this.op)} = idx;
|
|
val ${this.op}= getX(${uw(e,"coords",this.op)});
|
|
}
|
|
setOutputAtIndex(index, val);
|
|
}
|
|
}
|
|
`}};function uw(e,t,r){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 ${r} for rank ${e} is not yet supported`)}function dw(e,t,r){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 ${r} for rank ${e} is not yet supported`)}function V8(e,t,r,n,a,s){let i=t.shape.length,o=N.getAxesPermutation([n],i),l=t;o!=null&&(l=Ya({inputs:{x:t},backend:r,attrs:{perm:o}}));let u=N.getInnerMostAxes(1,i)[0];if(u!==i-1)throw new Error(`WebGPU cumprod shader expects an inner-most axis=${t.shape.length-1} but got axis=${n}`);let d=l.shape[u],h=Pn({inputs:{x:l},backend:r});for(let p=0;p<=Math.ceil(Math.log2(d))-1;p++){let c=new lw(e,l.shape,!1,s),f=h,m=[{type:"float32",data:[p]}];h=r.runWebGPUProgram(c,[h],h.dtype,m),r.disposeData(f.dataId)}if(a){let p=new lw(e,l.shape,a,s),c=h,f=[{type:"float32",data:[0]}];h=r.runWebGPUProgram(p,[h],h.dtype,f),r.disposeData(c.dataId)}if(o!=null){let p=N.getUndoAxesPermutation(o),c=Ya({inputs:{x:h},backend:r,attrs:{perm:p}});return r.disposeData(h.dataId),r.disposeData(l.dataId),c}return h}function Zhe(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,exclusive:i,reverse:o}=n;return V8("*",a,r,s,i,o)}var Yhe={kernelName:jo,backendName:"webgpu",kernelFunc:Zhe};function Jhe(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,exclusive:i,reverse:o}=n;return V8("+",a,r,s,i,o)}var Qhe={kernelName:ai,backendName:"webgpu",kernelFunc:Jhe},ece=class{constructor(e,t){this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.uniforms="blockSize : i32,",this.outputShape=e,this.dispatchLayout=Ke(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`depthToSpace_${t}`,this.dataFormat=t}getUserCode(){return`
|
|
${et()}
|
|
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 tce(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockSize:s,dataFormat:i}=n,o=a.shape[0],l=i==="NHWC"?a.shape[1]:a.shape[2],u=i==="NHWC"?a.shape[2]:a.shape[3],d=i==="NHWC"?a.shape[3]:a.shape[1],h=l*s,p=u*s,c=d/(s*s),f=i==="NHWC"?[o,h,p,c]:[o,c,h,p],m=[{type:"int32",data:[s]}],g=new ece(f,i);return r.runWebGPUProgram(g,[a],a.dtype,m)}var rce={kernelName:qo,backendName:"webgpu",kernelFunc:tce},U8=class{constructor(e,t=!1,r=null,n=!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"),n&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=r,this.hasPreluActivation=n,this.shaderKey=`depthwise3x3_${r}`}getUserCode(){let e="",t="";if(this.activation){let n=is(this.activation,this.isVec4);this.hasPreluActivation?e=`fn activation(a : vec4<f32>, outCoord : vec4<i32>) -> vec4<f32> {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${n}
|
|
}`:e=`
|
|
fn activation(a : vec4<f32>, outCoord : vec4<i32>) -> vec4<f32> {
|
|
${n}
|
|
}
|
|
`,t="dotProd[i] = activation(dotProd[i], coords);"}let r=this.addBias?"dotProd[i] = dotProd[i] + getBiasByOutputCoords(coords);":"";return`
|
|
${e}
|
|
|
|
${xb()}
|
|
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]);
|
|
}
|
|
}
|
|
}
|
|
`}},G8=class{constructor(e,t=!1,r=null,n=!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=Ke(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"),n&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=r,this.hasPreluActivation=n,this.shaderKey=`depthwise_${this.activation}`}getUserCode(){let e="",t="";if(this.activation){let n=is(this.activation,!1);this.hasPreluActivation?e=`fn activation(a : f32, outCoord : vec4<i32>) -> f32 {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${n}
|
|
}`:e=`
|
|
fn activation(a : f32, outCoord : vec4<i32>) -> f32 {
|
|
${n}
|
|
}
|
|
`,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);
|
|
}
|
|
}
|
|
|
|
${Hi()}
|
|
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 nce(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s}=t,{strides:i,pad:o,dilations:l,dimRoundingMode:u}=n,d=l;d==null&&(d=[1,1]);let h=N.computeConv2DInfo(a.shape,s.shape,i,d,o,u,!0),p=[{type:"int32",data:[h.padInfo.top,h.padInfo.left]},{type:"int32",data:[h.strideHeight,h.strideWidth]},{type:"int32",data:[h.dilationHeight,h.dilationWidth]},{type:"int32",data:[h.inHeight,h.inWidth]}],c;return h.batchSize===1&&h.inHeight===h.outHeight&&h.inWidth===h.outWidth&&h.strideHeight===1&&h.strideWidth===1&&h.filterHeight===h.filterWidth&&h.inChannels===h.outChannels&&h.dilationHeight===1&&h.dilationWidth===1&&h.filterHeight===3&&h.inChannels%4===0?c=new U8(h):(c=new G8(h),p.push({type:"int32",data:[h.filterHeight]},{type:"int32",data:[h.filterWidth]},{type:"int32",data:[h.outChannels/h.inChannels]})),r.runWebGPUProgram(c,[a,s],a.dtype,p)}var ace={kernelName:si,backendName:"webgpu",kernelFunc:nce},j8=Hr({opSnippet:0,cpuKernelImpl:$pe,supportsComplex:!0}),sce={kernelName:ki,backendName:"webgpu",kernelFunc:j8},ice=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=Ke(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 (isnan(candidate)) {
|
|
bestValue = uniforms.NAN;
|
|
} else if (!isnan(bestValue) && candidate ${this.reduceType==="min"?"<":">"} bestValue)
|
|
{ bestValue = candidate; }`,t="f32(x[offset])"):this.reduceType==="sum"||this.reduceType==="mean"?e=" bestValue = bestValue + candidate; ":this.reduceType==="prod"&&(e=" bestValue = bestValue * candidate; ",t="1.0");let 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;
|
|
}
|
|
${et()}
|
|
let outputIndex = index / i32(workGroupSizeX);
|
|
let offset = getOffset(outputIndex);
|
|
var bestValue = ${t};
|
|
let Length = uniforms.reduceSize;
|
|
let WorkPerThread = DIV_CEIL(u32(Length), workGroupSizeX);
|
|
for (var k = i32(localId.x); k < Length && outputIndex < uniforms.size;
|
|
k = k + i32(workGroupSizeX)) {
|
|
let candidate = f32(x[offset + k]);
|
|
${e}
|
|
}
|
|
xBestValues[localId.x] = bestValue;
|
|
workgroupBarrier();
|
|
|
|
var reduceSize = min(u32(Length), workGroupSizeX);
|
|
for (var currentSize = reduceSize / 2u; reduceSize > 1u;
|
|
currentSize = reduceSize / 2u) {
|
|
let interval = DIV_CEIL(reduceSize, 2u);
|
|
if (localId.x < currentSize) {
|
|
let candidate = xBestValues[localId.x + interval];
|
|
${e}
|
|
xBestValues[localId.x] = bestValue;
|
|
}
|
|
reduceSize = interval;
|
|
workgroupBarrier();
|
|
}
|
|
|
|
if (localId.x == 0u && outputIndex < uniforms.size) {
|
|
${r}
|
|
}
|
|
}
|
|
`}};function Gh(e,t,r,n,a){let s=e.shape.length,i=[],o=w.parseAxisParam(t,e.shape),l=o,u=N.getAxesPermutation(l,s),d=e;u!=null&&(d=Ya({inputs:{x:e},attrs:{perm:u},backend:a}),l=N.getInnerMostAxes(l.length,s),i.push(d)),N.assertAxesAreInnerMostDims(n,l,s);let[h,p]=N.computeOutAndReduceShapes(d.shape,l),c=h;r&&(c=N.expandShapeToKeepDim(h,o));let f;if((n==="max"||n==="prod")&&a.shouldExecuteOnCPU([d])){let m=a.tensorMap.get(d.dataId).values;switch(n){case"max":let g=Rpe(m,w.sizeFromShape(p),c,e.dtype);f=a.makeTensorInfo(c,e.dtype,g);break;case"prod":let{outVals:y,outShape:A,outDtype:x}=zpe(d.shape,d.dtype,m,l);f=a.makeTensorInfo(A,x,y);break;default:throw new Error(`${n} CPU implementation is not yet supported.`)}}else{let m=w.sizeFromShape(p),g=w.sizeFromShape(d.shape)/m,y={windowSize:m,inSize:m,batchSize:g,outSize:1},A=n==="mean"?"float32":ch(e.dtype),x=[{type:"int32",data:[m]}],b=new ice(y,n),v=a.runWebGPUProgram(b,[d],A,x);i.push(v),f=qe({inputs:{x:v},attrs:{shape:c},backend:a})}return i.forEach(m=>a.disposeData(m.dataId)),f}function Sb(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n;return Gh(a,s,i,"sum",r)}var oce={kernelName:_i,backendName:"webgpu",kernelFunc:Sb};function lce(e){let{inputs:t,backend:r,attrs:n}=e,{equation:a}=n,s=t,{allDims:i,summedDims:o,idDims:l}=N.decodeEinsumEquation(a,s.length);N.checkEinsumDimSizes(i.length,l,s);let{path:u,steps:d}=N.getEinsumComputePath(o,l),h=d.length,p=null,c=i.length,f=[];for(let m=0;m<h;++m){for(let g of d[m]){let{permutationIndices:y,expandDims:A}=N.getEinsumPermutation(c,l[g]),x;N.isIdentityPermutation(y)?x=s[g]:(x=Ya({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=qe({inputs:{x},backend:r,attrs:{shape:b}}),f.push(x)),p===null?p=x:(p=j8({inputs:{a:x,b:p},backend:r}),f.push(p))}m<h-1&&(u[m]>=0&&(p=Sb({inputs:{x:p},backend:r,attrs:{axis:u[m]-(i.length-c),keepDims:!1}}),f.push(p)),c--)}for(let m of f)m!==p&&r.disposeData(m.dataId);return p}var uce={kernelName:Qp,backendName:"webgpu",kernelFunc:lce},dce=kr({opType:4}),pce={kernelName:oi,backendName:"webgpu",kernelFunc:dce},hce=Hr({opSnippet:4,dtype:"bool",cpuKernelImpl:xpe}),cce={kernelName:Ko,backendName:"webgpu",kernelFunc:hce},H8=kr({opType:5,cpuKernelImpl:bpe,dtype:"float32"}),fce={kernelName:li,backendName:"webgpu",kernelFunc:H8};function s2(e){let{inputs:t,attrs:r,backend:n}=e,{dim:a}=r,{input:s}=t,i=s.shape.length,o=s.shape.slice(),l=a;return a<0&&(w.assert(-(i+1)<=a,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+a+1),o.splice(l,0,1),qe({inputs:{x:s},backend:n,attrs:{shape:o}})}var mce={kernelName:Xo,backendName:"webgpu",kernelFunc:s2},gce=kr({opType:6,cpuKernelImpl:vpe}),yce={kernelName:Zo,backendName:"webgpu",kernelFunc:gce},Ace=class{constructor(e){this.variableNames=[],this.outputShape=[],this.uniforms="value : f32,",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Ke(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="fill"}getUserCode(){return`
|
|
${et()}
|
|
if (index < uniforms.size) {
|
|
setOutputAtIndex(index, uniforms.value);
|
|
}
|
|
}
|
|
`}};function Rd(e){let{backend:t,attrs:r}=e,{shape:n,value:a}=r,{dtype:s}=r;if(s=s||w.inferDtype(a),s==="string"){let i=w.getArrayFromDType(s,w.sizeFromShape(n));return i.fill(a),t.makeTensorInfo(n,s,i)}else{let i=new Ace(n),o=[{type:"float32",data:[a]}];return t.runWebGPUProgram(i,[],s,o)}}var xce={kernelName:Hu,backendName:"webgpu",kernelFunc:Rd},bce=class{constructor(e){this.outputShape=[],this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Ke(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="flipLeftRight"}getUserCode(){return`
|
|
${et()}
|
|
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);
|
|
}
|
|
}
|
|
`}},vce={kernelName:Yo,backendName:"webgpu",kernelFunc:({inputs:e,backend:t})=>{let{image:r}=e,n=t,a=new bce(r.shape);return n.runWebGPUProgram(a,[r],r.dtype)}},wce=kr({opType:7,cpuKernelImpl:wpe}),kce={kernelName:ui,backendName:"webgpu",kernelFunc:wce},Ice=Hr({opSnippet:12,dtype:"int32"}),Sce={kernelName:di,backendName:"webgpu",kernelFunc:Ice},Tce=(e,t,r,n,a)=>{let s=[n,...r];return a&&s.push(a),e.createBindGroup({layout:t,entries:s.map((i,o)=>({binding:o,resource:i}))})},q8=(e,t,r,n,a,s=!1)=>{let i={dtype:a.dtype,shape:a.shape},o=Zde(n,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 K8(e,t,r,n="",a=""){return e.shaderKey+"_"+(e.workGroupSize?e.workGroupSize.join(","):"")+t.map(s=>s.length).join(",")+r.join(",")+e.variableNames.join(",")+n+a}function pw(e){let{externalImage:t,backend:r,attrs:n,outShape:a,useImport:s}=e,{numChannels:i}=n,o=w.sizeFromShape(a),l=w.computeStrides(a),u=r.makeTensorInfo(a,"int32"),d=r.getFromPixelsProgram(s?"import":"copyExternal");d.updateOutputShape(a);let h=[u.shape],p=[u.dtype,s?"import":"copyExternal"],c=K8(d,h,p),f=d.getLayout(r.device),m=r.getAndSavePipeline(c,()=>q8(r.device,d,f.pipelineLayout,[],u,!0));d.setPipeline(m),s||r.queue.copyExternalImageToTexture({source:t,origin:{x:0,y:0}},{texture:d.makeInputTexture(r.device,a[1],a[0])},[a[1],a[0]]);let g=r.tensorMap.get(u.dataId);g.bufferInfo.buffer=r.acquireBuffer(g.bufferInfo.byteSize);let y=[o,i,...l,...d.dispatch];d.setUniform(r.device,y);let A;if(s){let x={source:t};A=r.device.importExternalTexture(x)}else A=d.inputTexture.createView();return r.runFromPixelsProgram(d,g.bufferInfo.buffer,f,A,u.dataId),u}var Nce={kernelName:Pp,backendName:"webgpu",kernelFunc:Cce},uu;function Cce(e){let{inputs:t,backend:r,attrs:n}=e,{pixels:a}=t,{numChannels:s}=n;if(a==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let i=typeof HTMLVideoElement!="undefined"&&a instanceof HTMLVideoElement,o=typeof HTMLImageElement!="undefined"&&a instanceof HTMLImageElement,l=typeof HTMLCanvasElement!="undefined"&&a instanceof HTMLCanvasElement||typeof OffscreenCanvas!="undefined"&&a instanceof OffscreenCanvas,u=typeof ImageBitmap!="undefined"&&a instanceof ImageBitmap,[d,h]=i?[a.videoWidth,a.videoHeight]:[a.width,a.height],p=[h,d,s];if(Y().getBool("WEBGPU_USE_IMPORT")&&i)return pw({externalImage:a,backend:r,attrs:n,outShape:p,useImport:!0});if((i||o)&&(uu==null&&(uu=document.createElement("canvas").getContext("2d")),uu.canvas.width=d,uu.canvas.height=h,uu.drawImage(a,0,0,d,h),a=uu.canvas),u||l||i||o)return pw({externalImage:a,backend:r,attrs:n,outShape:p,useImport:!1});let c=a.data,f=c;if(s!=null&&s!==4){f=new Uint8Array(a.width*a.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(p,"int32"),g=r.tensorMap.get(m.dataId);return g.values=new Int32Array(f),r.maybeReleaseBuffer(m.dataId),r.uploadToGPU(m.dataId),m}var Ece=class{constructor(e,t,r,n,a){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=Ke(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),n!=null&&(N.assertAndGetBroadcastShape(e,n),this.variableNames.push("offset")),a!=null&&(N.assertAndGetBroadcastShape(e,a),this.variableNames.push("scale")),this.offsetShape=n,this.scaleShape=a,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)"),`
|
|
${et()}
|
|
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)));
|
|
}
|
|
}
|
|
`}},Rce={kernelName:pi,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{x:n,scale:a,offset:s,mean:i,variance:o}=e,{varianceEpsilon:l}=t,u=r,d=[n,i,o],h=null;s!=null&&(h=s.shape,d.push(s));let p=null;a!=null&&(p=a.shape,d.push(a));let c=new Ece(n.shape,i.shape,o.shape,h,p),f=[{type:"float32",data:[l]}];return u.runWebGPUProgram(c,d,n.dtype,f)}};function Mce(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:d,dilations:h,dimRoundingMode:p,activation:c,leakyreluAlpha:f}=n,m=N.convertConv2DDataFormat(d),g=N.computeConv2DInfo(a.shape,s.shape,l,h,u,p,!1,m);return W8({x:a,filter:s,convInfo:g,backend:r,bias:i,preluActivationWeights:o,leakyreluAlpha:f,activation:c})}var Fce={kernelName:$s,backendName:"webgpu",kernelFunc:Mce};function $ce(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:d,dimRoundingMode:h,activation:p,leakyreluAlpha:c}=n,f=d;f==null&&(f=[1,1]),w.assert(N.eitherStridesOrDilationsAreOne(l,f),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${f}'`);let m=N.computeConv2DInfo(a.shape,s.shape,l,f,u,h,!0),g=[a,s],y=i!=null,A=o!=null;y&&g.push(i),A&&g.push(o);let x=[{type:"int32",data:[m.padInfo.top,m.padInfo.left]},{type:"int32",data:[m.strideHeight,m.strideWidth]},{type:"int32",data:[m.dilationHeight,m.dilationWidth]},{type:"int32",data:[m.inHeight,m.inWidth]}],b;return m.batchSize===1&&m.inHeight===m.outHeight&&m.inWidth===m.outWidth&&m.strideHeight===1&&m.strideWidth===1&&m.filterHeight===m.filterWidth&&m.inChannels===m.outChannels&&m.dilationHeight===1&&m.dilationWidth===1&&m.filterHeight===3&&m.inChannels%4===0?b=new U8(m,y,p,A):(b=new G8(m,y,p,A),x.push({type:"int32",data:[m.filterHeight]},{type:"int32",data:[m.filterWidth]},{type:"int32",data:[m.outChannels/m.inChannels]})),p==="leakyrelu"&&(x.push({type:"float32",data:[c]}),b.uniforms+=" alpha : f32,"),r.runWebGPUProgram(b,g,"float32",x)}var Pce={kernelName:Ps,backendName:"webgpu",kernelFunc:$ce},_ce=class{constructor(e,t){this.variableNames=["A","indices"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=Ke(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`gathernd_${e}`,this.sliceDim=e,this.uniforms=`sliceDim : i32, strides : ${yr(e)},`}getUserCode(){let e;return this.sliceDim>1?e="uniforms.strides[j]":e="uniforms.strides",`
|
|
${et()}
|
|
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 zce(e){let{inputs:t,backend:r}=e,{params:n,indices:a}=t,s=a.shape,i=s[s.length-1],o=w.sizeFromShape(n.shape),[l,u,d,h]=N.prepareAndValidate(n,a),p=qe({inputs:{x:a},backend:r,attrs:{shape:[u,i]}}),c=qe({inputs:{x:n},backend:r,attrs:{shape:[w.sizeFromShape(n.shape)/d,d]}});if(r.shouldExecuteOnCPU([n,a])||n.dtype==="string"){let A=r.readSync(a.dataId),x=r.bufferSync(n),b=kpe(A,x,n.dtype,u,i,d,h,n.shape,o);return r.makeTensorInfo(l,n.dtype,b.values)}let f=new _ce(i,[u,d]),m=[{type:"int32",data:[i]},{type:"int32",data:h}],g=r.runWebGPUProgram(f,[c,p],c.dtype,m),y=qe({inputs:{x:g},backend:r,attrs:{shape:l}});return r.disposeData(p.dataId),r.disposeData(c.dataId),r.disposeData(g.dataId),y}var Oce={kernelName:Qo,backendName:"webgpu",kernelFunc:zce},Dce=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=Ke(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="gather"}getUserCode(){let e=Lce(this.aShape);return`
|
|
${et()}
|
|
if (index < uniforms.size) {
|
|
let resRC = getCoordsFromIndex(index);
|
|
let indexZ = i32(getIndices(resRC.x, resRC.z));
|
|
let inBounds = select(0.0, 1.0, indexZ >= 0 && indexZ < uniforms.aShape[2]);
|
|
setOutputAtIndex(index, inBounds * getA(${e}));
|
|
}
|
|
}
|
|
`}};function Lce(e){let t=["resRC.x","resRC.y","resRC.z","resRC.w"],r=[];for(let n=0;n<e.length;n++)n===2?r.push("indexZ"):r.push(`${t[n]}`);return r.join()}function X8(e){let{inputs:t,backend:r,attrs:n}=e,{x:a,indices:s}=t,{axis:i,batchDims:o}=n,l=w.parseAxisParam(i,a.shape)[0],u=N.segment_util.collectGatherOpShapeInfo(a,s,l,o),d=w.sizeFromShape(s.shape),h=[],p=qe({inputs:{x:a},backend:r,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),c=qe({inputs:{x:s},backend:r,attrs:{shape:[u.batchSize,d/u.batchSize]}});h.push(p),h.push(c);let f=[u.batchSize,u.outerSize,d/u.batchSize,u.sliceSize];if(r.shouldExecuteOnCPU([a,s])){let A=r.tensorMap.get(c.dataId).values,x=We(c.shape,c.dtype,A),b=r.tensorMap.get(p.dataId).values,v=We(p.shape,p.dtype,b),S=Ipe(v,x,f);return h.forEach(T=>r.disposeData(T.dataId)),r.makeTensorInfo(u.outputShape,S.dtype,S.values)}let m=new Dce(p.shape,f),g=r.runWebGPUProgram(m,[p,c],p.dtype);h.push(g);let y=qe({inputs:{x:g},backend:r,attrs:{shape:u.outputShape}});return h.forEach(A=>r.disposeData(A.dataId)),y}var Bce={kernelName:Jo,backendName:"webgpu",kernelFunc:X8},Wce=Hr({opSnippet:5,cpuKernelImpl:Tpe,dtype:"bool"}),Vce={kernelName:el,backendName:"webgpu",kernelFunc:Wce},Uce=Hr({opSnippet:6,dtype:"bool",cpuKernelImpl:Spe}),Gce={kernelName:hi,backendName:"webgpu",kernelFunc:Uce};function jce(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{alpha:s}=n,i=[{type:"float32",data:[s]}],o=new Vh(a.shape,14);return o.uniforms="alpha : f32,",r.runWebGPUProgram(o,[a],"float32",i)}var Hce={kernelName:fi,backendName:"webgpu",kernelFunc:jce},qce=Hr({opSnippet:7,dtype:"bool",cpuKernelImpl:Cpe}),Kce={kernelName:tl,backendName:"webgpu",kernelFunc:qce},Xce=Hr({opSnippet:8,dtype:"bool",cpuKernelImpl:Npe}),Zce={kernelName:rl,backendName:"webgpu",kernelFunc:Xce},Yce=kr({opType:9,cpuKernelImpl:Epe}),Jce={kernelName:mi,backendName:"webgpu",kernelFunc:Yce},Qce=Hr({opSnippet:9,dtype:"bool"}),efe={kernelName:nl,backendName:"webgpu",kernelFunc:Qce},tfe=kr({opType:10}),rfe={kernelName:Yu,backendName:"webgpu",kernelFunc:tfe};function Z8(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{reductionIndices:s,keepDims:i}=n;return Gh(a,s,i,"max",r)}var nfe={kernelName:gi,backendName:"webgpu",kernelFunc:Z8},afe=Hr({opSnippet:15,cpuKernelImpl:Mpe}),sfe={kernelName:yi,backendName:"webgpu",kernelFunc:afe};function ife(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n,u=1,d=N.computePool2DInfo(a.shape,s,i,u,o,l),h,p=[];if(d.filterHeight===1&&d.filterWidth===1){if(w.arraysEqual(d.inShape,d.outShape))return Pn({inputs:{x:a},backend:r});h=new D8(d),p.push({type:"int32",data:[d.strideHeight,d.strideWidth]})}else h=new O8(d,"max"),p.push({type:"int32",data:[d.strideHeight,d.strideWidth]},{type:"int32",data:[d.padInfo.top,d.padInfo.left]},{type:"int32",data:[d.dilationHeight,d.dilationWidth]},{type:"int32",data:[d.inHeight,d.inWidth]},{type:"int32",data:[d.effectiveFilterHeight,d.effectiveFilterWidth]});return r.runWebGPUProgram(h,[a],a.dtype,p)}var ofe={kernelName:Ai,backendName:"webgpu",kernelFunc:ife};function lfe(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{keepDims:s,axis:i}=n;return Gh(a,i,s,"mean",r)}var ufe={kernelName:xi,backendName:"webgpu",kernelFunc:lfe};function dfe(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n;return Gh(a,s,i,"min",r)}var pfe={kernelName:bi,backendName:"webgpu",kernelFunc:dfe},hfe=Hr({opSnippet:16,cpuKernelImpl:Fpe}),cfe={kernelName:vi,backendName:"webgpu",kernelFunc:hfe},ffe=class{constructor(e,t,r){this.uniforms="",this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t.map((n,a)=>n[0]+e[a]+n[1]),this.dispatchLayout=Ke(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.xShape=e,t.map((n,a)=>{this.uniforms+=` pad${a} : vec2<i32>,`}),this.offset=r==="reflect"?0:1,this.shaderKey=`mirrorPad_${r}`}getUserCode(){let e=this.xShape.length,t=this.xShape.map((l,u)=>`uniforms.pad${u}[0]`).join(","),r=this.xShape.map((l,u)=>`uniforms.pad${u}[0] + uniforms.xShape${e>1?`[${u}]`:""}`).join(","),n=e===1?"start":"start[i]",a=e===1?"end":"end[i]",s=e===1?"outC":"outC[i]",i=yr(e),o=e>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,e):"coords";return`
|
|
${et()}
|
|
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} < ${n}) {
|
|
${s} = ${n} * 2 - ${s} - ${this.offset};
|
|
} else if(${s} >= ${a}) {
|
|
${s} = (${a} - 1) * 2 - ${s} + ${this.offset};
|
|
}
|
|
}
|
|
let coords = outC - start;
|
|
setOutputAtIndex(index, getX(${o}));
|
|
}
|
|
}
|
|
`}},mfe={kernelName:wi,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{x:n}=e,{paddings:a,mode:s}=t,i=r,o=a.map(u=>({type:"int32",data:[u[0],u[1]]})),l=new ffe(n.shape,a,s);return i.runWebGPUProgram(l,[n],n.dtype,o)}};function gfe(e){let{inputs:t,backend:r}=e,{x:n}=t;if(r.shouldExecuteOnCPU([n])){let s=r.tensorMap.get(n.dataId),[i,o]=Ppe(s.values,n.shape,n.dtype);return r.makeTensorInfo(o,n.dtype,i)}let a=new Vh(n.shape,11);return r.runWebGPUProgram(a,[n],n.dtype)}var yfe={kernelName:al,backendName:"webgpu",kernelFunc:gfe};function Afe(e){console.warn("tf.nonMaxSuppression() in webgpu locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:r,attrs:n}=e,{boxes:a,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=n,u=r.readSync(a.dataId),d=r.readSync(s.dataId),{selectedIndices:h}=qn.nonMaxSuppressionV3Impl(u,d,i,o,l);return r.makeTensorInfo([h.length],"int32",new Int32Array(h))}var xfe={kernelName:il,backendName:"webgpu",kernelFunc:Afe};function bfe(e){console.warn("tf.nonMaxSuppression() in webgpu locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:r,attrs:n}=e,{boxes:a,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=n,d=r.readSync(a.dataId),h=r.readSync(s.dataId),p=i,c=o,f=l,m=u,{selectedIndices:g,selectedScores:y}=qn.nonMaxSuppressionV5Impl(d,h,p,c,f,m);return[r.makeTensorInfo([g.length],"int32",new Int32Array(g)),r.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var vfe={kernelName:ol,backendName:"webgpu",kernelFunc:bfe};function Vf(e){let{inputs:t,backend:r}=e,{x:n}=t;if(n.dtype==="complex64"){let a=Uh({inputs:{input:n},backend:r}),s=Vf({inputs:{x:a},backend:r}),i=S0({inputs:{input:n},backend:r}),o=Vf({inputs:{x:i},backend:r}),l=Cd({inputs:{real:s,imag:o},backend:r});return r.disposeData(a.dataId),r.disposeData(s.dataId),r.disposeData(i.dataId),r.disposeData(o.dataId),l}else return Rd({attrs:{shape:n.shape,dtype:n.dtype,value:n.dtype==="string"?"":0},backend:r})}var wfe={kernelName:Sl,backendName:"webgpu",kernelFunc:Vf};function Y8(e){let{inputs:t,backend:r}=e,{x:n}=t;if(n.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(n.dtype==="complex64"){let a=Uh({inputs:{input:n},backend:r}),s=Y8({inputs:{x:a},backend:r}),i=S0({inputs:{input:n},backend:r}),o=Vf({inputs:{x:i},backend:r}),l=Cd({inputs:{real:s,imag:o},backend:r});return r.disposeData(a.dataId),r.disposeData(s.dataId),r.disposeData(i.dataId),r.disposeData(o.dataId),l}else return Rd({attrs:{shape:n.shape,dtype:n.dtype,value:1},backend:r})}var kfe={kernelName:ll,backendName:"webgpu",kernelFunc:Y8};function Ife(e){let{inputs:t,backend:r,attrs:n}=e,{axis:a}=n;if(t.length===1)return s2({inputs:{input:t[0]},backend:r,attrs:{dim:a}});let s=t[0].shape,i=t[0].dtype;t.forEach(d=>{w.assertShapesMatch(s,d.shape,"All tensors passed to stack must have matching shapes"),w.assert(i===d.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(d=>{let h=s2({inputs:{input:d},backend:r,attrs:{dim:a}});return o.push(h),h}),u=B8({inputs:l,backend:r,attrs:{axis:a}});return o.forEach(d=>r.disposeData(d.dataId)),u}var Sfe={kernelName:dl,backendName:"webgpu",kernelFunc:Ife},Tfe=class{constructor(e,t){this.variableNames=["x"],this.uniforms="constantValue : f32,",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t.map((r,n)=>r[0]+e[n]+r[1]),this.dispatchLayout=Ke(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),t.map((r,n)=>{this.uniforms+=` pad${n} : vec2<i32>,`}),this.xShape=e,this.shaderKey="pad"}getUserCode(){let e=this.xShape.length,t=yr(e),r=this.xShape.map((u,d)=>`uniforms.pad${d}[0]`).join(","),n=this.xShape.map((u,d)=>`uniforms.pad${d}[0] + uniforms.xShape${e>1?`[${d}]`:""}`).join(","),a=e>1?`${t}(${r})`:`${r}`,s=e>1?`${t}(${n})`:`${n}`,i=e>1?"any(outC < start)":"outC < start",o=e>1?"any(outC >= end)":"outC >= end",l=e>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,e):"coords";return`
|
|
${et()}
|
|
if (index < uniforms.size) {
|
|
let start = ${a};
|
|
let end = ${s};
|
|
let outC = getCoordsFromIndex(index);
|
|
|
|
if (${i} || ${o}) {
|
|
setOutputAtIndex(index, uniforms.constantValue);
|
|
} else {
|
|
let coords = outC - start;
|
|
setOutputAtIndex(index, getX(${l}));
|
|
}
|
|
}
|
|
}
|
|
`}},J8=e=>{let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{paddings:s,constantValue:i}=n;if(s.every(u=>w.arraysEqual(u,[0,0])))return Pn({inputs:{x:a},backend:r});if(w.sizeFromShape(a.shape)===0){let u=s.map((d,h)=>d[0]+a.shape[h]+d[1]);return Rd({backend:r,attrs:{shape:u,value:i,dtype:a.dtype}})}let o=[{type:"float32",data:[i]}];s.map(u=>o.push({type:"int32",data:[u[0],u[1]]}));let l=new Tfe(a.shape,s);return r.runWebGPUProgram(l,[a],a.dtype,o)},Nfe={kernelName:Ii,backendName:"webgpu",kernelFunc:J8},Cfe=Hr({opSnippet:13}),Efe={kernelName:Si,backendName:"webgpu",kernelFunc:Cfe};function Rfe(e){let{inputs:t,backend:r}=e,{x:n,alpha:a}=t,s=new _8(14,n.shape,a.shape);return r.runWebGPUProgram(s,[n,a],"float32")}var Mfe={kernelName:Ti,backendName:"webgpu",kernelFunc:Rfe};function Ffe(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,keepDims:i}=n;return Gh(a,s,i,"prod",r)}var $fe={kernelName:Ni,backendName:"webgpu",kernelFunc:Ffe},Pfe=e=>{let{backend:t,attrs:r}=e,{start:n,stop:a,step:s,dtype:i}=r,o=Ope(n,a,s,i);return t.makeTensorInfo([o.length],i,o)},_fe={kernelName:ed,backendName:"webgpu",kernelFunc:Pfe},Q8=Hr({opSnippet:3}),zfe={kernelName:ii,backendName:"webgpu",kernelFunc:Q8},Ofe=kr({opType:12}),Dfe={kernelName:Ci,backendName:"webgpu",kernelFunc:Ofe},Lfe=kr({opType:13}),Bfe={kernelName:Ri,backendName:"webgpu",kernelFunc:Lfe},Wfe=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=Ke(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="resizeBilinear"}getUserCode(){return`
|
|
${et()}
|
|
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 Vfe(e){let{inputs:t,backend:r,attrs:n}=e,{images:a}=t,{alignCorners:s,size:i,halfPixelCenters:o}=n,[l,u]=i,d=s&&l>1?1:0,h=s&&u>1?1:0,p=[{type:"float32",data:[d,h]},{type:"float32",data:[o?.5:0]}],c=new Wfe(a.shape,l,u);return r.runWebGPUProgram(c,[a],"float32",p)}var Ufe={kernelName:Ei,backendName:"webgpu",kernelFunc:Vfe},Gfe=class{constructor(e,t,r,n){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=Ke(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.halfPixelCenters=n,this.shaderKey=`resizeNearest_${n}`}getUserCode(){let e;return this.halfPixelCenters?e="max((vec2<f32>(rc) + vec2<f32>(0.5)) * effectiveInputOverOutputRatioRC, vec2<f32>(0.0))":e="vec2<f32>(rc) * effectiveInputOverOutputRatioRC",`
|
|
${et()}
|
|
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 jfe(e){let{inputs:t,backend:r,attrs:n}=e,{images:a}=t,{alignCorners:s,halfPixelCenters:i,size:o}=n,[l,u]=o,d=s&&l>1?1:0,h=s&&u>1?1:0,p=[{type:"float32",data:[d,h]},{type:"float32",data:[s?.5:0]}],c=new Gfe(a.shape,l,u,i);return r.runWebGPUProgram(c,[a],a.dtype,p)}var Hfe={kernelName:rd,backendName:"webgpu",kernelFunc:jfe},qfe=class{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Ke(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`
|
|
${et()}
|
|
|
|
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);
|
|
}
|
|
}
|
|
`}},Kfe={kernelName:Tl,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:r})=>{let{image:n}=e,{radians:a,fillValue:s,center:i}=t,o=r,l=new qfe(n.shape,s),[u,d]=N.getImageCenter(i,n.shape[1],n.shape[2]),h=[{type:"float32",data:[u]},{type:"float32",data:[d]},{type:"float32",data:[Math.sin(a)]},{type:"float32",data:[Math.cos(a)]}];return typeof s=="number"?h.push({type:"float32",data:[Number.parseFloat(s.toFixed(2))]}):h.push({type:"float32",data:s}),o.runWebGPUProgram(l,[n],n.dtype,h)}},Xfe=kr({opType:15,cpuKernelImpl:Dpe}),Zfe={kernelName:Mi,backendName:"webgpu",kernelFunc:Xfe},Yfe=class{constructor(e,t,r,n,a,s,i){this.variableNames=["updates","indices"],this.workGroupSize=[64,1,1],this.atomic=!0,this.outputShape=s,this.type=i,this.dispatchLayout=Ke(e),this.dispatch=ze(this.dispatchLayout,e,this.workGroupSize),this.sliceDimGreaterThanOne=t>1,this.shaderKey=`scatter_${r}_${n}_${this.sliceDimGreaterThanOne}_${i}`;let o=yr(a.length);this.uniforms=`sliceDim : i32, strides: ${o}, size: i32,`,this.updatesRank=n,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",n="",a="",s="";this.updatesRank===1?(n="coords[0]",a="flattenedIndex",s=`
|
|
fn getUpdatesCoordsFromFlatIndex(index : i32) -> i32 {
|
|
return index;
|
|
}
|
|
`):this.updatesRank===2&&(n="coords[0], coords[1]",a="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(${n})`,o=this.type==="int32"?"atomicAdd(&(result[flatIndex]), i32(updateValue));":`
|
|
var assumed = atomicLoad(&(result[flatIndex]));
|
|
var success = 0;
|
|
for (; success == 0;) {
|
|
let new = bitcast<f32>(assumed) + updateValue;
|
|
let newI32 = bitcast<i32>(new);
|
|
let resValue = atomicCompareExchangeWeak(&(result[flatIndex]), assumed, newI32);
|
|
assumed = resValue[0];
|
|
success = resValue[1];
|
|
}
|
|
`;return`
|
|
${s}
|
|
|
|
${et()}
|
|
|
|
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(${a});
|
|
|
|
${o}
|
|
}
|
|
}`}};function Jfe(e){let{inputs:t,backend:r,attrs:n}=e,{indices:a,updates:s}=t,{shape:i}=n,{sliceRank:o,numUpdates:l,sliceSize:u,strides:d,outputSize:h}=N.calculateShapes(s,a,i),p=[h/u,u];if(h===0)return r.makeTensorInfo(i,a.dtype);let c=qe({inputs:{x:a},backend:r,attrs:{shape:[l,o]}}),f=qe({inputs:{x:s},backend:r,attrs:{shape:[l,u]}}),m=f.dtype,g=Rd({backend:r,attrs:{shape:p,value:0,dtype:m}}),y=w.sizeFromShape(f.shape),A=[{type:"int32",data:[o]},{type:"int32",data:d},{type:"int32",data:[y]}],x=new Yfe(f.shape,o,c.shape.length,f.shape.length,d,p,m),b=r.runWebGPUProgram(x,[f,c],m,A,g),v=qe({inputs:{x:b},backend:r,attrs:{shape:i}});return r.disposeData(c.dataId),r.disposeData(f.dataId),r.disposeData(b.dataId),v}var Qfe={kernelName:fl,backendName:"webgpu",kernelFunc:Jfe},eme=class{constructor(e,t,r){this.variableNames=["c","a","b"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=Ke(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"],n=[],a=[];for(let s=0;s<this.outputShape.length;s++)a.push(`${r[s]}`),s<this.cRank&&n.push(`${r[s]}`);e=n.join(),t=a.join()}return`
|
|
${et()}
|
|
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 tme(e){let{inputs:t,backend:r}=e,{condition:n,t:a,e:s}=t,i=new eme(n.shape.length,a.shape,a.shape.length);return r.runWebGPUProgram(i,[n,a,s],Cr(a.dtype,s.dtype))}var rme={kernelName:ml,backendName:"webgpu",kernelFunc:tme},nme=kr({opType:18}),ame={kernelName:$i,backendName:"webgpu",kernelFunc:nme},sme=kr({opType:16}),ime={kernelName:Fi,backendName:"webgpu",kernelFunc:sme},ome=kr({opType:17}),lme={kernelName:yl,backendName:"webgpu",kernelFunc:ome},eT=Hr({opSnippet:2,cpuKernelImpl:Upe,supportsComplex:!0}),ume={kernelName:Di,backendName:"webgpu",kernelFunc:eT};function dme(e){let{inputs:t,backend:r,attrs:n}=e,{logits:a}=t,{dim:s}=n,i=w.parseAxisParam([s],a.shape),o=Z8({inputs:{x:a},backend:r,attrs:{reductionIndices:i,keepDims:!1}}),l=N.expandShapeToKeepDim(o.shape,i),u=qe({inputs:{x:o},backend:r,attrs:{shape:l}}),d=eT({inputs:{a,b:u},backend:r}),h=H8({inputs:{x:d},backend:r}),p=Sb({inputs:{x:h},backend:r,attrs:{axis:i,keepDims:!1}}),c=qe({inputs:{x:p},backend:r,attrs:{shape:l}}),f=Q8({inputs:{a:h,b:c},backend:r});return r.disposeData(o.dataId),r.disposeData(u.dataId),r.disposeData(d.dataId),r.disposeData(h.dataId),r.disposeData(p.dataId),r.disposeData(c.dataId),f}var pme={kernelName:zi,backendName:"webgpu",kernelFunc:dme},hme=e=>{let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockShape:s,paddings:i}=n;w.assert(a.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<a.shape.length;++y)l.push([0,0]);let u=[],d=J8({inputs:{x:a},backend:r,attrs:{paddings:l,constantValue:0}}),h=N.getReshaped(d.shape,s,o,!1),p=N.getPermuted(h.length,s.length,!1),c=N.getReshapedPermuted(d.shape,s,o,!1),f=qe({inputs:{x:d},backend:r,attrs:{shape:h}}),m=Ya({inputs:{x:f},backend:r,attrs:{perm:p}}),g=qe({inputs:{x:m},backend:r,attrs:{shape:c}});return u.push(d),u.push(f),u.push(m),u.forEach(y=>r.disposeData(y.dataId)),g},cme={kernelName:Al,backendName:"webgpu",kernelFunc:hme},fme=class{constructor(e,t,r,n,a,s,i=!0){this.variableNames=["updates","indices","defaultValue"],this.workGroupSize=[64,1,1],this.workPerThread=4,this.size=!0,this.outputShape=s,this.dispatchLayout=Ke(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]);let o=t>1;this.shaderKey=`scatter_${r}_${n}_${o}`;let l=yr(a.length);this.uniforms=`updateSize : i32, sliceDim : i32, strides: ${l},`;let u="";r===1?u="i":r===2&&(u="i, j"),this.indicesSnippet=`getIndices(${u})`;let d="";n===1?d="i":n===2&&(d="i, coords[1]"),this.updatesSnippet=`getUpdates(${d})`,this.strideString=o?"uniforms.strides[j]":"uniforms.strides"}getUserCode(){return`
|
|
${et()}
|
|
|
|
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 mme(e){let{inputs:t,backend:r,attrs:n}=e,{sparseIndices:a,sparseValues:s,defaultValue:i}=t,{outputShape:o}=n,{sliceRank:l,numUpdates:u,strides:d,outputSize:h}=N.calculateShapes(s,a,o),p=!1,c=[{type:"int32",data:[u]},{type:"int32",data:[l]},{type:"int32",data:d}],f=new fme(u,l,a.shape.length,s.shape.length,d,[h,1],p),m=r.runWebGPUProgram(f,[s,a,i],s.dtype,c),g=qe({inputs:{x:m},backend:r,attrs:{shape:o}});return r.disposeData(m.dataId),g}var gme={kernelName:lh,backendName:"webgpu",kernelFunc:mme};function yme(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{numOrSizeSplits:s,axis:i}=n,o=w.parseAxisParam(i,a.shape)[0],l=N.prepareSplitSize(a,s,o),u=a.shape.length,d=new Array(u).fill(0),h=a.shape.slice();return l.map(p=>{let c=[...h];c[o]=p;let f=Ed({inputs:{x:a},backend:r,attrs:{begin:d,size:c}});return d[o]+=p,f})}var Ame={kernelName:xl,backendName:"webgpu",kernelFunc:yme},xme=kr({opType:19}),bme={kernelName:Pi,backendName:"webgpu",kernelFunc:xme},vme={kernelName:od,backendName:"webgpu",kernelFunc:({inputs:e,backend:t})=>{let{x:r}=e,n=t,a=new Vh(r.shape,20);return n.runWebGPUProgram(a,[r],r.dtype)}},wme=Hr({opSnippet:11}),kme={kernelName:Oi,backendName:"webgpu",kernelFunc:wme},Ime=class{constructor(e){this.variableNames=["x"],this.workPerThread=1,this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Ke(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]);let t=yr(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((n,a)=>(r++,this.outputShape.length===1?`coords * uniforms.strides[${a}] + uniforms.begin[${a}]`:`coords[${r-1}] * uniforms.strides[${a}] + uniforms.begin[${a}]`)).join(",")}return`
|
|
${et()}
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
setOutputAtIndex(index, getX(${t}));
|
|
}
|
|
}
|
|
`}};function Sme(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:d,newAxisMask:h,shrinkAxisMask:p}=n,{finalShapeSparse:c,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:A,end:x,strides:b}=zt.sliceInfo(a.shape,s,i,o,l,u,d,h,p),v;if(m)v=qe({inputs:{x:a},backend:r,attrs:{shape:f}});else if(g||y){w.assert(a.shape.length>=1,()=>`Input must have rank at least 1, got: ${a.shape.length}`);let S=zt.computeOutShape(A,x,b),T=Ed({inputs:{x:a},backend:r,attrs:{begin:A,size:S}});v=qe({inputs:{x:T},backend:r,attrs:{shape:f}}),r.disposeData(T.dataId)}else if(r.shouldExecuteOnCPU([a])){let S=r.readSync(a.dataId),T=We(a.shape,a.dtype,S),E=Wpe(c,T,b,A);v=r.makeTensorInfo(f,a.dtype,E.values)}else{let S=new Ime(c),T=[{type:"int32",data:A},{type:"int32",data:b}],E=r.runWebGPUProgram(S,[a],a.dtype,T);v=qe({inputs:{x:E},backend:r,attrs:{shape:f}}),r.disposeData(E.dataId)}return v}var Tme={kernelName:bl,backendName:"webgpu",kernelFunc:Sme};function Nme(e){let{inputs:t,backend:r,attrs:n}=e,{separator:a,nGramWidths:s,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=n,{data:d,dataSplits:h}=t,p=r.readSync(d.dataId),c=r.readSync(h.dataId),[f,m]=Vpe(p,c,a,s,i,o,l,u);return[r.makeTensorInfo([f.length],"string",f),r.makeTensorInfo(h.shape,"int32",m)]}var Cme={kernelName:uh,backendName:"webgpu",kernelFunc:Nme},Eme=kr({opType:21}),Rme={kernelName:Li,backendName:"webgpu",kernelFunc:Eme},Mme=class{constructor(e,t){this.variableNames=["A"],this.workGroupSize=[64,1,1],this.size=!0;let r=new Array(e.length);for(let n=0;n<r.length;n++)r[n]=e[n]*t[n];this.outputShape=r,this.dispatchLayout=Ke(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.rank=this.outputShape.length,this.shaderKey="tile"}getUserCode(){let e=Fme(this.rank,"uniforms.");return`
|
|
${et()}
|
|
if (index < uniforms.size) {
|
|
let resRC = getCoordsFromIndex(index);
|
|
setOutputAtIndex(index, getA(${e}));
|
|
}
|
|
}
|
|
`}};function Fme(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"],n=[];for(let a=0;a<e;a++)n.push(`(${r[a]} % ${t}aShape[${a}])`);return n.join()}function $me(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{reps:s}=n;if(r.shouldExecuteOnCPU([a])||a.dtype==="string"||a.shape.length>=5){let o=r.readSync(a.dataId),l=a.dtype==="string"?o.map(h=>w.decodeString(h)):o,u=We(a.shape,a.dtype,l),d=Gpe(u,s);return r.makeTensorInfo(d.shape,d.dtype,d.values)}let i=new Mme(a.shape,s);return r.runWebGPUProgram(i,[a],a.dtype)}var Pme={kernelName:es,backendName:"webgpu",kernelFunc:$me},_me=class{constructor(e){this.variableNames=["x","indices"],this.workGroupSize=[256,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Ke(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`
|
|
${et()}
|
|
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));
|
|
}
|
|
}
|
|
}
|
|
`}},zme=class{constructor(e){this.variableNames=["x","indices"],this.workGroupSize=[256,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Ke(this.outputShape),this.dispatch=ze(this.dispatchLayout,this.outputShape,this.workGroupSize),this.uniforms="inputSize : i32, firstPass : i32, k : i32,",this.shaderKey="merge"}getUserCode(){return`
|
|
${et()}
|
|
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 du(e,t){t!==null&&e.disposeData(t.dataId)}function hw(e){let t=1;for(;t<e;)t*=2;return t}function Ome(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{k:s,sorted:i}=n,o=a.shape,l=o[o.length-1];if(r.shouldExecuteOnCPU([a])){let b=r.readSync(a.dataId),[v,S]=jpe(b,o,a.dtype,s,i);return[r.makeTensorInfo(v.shape,v.dtype,v.values),r.makeTensorInfo(S.shape,S.dtype,S.values)]}if(s===0)return o[o.length-1]=0,[r.makeTensorInfo(o,a.dtype,[]),r.makeTensorInfo(o,"int32",[])];if(l===1)return[a,Rd({attrs:{shape:o,dtype:"int32",value:0},backend:r})];let u=w.sizeFromShape(o)/l,d=qe({inputs:{x:a},attrs:{shape:[u,l]},backend:r}),h=hw(s),p=hw(l),c=null,f=()=>c===null?[d,d]:[d,c],m=(b,v,S)=>{let T=f(),E=new _me(S),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]}],_=c;c=r.runWebGPUProgram(E,T,"int32",R),du(r,_)};for(let b=1;b<h;b*=2){let v=b*2;for(let S=b;S>=1;S/=2)m(v,S,[u,p])}for(let b=p;b>h;b/=2){let v=f(),S=new zme([u,b/2]),T=[{type:"int32",data:[l]},{type:"int32",data:[c===null?1:0]},{type:"int32",data:[h]}],E=c;c=r.runWebGPUProgram(S,v,"int32",T),du(r,E);let R=h/2,_=R*2;for(let M=R;M>=1;M/=2)m(_,M,c.shape)}let g=c;c=Ed({inputs:{x:c},backend:r,attrs:{begin:0,size:[u,s]}}),du(r,g);let y=X8({inputs:{x:d,indices:c},backend:r,attrs:{axis:1,batchDims:1}});du(r,d);let A=o.slice(0,-1);A.push(s),g=c,c=qe({inputs:{x:c},attrs:{shape:A},backend:r}),du(r,g);let x=y;return y=qe({inputs:{x:y},attrs:{shape:A},backend:r}),du(r,x),[y,c]}var Dme={kernelName:wl,backendName:"webgpu",kernelFunc:Ome},Lme=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=Ke(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;
|
|
}
|
|
|
|
${et()}
|
|
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 Bme(e){let{inputs:t,backend:r,attrs:n}=e,{image:a,transforms:s}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=n,[d,h,p,c]=a.shape,[f,m]=u!=null?u:[h,p],g=[d,f,m,c],y=new Lme(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,[a,s],"float32",b)}var Wme={kernelName:kl,backendName:"webgpu",kernelFunc:Bme};function Vme(e){let{inputs:t,backend:r,attrs:n}=e,{value:a}=t,{axis:s}=n;s<0&&(s+=a.shape.length);let i=a,o=i.shape.length,l=a.shape[s],u=new Array(o-1),d=0;for(let m=0;m<o;m++)m!==s&&(u[d++]=i.shape[m]);let h=[],p=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++){p[s]=m;let g=Ed({inputs:{x:i},backend:r,attrs:{begin:p,size:c}}),y=qe({inputs:{x:g},backend:r,attrs:{shape:u}});f[m]=y,h.push(g)}return h.forEach(m=>r.disposeData(m.dataId)),f}var Ume={kernelName:Il,backendName:"webgpu",kernelFunc:Vme},Gme=[ppe,Kpe,Zpe,Qpe,she,ohe,uhe,phe,ghe,bhe,whe,The,mpe,Rhe,Dhe,Vhe,Ghe,Hhe,Xhe,Yhe,Qhe,rce,ace,uce,pce,cce,fce,mce,yce,xce,vce,Nce,kce,Sce,Rce,Fce,Pce,Oce,Bce,Vce,Gce,fpe,Che,Hce,Kce,Zce,Jce,efe,rfe,nfe,sfe,ofe,ufe,pfe,cfe,mfe,sce,yfe,xfe,vfe,yhe,kfe,Sfe,Nfe,Efe,Mfe,$fe,_fe,Ahe,zfe,Dfe,Bfe,upe,Ufe,Hfe,Kfe,Zfe,Qfe,rme,ame,ime,lme,fhe,Tme,Cme,pme,cme,gme,Ame,bme,vme,kme,ume,oce,Rme,Pme,Dme,Wme,nhe,Ume,wfe];for(let e of Gme)jn(e);var jme=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 n=cw(e,t);if(this.freeBuffers.has(n)||this.freeBuffers.set(n,[]),this.usedBuffers.has(n)||this.usedBuffers.set(n,[]),this.numBytesUsed+=e,this.numUsedBuffers++,this.freeBuffers.get(n).length>0){this.numFreeBuffers--;let s=this.freeBuffers.get(n).shift();return this.usedBuffers.get(n).push(s),s}this.numBytesAllocated+=e;let a=this.device.createBuffer({mappedAtCreation:r,size:e,usage:t});return this.usedBuffers.get(n).push(a),a}releaseBuffer(e,t,r){if(this.freeBuffers.size===0)return;let n=cw(t,r);this.freeBuffers.has(n)||this.freeBuffers.set(n,[]),this.freeBuffers.get(n).push(e),this.numFreeBuffers++,this.numUsedBuffers--;let a=this.usedBuffers.get(n),s=a.indexOf(e);if(s<0)throw new Error("Cannot release a buffer that was never provided by this buffer manager");a.splice(s,1),this.numBytesUsed-=t}releaseUploadBuffer(e,t,r){e.mapAsync(GPUMapMode.WRITE).then(()=>{this.releaseBuffer(e,t,r)},n=>{})}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 cw(e,t){return`${e}_${t}`}var tT=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=Ke(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>"};
|
|
|
|
${et()}
|
|
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[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,n)=>r===this.lastUniformData[n])||(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}),n=e.createPipelineLayout({bindGroupLayouts:[r]});return{bindGroupLayout:r,pipelineLayout:n}}},Hme=class extends tT{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}),n=e.createPipelineLayout({bindGroupLayouts:[r]});return{bindGroupLayout:r,pipelineLayout:n}}},qme=Y().getNumber("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD"),fw=(e,t)=>{let r=e.limits.maxComputeWorkgroupsPerDimension,n=t.dispatchLayout,a=t.dispatch;if(a.every(i=>i<=r))return a;w.assert(a[0]>r&&n.y===void 0&&n.z===void 0,()=>"Dispatch size exceeds WebGPU limits in Y or Z dimension.");let s=Math.ceil(Math.sqrt(a[0]));return s>r?(s=Math.ceil(Math.cbrt(a[0])),w.assert(s<=r,()=>"Total dispatch size exceeds WebGPU maximum."),[s,s,s]):[s,s,1]},rT=class extends $u{constructor(e,t=!1){if(super(),this.commandQueueOwnedIds=new WeakSet,this.tensorDisposalQueue=[],this.uniformDisposalQueue=[],this.stagingDisposalQueue=[],this.disposed=!1,this.uploadWaitMs=0,this.downloadWaitMs=0,this.dispatchNumberInEncoder=0,!wb())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 jme(this.device),this.tensorMap=new qp(this,nr()),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 rT.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:n}=this.tensorMap.get(e);n!=null&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.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 n={id:this.nextDataId()},a=w.sizeFromShape(t)*t2(r);return this.tensorMap.set(n,{dtype:r,values:e,bufferInfo:{byteSize:a,usage:this.defaultGpuBufferUsage()},refCount:1}),n}move(e,t,r,n,a){if(n==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let s=w.sizeFromShape(r)*t2(n);this.tensorMap.set(e,{dtype:n,values:t,bufferInfo:{byteSize:s,usage:this.defaultGpuBufferUsage()},refCount:a})}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 tT),this.fromPixelProgram;case"import":return this.fromPixelImportProgram||(this.fromPixelImportProgram=new Hme),this.fromPixelImportProgram;default:w.assert(!1,()=>"Unsupported fromPixels shape");return}}ensureCommandEncoderReady(){this.currentCommandEncoder||(this.currentCommandEncoder=this.device.createCommandEncoder())}ensureComputePassEnded(){this.currentComputePass&&(this.currentComputePass.end(),this.currentComputePass=null)}getComputePass(){return this.currentComputePass||(this.currentComputePass=this.currentCommandEncoder.beginComputePass()),this.currentComputePass}async getBufferData(e){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 n;if(t.dtype==="complex64"){let a=await Promise.all([this.read(t.complexTensorInfos.real.dataId),this.read(t.complexTensorInfos.imag.dataId)]),s=a[0],i=a[1];n=N.mergeRealAndImagArrays(s,i)}else{let a=await this.getBufferData(t);n=F8(a,t.dtype)}return this.convertAndCacheOnCPU(e,n),n}bufferSync(e){let t=this.readSync(e.dataId),r=t;if(e.dtype==="string")try{r=t.map(n=>w.decodeString(n))}catch(n){throw new Error("Failed to decode encoded string bytes into utf-8")}return We(e.shape,e.dtype,r)}async time(e){let t=this.activeTimers,r=[],n=!1;this.programTimersStack==null?(this.programTimersStack=r,n=!0):this.activeTimers.push(r),this.activeTimers=r,e();let a=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,n&&(this.programTimersStack=null);let i={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null},o=await Promise.all(a);return i.kernelMs=w.sum(o),i.getExtraProfileInfo=()=>o.map((l,u)=>({name:s[u],ms:l})).map(l=>`${l.name}: ${l.ms}`).join(", "),this.uploadWaitMs=0,this.downloadWaitMs=0,i}getAndSavePipeline(e,t){return e in this.pipelineCache||(this.pipelineCache[e]=t()),this.pipelineCache[e]}makeTensorInfo(e,t,r){let n;if(t==="string"&&r!=null&&r.length>0&&w.isString(r[0])){let a=r.map(s=>w.encodeString(s));n=this.write(a,e,t)}else n=this.write(r,e,t);return{dataId:n,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),n=r.getMappedRange();t.dtype==="int32"||t.dtype==="bool"?new Int32Array(n).set(t.values):new Float32Array(n).set(t.values),r.unmap(),this.ensureCommandEncoderReady(),this.ensureComputePassEnded(),this.currentCommandEncoder.copyBufferToBuffer(r,0,t.bufferInfo.buffer,0,t.bufferInfo.byteSize);let a={byteSize:t.bufferInfo.byteSize,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC,buffer:r};this.stagingDisposalQueue.push(a)}}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 n=new ArrayBuffer(t);e.forEach((s,i)=>{let o=r[i];s.type==="int32"?new Int32Array(n,o,s.data.length).set(s.data):s.type==="uint32"?new Uint32Array(n,o,s.data.length).set(s.data):new Float32Array(n,o,s.data.length).set(s.data)});let a=this.acquireBuffer(t,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);return this.queue.writeBuffer(a,0,n,0,t),{offset:0,size:t,buffer:a}}createLayout(e){let t=[];t.push({binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}});for(let a=0;a<e;a++)t.push({binding:a+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}),n=this.device.createPipelineLayout({bindGroupLayouts:[r]});return{bindGroupLayout:r,pipelineLayout:n}}getCachedOrCreateLayout(e){return e in this.layoutCache||(this.layoutCache[e]=this.createLayout(e)),this.layoutCache[e]}runWebGPUProgram(e,t,r,n,a){if(!a){if(a=this.makeTensorInfo(e.outputShape,r),w.sizeFromShape(a.shape)===0){let T=this.tensorMap.get(a.dataId);return T.values=w.getTypedArrayFromDType(a.dtype,0),a}this.uploadToGPU(a.dataId)}e.dispatch=fw(this.device,e);let s=[{type:"float32",data:[NaN]}],i=t.concat(a).map(T=>T.shape),o="int32";i.map(T=>{s.push({type:o,data:T})});let l=w.computeStrides(a.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]})}n&&(s=[...s,...n]);let u=this.makeUniforms(s),d=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]}}),h=d.map(T=>T.dtype).concat(a.dtype),p=d.map(T=>N.getBroadcastDims(T.shape,a.shape)),c=d.map(T=>w.arraysEqual(T.shape,a.shape)).join("_"),f=p.map(T=>T.join("_")).join(";"),m=K8(e,i,h,f,c),{bindGroupLayout:g,pipelineLayout:y}=this.getCachedOrCreateLayout(e.variableNames.length),A=this.getAndSavePipeline(m,()=>q8(this.device,e,y,d,a)),x=this.activeTimers!=null,b=Tce(this.device,g,t.map(T=>this.tensorToBinding(T)),this.tensorToBinding(a),u);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(a.dataId);let S={byteSize:u.size,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM,buffer:u.buffer};return this.uniformDisposalQueue.push(S),Y().get("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE")<=this.dispatchNumberInEncoder&&this.submitQueue(),x&&this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(this.querySet)}),a}runFromPixelsProgram(e,t,r,n,a){e.dispatch=fw(this.device,e);let s=this.device.createBindGroup({layout:r.bindGroupLayout,entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:n},{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(a),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 n=new BigUint64Array(r.getMappedRange()),a=Number(n[1]-n[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),a/1e6}shouldExecuteOnCPU(e,t=qme){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)}},Tb=rT;Tb.nextDataId=0;var nT={};Le(nT,{WebGPUBackend:()=>Tb,webgpu_util:()=>R8});wb()&&Cl("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=t.limits,n={},a=t.features.has("timestamp-query");n.requiredLimits={maxComputeWorkgroupStorageSize:r.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:r.maxComputeWorkgroupsPerDimension},a?n.requiredFeatures=["timestamp-query"]:console.warn("This device doesn't support timestamp-query extension. Start Chrome browser with flag --disable-dawn-features=disallow_unsafe_apis then try again. Or zero will shown for the kernel time when profiling mode isenabled. Using performance.now is not workable for webgpu sinceit doesn't support synchronously to read data from GPU.");let s=await t.requestDevice(n);return new Tb(s,a)},3);var Vt=(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))(Vt||{}),T0=(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))(T0||{}),aT;function Kme(e){aT=e.wasm.cwrap(Fs,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function Xme(e){let{inputs:t,backend:r,attrs:n}=e,{a,b:s,bias:i,preluActivationWeights:o}=t;if(a.dtype!=="float32"||s.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:l,transposeB:u,activation:d,leakyreluAlpha:h}=n,p=r.dataIdMap.get(a.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=T0[d];if(g==null)throw new Error(`${d} activation not yet supported for FusedConv2D in the wasm backend.`);let y=l?a.shape[2]:a.shape[1],A=u?s.shape[1]:s.shape[2],x=Nl.assertAndGetBroadcastShape(a.shape.slice(0,-2),s.shape.slice(0,-2)),b=r.makeOutput([...x,y,A],a.dtype),v=r.dataIdMap.get(b.dataId).id,S=new Uint8Array(new Int32Array(a.shape).buffer),T=new Uint8Array(new Int32Array(s.shape).buffer);return aT(p,S,a.shape.length,c,T,s.shape.length,l,u,g,f,m,h||0,v),b}var Zme={kernelName:Fs,backendName:"wasm",setupFunc:Kme,kernelFunc:Xme};function Ir(e,t){let r;function n(s){r=s.wasm.cwrap(e,null,["number","number","number"])}function a(s){let{backend:i,inputs:{x:o}}=s,l=i.dataIdMap.get(o.dataId).id,u=i.makeOutput(o.shape,t||o.dtype),d=i.dataIdMap.get(u.dataId).id;return w.sizeFromShape(u.shape)===0||r(l,Vt[o.dtype],d),u}return{kernelName:e,backendName:"wasm",setupFunc:n,kernelFunc:a}}var Yme=Ir(Vo);function qr(e,t,r){let n;function a(i){n=i.wasm.cwrap(e,null,["number","array","number","number","array","number","number","number"])}function s(i){let{backend:o,inputs:l}=i,{a:u,b:d}=l,h=o.dataIdMap.get(u.dataId).id,p=o.dataIdMap.get(d.dataId).id,c=r!=null?r:u.dtype,f=N.assertAndGetBroadcastShape(u.shape,d.shape),m=o.makeOutput(f,c);if(w.sizeFromShape(f)===0)return m;let g=new Uint8Array(new Int32Array(u.shape).buffer),y=new Uint8Array(new Int32Array(d.shape).buffer),A=o.dataIdMap.get(m.dataId).id;return n(h,g,u.shape.length,p,y,d.shape.length,Vt[u.dtype],A),m}return{kernelName:e,backendName:"wasm",setupFunc:a,kernelFunc:s}}var Jme=!0,Qme=qr(Ja,Jme),sT;function e0e(e){sT=e.wasm.cwrap(Ks,null,["array","number","number","number"])}function t0e(e){let{inputs:t,backend:r}=e,n=r.makeOutput(t[0].shape,t[0].dtype);if(w.sizeFromShape(n.shape)===0)return n;let a=t.map(o=>r.dataIdMap.get(o.dataId).id),s=new Uint8Array(new Int32Array(a).buffer),i=r.dataIdMap.get(n.dataId).id;return sT(s,a.length,Vt[n.dtype],i),n}var r0e={kernelName:Ks,backendName:"wasm",setupFunc:e0e,kernelFunc:t0e};function N0(e){let{inputs:{x:t},backend:r}=e,n=r.makeOutput(t.shape,t.dtype),a=r.typedArrayFromHeap(t);return r.typedArrayFromHeap(n).set(a),n}var n0e={kernelName:ci,backendName:"wasm",kernelFunc:N0},iT;function a0e(e){iT=e.wasm.cwrap(Bi,null,["number","array","number","number","number","array","number"])}function Hs(e){let{inputs:t,backend:r,attrs:n}=e,[a,s]=i0e(t.x.shape,n.perm),i=!0;for(let f=0;f<s.length;f++)s[f]!==f&&(i=!1);let o=s0e(t.x.shape,n.perm),l={dataId:t.x.dataId,shape:a,dtype:t.x.dtype};if(i){let f=N0({inputs:t,backend:r});return f.shape=o,f}let u=r.makeOutput(o,l.dtype),d=r.dataIdMap.get(l.dataId).id,h=r.dataIdMap.get(u.dataId).id,p=new Uint8Array(new Int32Array(s).buffer),c=new Uint8Array(new Int32Array(l.shape).buffer);return iT(d,c,l.shape.length,Vt[l.dtype],h,p,s.length),u}function s0e(e,t){let r=new Array(e.length);for(let n=0;n<r.length;n++)r[n]=e[t[n]];return r}function i0e(e,t){let r=[],n=[];for(let a=0;a<e.length;++a)e[a]!==1&&r.push(e[a]),e[t[a]]!==1&&n.push(t[a]);for(let a=0;a<n.length;++a){let s=-1;for(let i=0;i<n.length;++i)n[i]>=a&&(s===-1||n[s]>n[i])&&(s=i);n[s]=a}return[r,n]}var o0e={kernelName:Bi,backendName:"wasm",kernelFunc:Hs,setupFunc:a0e};function qi(e,t,r){let n=e.shape,a=e.shape.length,s=w.parseAxisParam(t,n),i=s,o=N.getAxesPermutation(i,a),l=null,u=!1;if(o!=null){let d=new Array(a);for(let p=0;p<d.length;p++)d[p]=n[o[p]];i=N.getInnerMostAxes(i.length,a),l=Hs({inputs:{x:e},attrs:{perm:o},backend:r});let h=r.dataIdMap.get(e.dataId).id;r.dataIdMap.get(l.dataId).id!==h&&(u=!0)}return{transposed:l,originalAxes:s,axes:i,inputWasTransposed:u}}var oT;function l0e(e){oT=e.wasm.cwrap(Ou,null,["number, number, number"])}function u0e(e){let{backend:t,inputs:r,attrs:n}=e,{axis:a,keepDims:s}=n,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=i,{transposed:u,axes:d,originalAxes:h,inputWasTransposed:p}=qi(i,a,t);if(p){let A=t.dataIdMap.get(u.dataId).id;l=u,o=A}let c=l.shape.length;N.assertAxesAreInnerMostDims("all",d,c);let[f,m]=N.computeOutAndReduceShapes(l.shape,d),g=w.sizeFromShape(m),y=t.makeOutput(f,i.dtype);if(w.sizeFromShape(l.shape)!==0){let A=t.dataIdMap.get(y.dataId).id;oT(o,g,A)}if(p&&t.disposeData(u.dataId),s){let A=N.expandShapeToKeepDim(y.shape,h);y.shape=A}return y}var d0e={kernelName:Ou,backendName:"wasm",setupFunc:l0e,kernelFunc:u0e},lT;function p0e(e){lT=e.wasm.cwrap(Du,null,["number, number, number"])}function h0e(e){let{backend:t,inputs:r,attrs:n}=e,{axis:a,keepDims:s}=n,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=i,{transposed:u,axes:d,originalAxes:h,inputWasTransposed:p}=qi(i,a,t);if(p){let A=t.dataIdMap.get(u.dataId).id;l=u,o=A}let c=l.shape.length;N.assertAxesAreInnerMostDims("any",d,c);let[f,m]=N.computeOutAndReduceShapes(l.shape,d),g=w.sizeFromShape(m),y=t.makeOutput(f,i.dtype);if(w.sizeFromShape(l.shape)!==0){let A=t.dataIdMap.get(y.dataId).id;lT(o,g,A)}if(p&&t.disposeData(u.dataId),s){let A=N.expandShapeToKeepDim(y.shape,h);y.shape=A}return y}var c0e={kernelName:Du,backendName:"wasm",setupFunc:p0e,kernelFunc:h0e},uT;function f0e(e){uT=e.wasm.cwrap(Xs,null,["number","number","number","number","number"])}function m0e(e){let{backend:t,inputs:r,attrs:n}=e,{axis:a}=n,{x:s}=r,i=t.dataIdMap.get(s.dataId).id,o=i,l=s,{transposed:u,axes:d,inputWasTransposed:h}=qi(s,a,t);if(h){let y=t.dataIdMap.get(u.dataId).id;y!==i&&(l=u,o=y)}let p=l.shape.slice(0,-1),c=t.makeOutput(p,"int32"),f=t.dataIdMap.get(c.dataId).id,m=w.sizeFromShape(c.shape),g=l.shape[d[0]];return uT(o,Vt[l.dtype],m,g,f),h&&t.disposeData(u.dataId),c}var g0e={kernelName:Xs,backendName:"wasm",kernelFunc:m0e,setupFunc:f0e},dT;function y0e(e){dT=e.wasm.cwrap(Zs,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function A0e(e){let{inputs:t,attrs:r,backend:n}=e,a=t.x,s=n.dataIdMap.get(a.dataId).id,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=r,d=N.computePool2DInfo(a.shape,i,o,1,l,u),h=d.filterHeight,p=d.filterWidth,c=d.padInfo.top,f=d.padInfo.right,m=d.padInfo.bottom,g=d.padInfo.left,y=d.strideHeight,A=d.strideWidth,x=d.inChannels;if(d.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${d.dataFormat}'. Please use 'channelsLast'.`);if(d.dilationWidth!==1||d.dilationHeight!==1)throw new Error(`was backend only supports average pooling with dilation = [1, 1], got [${d.dilationHeight}, ${d.dilationWidth}].`);let b=n.makeOutput(d.outShape,"float32"),v=n.dataIdMap.get(b.dataId).id;return dT(s,a.shape[0],a.shape[1],a.shape[2],h,p,c,f,m,g,y,A,x,v),b}var x0e={kernelName:Zs,backendName:"wasm",setupFunc:y0e,kernelFunc:A0e};function tn(e){let{inputs:t,attrs:r}=e,{x:n}=t,{shape:a}=r,s=w.sizeFromShape(n.shape),i=w.inferFromImplicitShape(a,s);return w.assert(s===w.sizeFromShape(i),()=>`new shape: ${i}, old shape: ${n.shape}. New shape and old shape must have the same number of elements.`),e.backend.incRef(n.dataId),{dataId:n.dataId,shape:i,dtype:n.dtype}}var b0e={kernelName:pl,backendName:"wasm",kernelFunc:tn},pT;function v0e(e){pT=e.wasm.cwrap(Ys,null,["number","array","number","number","array","number","number","number","number"])}function w0e(e){let{inputs:t,backend:r,attrs:n}=e,{a,b:s}=t,{transposeA:i,transposeB:o}=n;if(a.dtype!=="float32"||s.dtype!=="float32")throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");let l=a.shape.length,u=s.shape.length,d=i?a.shape[l-2]:a.shape[l-1],h=o?s.shape[u-1]:s.shape[u-2],p=i?a.shape[l-1]:a.shape[l-2],c=o?s.shape[u-2]:s.shape[u-1],f=a.shape.slice(0,-2),m=s.shape.slice(0,-2),g=w.sizeFromShape(f),y=w.sizeFromShape(m),A=Nl.assertAndGetBroadcastShape(a.shape.slice(0,-2),s.shape.slice(0,-2)).concat([p,c]);w.assert(d===h,()=>`Error in matMul: inner shapes (${d}) and (${h}) of Tensors with shapes ${a.shape} and ${s.shape} and transposeA=${i} and transposeB=${o} must match.`);let x=i?[g,d,p]:[g,p,d],b=o?[y,c,h]:[y,h,c],v=tn({inputs:{x:a},backend:r,attrs:{shape:x}}),S=tn({inputs:{x:s},backend:r,attrs:{shape:b}}),T=r.dataIdMap.get(v.dataId).id,E=r.dataIdMap.get(S.dataId).id,R=i?v.shape[2]:v.shape[1],_=o?S.shape[1]:S.shape[2],M=Math.max(g,y),I=r.makeOutput([M,R,_],v.dtype),z=r.dataIdMap.get(I.dataId).id,O=new Uint8Array(new Int32Array(v.shape).buffer),j=new Uint8Array(new Int32Array(S.shape).buffer);return pT(T,O,v.shape.length,E,j,S.shape.length,i,o,z),r.disposeData(v.dataId),r.disposeData(S.dataId),I.shape=A,I}var k0e={kernelName:Ys,backendName:"wasm",setupFunc:v0e,kernelFunc:w0e};function Lo(e){let{inputs:{x:t},attrs:{begin:r,size:n},backend:a}=e,[s,i]=zt.parseSliceParams(t,r,n),o=zt.isSliceContinous(t.shape,s,i),l=a.readSync(t.dataId),u=a.makeOutput(i,t.dtype),d=w.computeStrides(t.shape),h=a.dataIdMap.get(u.dataId);if(o){let f=zt.computeFlatOffset(s,d);return t.dtype==="string"?h.stringBytes=l.slice(f,f+w.sizeFromShape(i)):a.typedArrayFromHeap(u).set(l.subarray(f,f+w.sizeFromShape(i))),u}if(t.dtype==="string"){let f=Of(l,s,i,t.shape,t.dtype);return h.stringBytes=f,u}let p=a.typedArrayFromHeap(u),c=t.shape.length;if(c===2)I0e(l,d[0],p,s,i);else if(c===3)S0e(l,d[0],d[1],p,s,i);else if(c===4)T0e(l,d[0],d[1],d[2],p,s,i);else{let f=Of(l,s,i,t.shape,t.dtype);p.set(f)}return u}function I0e(e,t,r,n,a){let s=0,i=n[0],o=n[1],l=i+a[0];for(let u=i;u<l;u++){let d=u*t+o;r.set(e.subarray(d,d+a[1]),s),s+=a[1]}}function S0e(e,t,r,n,a,s){let i=0,o=a[0],l=a[1],u=a[2],d=o+s[0],h=l+s[1];for(let p=o;p<d;p++)for(let c=l;c<h;c++){let f=p*t+c*r+u;n.set(e.subarray(f,f+s[2]),i),i+=s[2]}}function T0e(e,t,r,n,a,s,i){let o=0,l=s[0],u=s[1],d=s[2],h=l+i[0],p=u+i[1],c=d+i[2],f=s[3];for(let m=l;m<h;m++)for(let g=u;g<p;g++)for(let y=d;y<c;y++){let A=m*t+g*r+y*n+f;a.set(e.subarray(A,A+i[3]),o),o+=i[3]}}var N0e={kernelName:gl,backendName:"wasm",kernelFunc:Lo};function C0e(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockShape:s,crops:i}=n,o=s.reduce((y,A)=>y*A),l=N.getReshaped(a.shape,s,o),u=N.getPermuted(l.length,s.length),d=N.getReshapedPermuted(a.shape,s,o),h=N.getSliceBeginCoords(i,s.length),p=N.getSliceSize(d,i,s.length),c=tn({inputs:{x:a},backend:r,attrs:{shape:l}}),f=Hs({inputs:{x:c},backend:r,attrs:{perm:u}}),m=tn({inputs:{x:f},backend:r,attrs:{shape:d}}),g=Lo({inputs:{x:m},backend:r,attrs:{begin:h,size:p}});return r.disposeData(c.dataId),r.disposeData(f.dataId),r.disposeData(c.dataId),g}var E0e={kernelName:Uo,backendName:"wasm",kernelFunc:C0e};function jh(e){let{inputs:{x:t},attrs:{dtype:r},backend:n}=e,a=n.makeOutput(t.shape,r),s=n.typedArrayFromHeap(t);return n.typedArrayFromHeap(a).set(s),a}var R0e={kernelName:Js,backendName:"wasm",kernelFunc:jh},M0e=Ir(Qs),hT;function F0e(e){hT=e.wasm.cwrap(Qa,null,["number","number","number","number"])}function $0e(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{clipValueMin:s,clipValueMax:i}=n,o=r.dataIdMap.get(a.dataId).id,l=r.makeOutput(a.shape,a.dtype),u=r.dataIdMap.get(l.dataId).id;return hT(o,s,i,u),l}var P0e={kernelName:Qa,backendName:"wasm",setupFunc:F0e,kernelFunc:$0e};function cT(e){let{inputs:t,backend:r}=e,n=w.parseAxisParam(e.attrs.axis,t[0].shape)[0],a=N.computeOutShape(t.map(c=>c.shape),n),s=t.filter(c=>w.sizeFromShape(c.shape)>0);if(s.length===1)return N0({inputs:{x:s[0]},backend:r});let i=r.makeOutput(a,t[0].dtype);if(w.sizeFromShape(a)===0)return i;let o=s.map(c=>c.shape);if(N.assertParamsConsistent(o,n),s[0].dtype==="string"){let c=s.map(x=>{let b=w.sizeFromShape(x.shape.slice(n));return tn({inputs:{x},backend:r,attrs:{shape:[-1,b]}})}),f=c.map(x=>({vals:r.readSync(x.dataId),shape:x.shape}));a=N.computeOutShape(c.map(x=>x.shape),1);let m=c[0].shape[0]===1,g=Zx(f,a,t[0].dtype,m),y=N.computeOutShape(s.map(x=>x.shape),n);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,n)),u=0,d=s.map(c=>{let f=w.sizeFromShape(c.shape.slice(n));return u+=f,f}),h=s.map(c=>r.typedArrayFromHeap(c)),p=r.typedArrayFromHeap(i);for(let c=0;c<l;c++){let f=c*u;for(let m=0;m<h.length;m++){let g=d[m],y=c*g,A=h[m].subarray(y,y+g);p.set(A,f),f+=g}}return i}var _0e={kernelName:Go,backendName:"wasm",kernelFunc:cT},fT;function z0e(e){fT=e.wasm.cwrap(ei,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function O0e(e){let{inputs:t,attrs:r,backend:n}=e,{x:a,filter:s}=t,i=n.dataIdMap.get(a.dataId).id,o=n.dataIdMap.get(s.dataId).id,{strides:l,dilations:u,pad:d,dimRoundingMode:h,dataFormat:p}=r,c=N.convertConv2DDataFormat(p),f=N.computeConv2DInfo(a.shape,s.shape,l,u,d,h,!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,S=f.dilationWidth,T=f.strideHeight,E=f.strideWidth,R=f.inChannels,_=f.outChannels,M=f.padInfo.type==="SAME"?1:0;if(f.dataFormat!=="channelsLast")throw new Error(`wasm backend Conv2D does not support dataFormat:'${f.dataFormat}'. Please use 'channelsLast'.`);let I=n.makeOutput(f.outShape,"float32"),z=n.dataIdMap.get(I.dataId).id;return fT(i,a.shape[0],a.shape[1],a.shape[2],o,m,g,y,A,x,b,M,v,S,T,E,R,_,z),I}var D0e={kernelName:ei,backendName:"wasm",setupFunc:z0e,kernelFunc:O0e},mT;function L0e(e){mT=e.wasm.cwrap(ti,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 B0e(e){let{backend:t,inputs:r,attrs:n}=e,{dy:a,filter:s}=r,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,inputShape:d}=n,h=1,p=N.convertConv2DDataFormat(l),c=N.computeConv2DInfo(d,s.shape,i,h,o,u,!1,p),{batchSize:f,filterHeight:m,filterWidth:g,inChannels:y,inHeight:A,inWidth:x,outChannels:b,outHeight:v,outWidth:S,strideHeight:T,strideWidth:E}=c,R=m-1-c.padInfo.top,_=g-1-c.padInfo.left,M=c.dataFormat==="channelsLast",I=w.computeStrides(c.inShape),z=w.computeStrides(a.shape),[O,j,X]=w.computeStrides(s.shape),D=I[0],Q=M?I[1]:I[2],V=M?I[2]:1,ee=M?1:I[1],J=z[0],ie=M?z[1]:z[2],Z=M?z[2]:1,ae=M?1:z[1],de=t.makeOutput(c.inShape,"float32"),Ae=t.dataIdMap.get(de.dataId).id,be=t.dataIdMap.get(a.dataId).id,Ee=t.dataIdMap.get(s.dataId).id;return mT(be,Ee,f,m,g,A,x,y,v,S,b,T,E,R,_,O,j,X,D,Q,V,ee,J,ie,Z,ae,Ae),de}var W0e={kernelName:ti,backendName:"wasm",setupFunc:L0e,kernelFunc:B0e},V0e=Ir(ri),U0e=Ir(ni),gT=(e=>(e[e.bilinear=0]="bilinear",e[e.nearest=1]="nearest",e))(gT||{}),yT;function G0e(e){yT=e.wasm.cwrap(Ho,null,["number","number","number","number","array","number","number","number","number","number"])}function j0e(e){let{backend:t,inputs:r,attrs:n}=e,{method:a,extrapolationValue:s,cropSize:i}=n,{image:o,boxes:l,boxInd:u}=r,d=l.shape[0],[h,p]=i,c=[d,h,p,o.shape[3]],f=t.dataIdMap.get(o.dataId),m;o.dtype!=="float32"&&(m=jh({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(u.dataId).id,x=t.makeOutput(c,"float32"),b=t.dataIdMap.get(x.dataId).id,v=new Uint8Array(new Int32Array(o.shape).buffer);return yT(g,y,A,d,v,h,p,gT[a],s,b),m!=null&&t.disposeData(m.dataId),x}var H0e={kernelName:Ho,backendName:"wasm",setupFunc:G0e,kernelFunc:j0e},AT;function q0e(e){AT=e.wasm.cwrap(jo,null,["number","number","number","number","number","number"])}function K0e(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,exclusive:i,reverse:o}=n,l=a.shape.length;w.assert(a.dtype==="float32"||a.dtype==="int32",()=>`cumprod does not support ${a.dtype} tensors in the WASM backend`);let u=N.getAxesPermutation([s],l),d=a;u!==null&&(d=Hs({inputs:{x:a},attrs:{perm:u},backend:r}));let h=N.getInnerMostAxes(1,l)[0];N.assertAxesAreInnerMostDims("cumprod",[h],l);let p=r.makeOutput(d.shape,d.dtype),c=d.shape[h],f=r.dataIdMap.get(d.dataId).id,m=r.dataIdMap.get(p.dataId).id;AT(f,i?1:0,o?1:0,c,m,Vt[a.dtype]);let g=p;if(u!==null){let y=N.getUndoAxesPermutation(u);g=Hs({inputs:{x:p},attrs:{perm:y},backend:r}),r.disposeData(d.dataId),r.disposeData(p.dataId)}return g}var X0e={kernelName:jo,backendName:"wasm",setupFunc:q0e,kernelFunc:K0e},xT;function Z0e(e){xT=e.wasm.cwrap(ai,null,["number","number","number","number","number","number"])}function Y0e(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{axis:s,exclusive:i,reverse:o}=n,l=a.shape.length;w.assert(a.dtype==="float32"||a.dtype==="int32",()=>`cumsum does not support ${a.dtype} tensors in the WASM backend`);let u=N.getAxesPermutation([s],l),d=a;u!==null&&(d=Hs({inputs:{x:a},attrs:{perm:u},backend:r}));let h=N.getInnerMostAxes(1,l)[0];N.assertAxesAreInnerMostDims("cumsum",[h],l);let p=r.makeOutput(d.shape,d.dtype),c=d.shape[h],f=r.dataIdMap.get(d.dataId).id,m=r.dataIdMap.get(p.dataId).id;xT(f,i?1:0,o?1:0,c,m,Vt[a.dtype]);let g=p;if(u!==null){let y=N.getUndoAxesPermutation(u);g=Hs({inputs:{x:p},attrs:{perm:y},backend:r}),r.disposeData(d.dataId),r.disposeData(p.dataId)}return g}var J0e={kernelName:ai,backendName:"wasm",setupFunc:Z0e,kernelFunc:Y0e},bT;function Q0e(e){bT=e.wasm.cwrap(qo,null,["number","number","number","array","number","array","array","number","number"])}function ege(e){let{backend:t,inputs:r,attrs:n}=e,{x:a}=r,{blockSize:s,dataFormat:i}=n,o=a.shape[0],l=i==="NHWC"?a.shape[1]:a.shape[2],u=i==="NHWC"?a.shape[2]:a.shape[3],d=i==="NHWC"?a.shape[3]:a.shape[1],h=l*s,p=u*s,c=d/(s*s),f=i==="NHWC"?[o,h,p,c]:[o,c,h,p],m=t.makeOutput(f,"float32"),g=t.dataIdMap.get(a.dataId).id,y=new Uint8Array(new Int32Array(w.computeStrides(a.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 bT(g,s,i==="NHWC"?1:0,y,a.shape.length-1,A,x,f.length,b),m}var tge={kernelName:qo,backendName:"wasm",setupFunc:Q0e,kernelFunc:ege},vT;function rge(e){vT=e.wasm.cwrap(si,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function nge(e){let{inputs:t,attrs:r,backend:n}=e,{x:a,filter:s}=t,i=n.dataIdMap.get(a.dataId).id,o=n.dataIdMap.get(s.dataId).id,{strides:l,dilations:u,pad:d,dimRoundingMode:h}=r,p=u==null?[1,1]:u,c=N.computeConv2DInfo(a.shape,s.shape,l,p,d,h,!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,S=c.strideHeight,T=c.strideWidth,E=c.inChannels,R=c.outChannels,_=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=n.makeOutput(c.outShape,"float32"),I=n.dataIdMap.get(M.dataId).id;return vT(i,a.shape[0],a.shape[1],a.shape[2],o,f,m,g,y,A,x,_,b,v,S,T,E,R,I),M}var age={kernelName:si,backendName:"wasm",setupFunc:rge,kernelFunc:nge},sge=Ir(oi),ige=!1,oge=qr(Ko,ige,"bool"),lge=Ir(li,"float32");function i2(e){let{inputs:t,attrs:r,backend:n}=e,{input:a}=t,{dim:s}=r,i=a.shape.length,o=a.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),tn({inputs:{x:a},backend:n,attrs:{shape:o}})}var uge={kernelName:Xo,backendName:"wasm",kernelFunc:i2};function wT(e){let{attrs:{shape:t,value:r,dtype:n},backend:a}=e,s=a.makeOutput(t,n);return a.typedArrayFromHeap(s).fill(r),s}var dge={kernelName:Hu,backendName:"wasm",kernelFunc:wT},kT;function pge(e){kT=e.wasm.cwrap(Yo,null,["number","number","number","number","number","number"])}function hge(e){let{inputs:t,backend:r}=e,{image:n}=t,a=r.makeOutput(n.shape,n.dtype),s=r.dataIdMap.get(n.dataId).id,i=r.dataIdMap.get(a.dataId).id,[o,l,u,d]=n.shape;return kT(s,o,l,u,d,i),a}var cge={kernelName:Yo,backendName:"wasm",kernelFunc:hge,setupFunc:pge},fge=Ir(ui),mge=!1,gge=qr(di,mge),IT;function yge(e){IT=e.wasm.cwrap(pi,null,["number","number","number","number","number","number","number"])}function Age(e){let{backend:t,inputs:r,attrs:n}=e,{varianceEpsilon:a}=n,{x:s,mean:i,variance:o,offset:l,scale:u}=r,d=t.dataIdMap.get(s.dataId).id,h=t.dataIdMap.get(i.dataId).id,p=t.dataIdMap.get(o.dataId).id,c=l!=null?t.dataIdMap.get(l.dataId).id:0,f=u!=null?t.dataIdMap.get(u.dataId).id:0,m=t.makeOutput(s.shape,s.dtype);if(w.sizeFromShape(s.shape)===0)return m;let g=t.dataIdMap.get(m.dataId).id;return IT(d,h,p,c,f,a,g),m}var xge={kernelName:pi,backendName:"wasm",setupFunc:yge,kernelFunc:Age},ST;function bge(e){ST=e.wasm.cwrap($s,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 vge(e){let{inputs:t,attrs:r,backend:n}=e,{x:a,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:d,dataFormat:h,dimRoundingMode:p,activation:c,leakyreluAlpha:f}=r,m=N.computeConv2DInfo(a.shape,s.shape,l,d,u,p),g=T0[c];if(g==null)throw new Error(`${c} activation not yet supported for FusedConv2D in the wasm backend.`);let y=n.dataIdMap.get(a.dataId).id,A=n.dataIdMap.get(s.dataId).id,x=m.outChannels,b=0;if(i!=null){let Z=n.dataIdMap.get(i.dataId);if(Z.shape.length!==1)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${Z.shape.length}.`);if(Z.shape[0]!==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,S=m.filterWidth,T=m.padInfo.top,E=m.padInfo.right,R=m.padInfo.bottom,_=m.padInfo.left,M=m.dilationHeight,I=m.dilationWidth,z=m.strideHeight,O=m.strideWidth,j=m.inChannels,X=m.padInfo.type==="SAME"?1:0,D=m.batchSize,Q=m.inHeight,V=m.inWidth;if(h!=="NHWC")throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${h}'. Please use 'NHWC'.`);let ee=n.makeOutput(m.outShape,"float32"),J=n.dataIdMap.get(ee.dataId).id,ie=o==null?0:n.dataIdMap.get(o.dataId).id;return ST(y,D,Q,V,A,v,S,b,T,E,R,_,X,M,I,z,O,j,x,g,ie,f||0,J),ee}var wge={kernelName:$s,backendName:"wasm",setupFunc:bge,kernelFunc:vge},TT;function kge(e){TT=e.wasm.cwrap(Ps,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 Ige(e){let{inputs:t,attrs:r,backend:n}=e,{x:a,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:d,dataFormat:h,dimRoundingMode:p,activation:c,leakyreluAlpha:f}=r,m=N.computeConv2DInfo(a.shape,s.shape,l,d,u,p,!0),g=T0[c];if(g==null)throw new Error(`${c} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);let y=n.dataIdMap.get(a.dataId).id,A=n.dataIdMap.get(s.dataId).id,x=m.outChannels,b=0;if(i!=null){let Z=n.dataIdMap.get(i.dataId);if(Z.shape.length!==1)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${Z.shape.length}.`);if(Z.shape[0]!==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,S=m.filterWidth,T=m.padInfo.top,E=m.padInfo.right,R=m.padInfo.bottom,_=m.padInfo.left,M=m.dilationHeight,I=m.dilationWidth,z=m.strideHeight,O=m.strideWidth,j=m.inChannels,X=m.padInfo.type==="SAME"?1:0,D=m.batchSize,Q=m.inHeight,V=m.inWidth;if(h!=="NHWC")throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${h}'. Please use 'NHWC'.`);let ee=n.makeOutput(m.outShape,"float32"),J=n.dataIdMap.get(ee.dataId).id,ie=o==null?0:n.dataIdMap.get(o.dataId).id;return TT(y,D,Q,V,A,v,S,b,T,E,R,_,X,M,I,z,O,j,x,g,ie,f||0,J),ee}var Sge={kernelName:Ps,backendName:"wasm",setupFunc:kge,kernelFunc:Ige},NT;function Tge(e){NT=e.wasm.cwrap(Qo,null,["number","number","number","number","number","number","array","number"])}function Nge(e){let{backend:t,inputs:r}=e,{params:n,indices:a}=r,[s,i,o,l]=w2.prepareAndValidate(n,a),u=t.makeOutput(s,n.dtype);if(i===0)return u;let d=a.shape,h=d[d.length-1],p=t.dataIdMap.get(n.dataId).id,c=t.dataIdMap.get(a.dataId).id,f=new Uint8Array(new Int32Array(l).buffer),m=t.dataIdMap.get(u.dataId).id;return NT(p,Vt[n.dtype],c,i,h,o,f,m),u}var Cge={kernelName:Qo,backendName:"wasm",setupFunc:Tge,kernelFunc:Nge},CT;function Ege(e){CT=e.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function Rge(e){let{backend:t,inputs:r,attrs:n}=e,{x:a,indices:s}=r,{axis:i,batchDims:o}=n,l=w.parseAxisParam(i,a.shape)[0],u=t.readSync(s.dataId),d=a.shape[l];for(let T=0;T<u.length;++T){let E=u[T];w.assert(E<=d-1&&E>=0,()=>`GatherV2: the index value ${E} is not in [0, ${d-1}]`)}let h=N.segment_util.collectGatherOpShapeInfo(a,s,l,o),p=tn({inputs:{x:a},attrs:{shape:[h.batchSize,h.outerSize,h.dimSize,h.sliceSize]},backend:t}),c=w.sizeFromShape(s.shape),f=tn({inputs:{x:s},attrs:{shape:[h.batchSize,c/h.batchSize]},backend:t}),m=[h.batchSize,h.outerSize,c/h.batchSize,h.sliceSize],g=t.makeOutput(m,a.dtype);if(w.sizeFromShape(a.shape)===0)return g;let y=p.shape.length-1,A=t.dataIdMap.get(p.dataId).id,x=t.dataIdMap.get(f.dataId).id,b=t.dataIdMap.get(g.dataId).id,v=new Uint8Array(new Int32Array(w.computeStrides(p.shape)).buffer),S=new Uint8Array(new Int32Array(w.computeStrides(m)).buffer);return CT(A,Vt[a.dtype],v,y,x,h.batchSize,S,b),t.disposeData(p.dataId),t.disposeData(f.dataId),g.shape=h.outputShape,g}var Mge={kernelName:Jo,backendName:"wasm",setupFunc:Ege,kernelFunc:Rge},Fge=!1,$ge=qr(el,Fge,"bool"),Pge=!1,_ge=qr(hi,Pge,"bool"),ET;function zge(e){ET=e.wasm.cwrap(fi,null,["number","number","number","number"])}function Oge(e){let{inputs:{x:t},attrs:{alpha:r},backend:n}=e,a=n.dataIdMap.get(t.dataId).id,s=n.makeOutput(t.shape,"float32");if(w.sizeFromShape(t.shape)!==0){let i=n.dataIdMap.get(s.dataId).id;ET(a,Vt[t.dtype],r,i)}return s}var Dge={kernelName:fi,backendName:"wasm",setupFunc:zge,kernelFunc:Oge},Lge=!1,Bge=qr(tl,Lge,"bool"),Wge=!1,Vge=qr(rl,Wge,"bool"),Uge=Ir(mi),Gge=!1,jge=qr(nl,Gge,"bool"),RT;function Hge(e){RT=e.wasm.cwrap(gi,null,["number","number","number","number"])}function qge(e){let{backend:t,inputs:r,attrs:n}=e,{reductionIndices:a,keepDims:s}=n,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=i,{transposed:u,axes:d,originalAxes:h,inputWasTransposed:p}=qi(i,a,t);if(p){let A=t.dataIdMap.get(u.dataId).id;l=u,o=A}let c=l.shape.length;N.assertAxesAreInnerMostDims("max",d,c);let[f,m]=N.computeOutAndReduceShapes(l.shape,d),g=w.sizeFromShape(m),y=t.makeOutput(f,i.dtype);if(w.sizeFromShape(l.shape)!==0){let A=t.dataIdMap.get(y.dataId).id;RT(o,Vt[i.dtype],g,A)}if(p&&t.disposeData(u.dataId),s){let A=N.expandShapeToKeepDim(y.shape,h);y.shape=A}return y}var Kge={kernelName:gi,backendName:"wasm",setupFunc:Hge,kernelFunc:qge},Xge=!1,Zge=qr(yi,Xge),MT;function Yge(e){MT=e.wasm.cwrap(Ai,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Jge(e){let{inputs:t,attrs:r,backend:n}=e,a=t.x,s=n.dataIdMap.get(a.dataId).id;w.assert(a.dtype==="float32",()=>`Error in MaxPool: only float32 input is supported. Got ${a.dtype}.`);let{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=r,d=N.computePool2DInfo(a.shape,i,o,1,l,u),h=d.filterHeight,p=d.filterWidth,c=d.padInfo.top,f=d.padInfo.right,m=d.padInfo.bottom,g=d.padInfo.left,y=d.dilationHeight,A=d.dilationWidth,x=d.strideHeight,b=d.strideWidth,v=d.inChannels,S=d.outChannels;if(d.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${d.dataFormat}'. Please use 'channelsLast'.`);let T=n.makeOutput(d.outShape,"float32"),E=n.dataIdMap.get(T.dataId).id;return MT(s,a.shape[0],a.shape[1],a.shape[2],h,p,c,f,m,g,y,A,x,b,v,S,E),T}var Qge={kernelName:Ai,backendName:"wasm",setupFunc:Yge,kernelFunc:Jge},FT;function e1e(e){FT=e.wasm.cwrap(xi,null,["number, number, number"])}function t1e(e){let{backend:t,inputs:r,attrs:n}=e,{axis:a,keepDims:s}=n,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=o,u=i,{transposed:d,axes:h,originalAxes:p,inputWasTransposed:c}=qi(i,a,t),f=h;if(c){let b=t.dataIdMap.get(d.dataId).id;b!==o&&(u=d,l=b,f=N.getInnerMostAxes(f.length,u.shape.length))}N.assertAxesAreInnerMostDims("mean",f,u.shape.length);let[m,g]=N.computeOutAndReduceShapes(u.shape,f),y=w.sizeFromShape(g),A=u;u.dtype!=="float32"&&(A=jh({backend:t,inputs:{x:u},attrs:{dtype:"float32"}}),l=t.dataIdMap.get(A.dataId).id);let x=t.makeOutput(m,"float32");if(w.sizeFromShape(u.shape)!==0){let b=t.dataIdMap.get(x.dataId).id;FT(l,y,b)}if(c&&t.disposeData(d.dataId),s){let b=N.expandShapeToKeepDim(x.shape,p);x.shape=b}return u.dtype!=="float32"&&t.disposeData(A.dataId),x}var r1e={kernelName:xi,backendName:"wasm",setupFunc:e1e,kernelFunc:t1e},$T;function n1e(e){$T=e.wasm.cwrap(bi,null,["number","number","number","number"])}function a1e(e){let{backend:t,inputs:r,attrs:n}=e,{axis:a,keepDims:s}=n,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=o,u=i,{transposed:d,axes:h,originalAxes:p,inputWasTransposed:c}=qi(i,a,t);if(c){let x=t.dataIdMap.get(d.dataId).id;x!==o&&(u=d,l=x)}let f=u.shape.length;N.assertAxesAreInnerMostDims("min",h,f);let[m,g]=N.computeOutAndReduceShapes(u.shape,h),y=w.sizeFromShape(g),A=t.makeOutput(m,u.dtype);if(w.sizeFromShape(u.shape)!==0){let x=t.dataIdMap.get(A.dataId).id;$T(l,Vt[i.dtype],y,x)}if(c&&t.disposeData(d.dataId),s){let x=N.expandShapeToKeepDim(A.shape,p);A.shape=x}return A}var s1e={kernelName:bi,backendName:"wasm",setupFunc:n1e,kernelFunc:a1e},i1e=!1,o1e=qr(vi,i1e),PT=(e=>(e[e.reflect=0]="reflect",e[e.symmetric=1]="symmetric",e))(PT||{}),_T;function l1e(e){_T=e.wasm.cwrap(wi,null,["number","array","number","number","array","array","number","number"])}function u1e(e){let{inputs:{x:t},backend:r,attrs:{paddings:n,mode:a}}=e,s=n.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,u=new Uint8Array(new Int32Array(t.shape).buffer),d=n.map(f=>f[0]),h=n.map(f=>f[1]),p=new Uint8Array(new Int32Array(d).buffer),c=new Uint8Array(new Int32Array(h).buffer);return _T(i,u,t.shape.length,Vt[t.dtype],p,c,PT[a],l),o}var d1e={kernelName:wi,backendName:"wasm",kernelFunc:u1e,setupFunc:l1e},p1e=!0,h1e=qr(ki,p1e),c1e=Ir(al);function Nb(e,t){let r=new Int32Array(e.wasm.HEAPU8.buffer,t,4),n=r[0],a=r[1],s=r[2],i=r[3];return e.wasm._free(t),{pSelectedIndices:n,selectedSize:a,pSelectedScores:s,pValidOutputs:i}}var zT;function f1e(e){zT=e.wasm.cwrap(il,"number",["number","number","number","number","number"])}function m1e(e){let{backend:t,inputs:r,attrs:n}=e,{iouThreshold:a,maxOutputSize:s,scoreThreshold:i}=n,{boxes:o,scores:l}=r,u=t.dataIdMap.get(o.dataId).id,d=t.dataIdMap.get(l.dataId).id,h=zT(u,d,s,a,i),{pSelectedIndices:p,selectedSize:c,pSelectedScores:f,pValidOutputs:m}=Nb(t,h);return t.wasm._free(f),t.wasm._free(m),t.makeOutput([c],"int32",p)}var g1e={kernelName:il,backendName:"wasm",setupFunc:f1e,kernelFunc:m1e},OT;function y1e(e){OT=e.wasm.cwrap(Qu,"number",["number","number","number","number","number","bool"])}function A1e(e){let{backend:t,inputs:r,attrs:n}=e,{iouThreshold:a,maxOutputSize:s,scoreThreshold:i,padToMaxOutputSize:o}=n,{boxes:l,scores:u}=r,d=t.dataIdMap.get(l.dataId).id,h=t.dataIdMap.get(u.dataId).id,p=OT(d,h,s,a,i,o),{pSelectedIndices:c,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=Nb(t,p);t.wasm._free(m);let y=t.makeOutput([f],"int32",c),A=t.makeOutput([],"int32",g);return[y,A]}var x1e={kernelName:Qu,backendName:"wasm",setupFunc:y1e,kernelFunc:A1e},DT;function b1e(e){DT=e.wasm.cwrap(ol,"number",["number","number","number","number","number","number"])}function v1e(e){let{backend:t,inputs:r,attrs:n}=e,{iouThreshold:a,maxOutputSize:s,scoreThreshold:i,softNmsSigma:o}=n,{boxes:l,scores:u}=r,d=t.dataIdMap.get(l.dataId).id,h=t.dataIdMap.get(u.dataId).id,p=DT(d,h,s,a,i,o),{pSelectedIndices:c,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=Nb(t,p);t.wasm._free(g);let y=t.makeOutput([f],"int32",c),A=t.makeOutput([f],"float32",m);return[y,A]}var w1e={kernelName:ol,backendName:"wasm",setupFunc:b1e,kernelFunc:v1e},k1e=!1,I1e=qr(sl,k1e,"bool"),LT;function S1e(e){LT=e.wasm.cwrap(ul,null,["number","number","number","number","number"])}function T1e(e){let{inputs:t,backend:r,attrs:n}=e,{indices:a}=t,{depth:s,onValue:i,offValue:o}=n,l=r.makeOutput([...a.shape,s],"int32"),u=r.dataIdMap.get(l.dataId).id,d=r.dataIdMap.get(a.dataId).id;return LT(d,s,i,o,u),l}var N1e={kernelName:ul,backendName:"wasm",setupFunc:S1e,kernelFunc:T1e};function C1e(e){let{inputs:{x:t},backend:r}=e,n=r.makeOutput(t.shape,t.dtype);return r.typedArrayFromHeap(n).fill(1),n}var E1e={kernelName:ll,backendName:"wasm",kernelFunc:C1e};function R1e(e){let{inputs:t,backend:r,attrs:n}=e,{axis:a}=n;if(t.length===1)return i2({inputs:{input:t[0]},backend:r,attrs:{dim:a}});let s=t[0].shape,i=t[0].dtype;t.forEach(d=>{w.assertShapesMatch(s,d.shape,"All tensors passed to stack must have matching shapes"),w.assert(i===d.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(d=>{let h=i2({inputs:{input:d},backend:r,attrs:{dim:a}});return o.push(h),h}),u=cT({inputs:l,backend:r,attrs:{axis:a}});return o.forEach(d=>r.disposeData(d.dataId)),u}var M1e={kernelName:dl,backendName:"wasm",kernelFunc:R1e},BT;function F1e(e){BT=e.wasm.cwrap(Ii,null,["number","array","number","number","array","array","number","number"])}function $1e(e){let{inputs:{x:t},backend:r,attrs:{paddings:n,constantValue:a}}=e,s=n.map((f,m)=>f[0]+t.shape[m]+f[1]);if(w.sizeFromShape(t.shape)===0)return wT({backend:r,attrs:{shape:s,value:a,dtype:t.dtype}});let i=r.dataIdMap.get(t.dataId).id,o=r.makeOutput(s,t.dtype),l=r.dataIdMap.get(o.dataId).id,u=new Uint8Array(new Int32Array(t.shape).buffer),d=n.map(f=>f[0]),h=n.map(f=>f[1]),p=new Uint8Array(new Int32Array(d).buffer),c=new Uint8Array(new Int32Array(h).buffer);return BT(i,u,t.shape.length,Vt[t.dtype],p,c,a,l),o}var WT={kernelName:Ii,backendName:"wasm",kernelFunc:$1e,setupFunc:F1e},P1e=!1,_1e=qr(Si,P1e),VT;function z1e(e){VT=e.wasm.cwrap(Ti,null,["number","number","number"])}function O1e(e){let{inputs:t,backend:r}=e,{x:n,alpha:a}=t,s=r.dataIdMap.get(n.dataId).id,i=r.dataIdMap.get(a.dataId).id,o=s,l=n,u=l;l.dtype!=="float32"&&(u=jh({backend:r,inputs:{x:n},attrs:{dtype:"float32"}}),o=r.dataIdMap.get(u.dataId).id);let d=r.makeOutput(n.shape,"float32"),h=r.dataIdMap.get(d.dataId).id;return VT(o,i,h),l.dtype!=="float32"&&r.disposeData(u.dataId),d}var D1e={kernelName:Ti,backendName:"wasm",setupFunc:z1e,kernelFunc:O1e},UT;function L1e(e){UT=e.wasm.cwrap(Ni,null,["number","number","number","number"])}function B1e(e){let{backend:t,inputs:r,attrs:n}=e,{axis:a,keepDims:s}=n,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=o,u=i,{transposed:d,axes:h,originalAxes:p,inputWasTransposed:c}=qi(i,a,t),f=h;if(c){let x=t.dataIdMap.get(d.dataId).id;x!==o&&(u=d,l=x,f=N.getInnerMostAxes(f.length,u.shape.length))}N.assertAxesAreInnerMostDims("prod",f,u.shape.length);let[m,g]=N.computeOutAndReduceShapes(u.shape,f),y=w.sizeFromShape(g),A=t.makeOutput(m,u.dtype);if(w.sizeFromShape(u.shape)!==0){let x=t.dataIdMap.get(A.dataId).id;UT(l,y,Vt[A.dtype],x)}if(c&&t.disposeData(d.dataId),s){let x=N.expandShapeToKeepDim(A.shape,p);A.shape=x}return A}var W1e={kernelName:Ni,backendName:"wasm",setupFunc:L1e,kernelFunc:B1e},V1e=e=>{let{backend:t,attrs:r}=e,{start:n,stop:a,step:s,dtype:i}=r,o=Qx(n,a,s,i),l=t.makeOutput([o.length],i);return t.typedArrayFromHeap(l).set(o),l},U1e={kernelName:ed,backendName:"wasm",kernelFunc:V1e},G1e=!0,j1e=qr(ii,G1e),H1e=Ir(Ci),q1e=Ir(Ri),GT;function K1e(e){GT=e.wasm.cwrap(Ei,null,["number","number","number","number","number","number","number","number","number","number"])}function X1e(e){let{backend:t,inputs:r,attrs:n}=e,{images:a}=r,{alignCorners:s,halfPixelCenters:i,size:o}=n,[l,u]=o,[d,h,p,c]=a.shape,f=[d,l,u,c],m=t.dataIdMap.get(a.dataId),g;m.dtype!=="float32"&&(g=jh({backend:t,inputs:{x:a},attrs:{dtype:"float32"}}),m=t.dataIdMap.get(g.dataId));let y=m.id,A=t.makeOutput(f,"float32");if(w.sizeFromShape(a.shape)===0)return A;let x=t.dataIdMap.get(A.dataId).id;return GT(y,d,h,p,c,l,u,s?1:0,i?1:0,x),g!=null&&t.disposeData(g.dataId),A}var Z1e={kernelName:Ei,backendName:"wasm",setupFunc:K1e,kernelFunc:X1e},jT;function Y1e(e){jT=e.wasm.cwrap(hl,null,["number","array","number","array","number","number"])}function J1e(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{dims:s}=n,i=w.parseAxisParam(s,a.shape);if(a.shape.length===0)return N0({inputs:{x:a},backend:r});let o=r.makeOutput(a.shape,a.dtype),l=r.dataIdMap.get(a.dataId).id,u=r.dataIdMap.get(o.dataId).id,d=new Uint8Array(new Int32Array(i).buffer),h=new Uint8Array(new Int32Array(a.shape).buffer);jT(l,d,i.length,h,a.shape.length,u);let p=tn({inputs:{x:o},attrs:{shape:a.shape},backend:r});return r.disposeData(o.dataId),p}var Q1e={kernelName:hl,backendName:"wasm",kernelFunc:J1e,setupFunc:Y1e},HT;function eye(e){HT=e.wasm.cwrap(Tl,null,["number","number","number","number","number","number","number","number","array","number","number"])}function tye(e){let{inputs:t,backend:r,attrs:n}=e,{image:a}=t,{radians:s,fillValue:i,center:o}=n,l=r.makeOutput(a.shape,a.dtype),u=r.dataIdMap.get(a.dataId).id,d=r.dataIdMap.get(l.dataId).id,[h,p,c,f]=a.shape,[m,g]=N.getImageCenter(o,p,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 HT(u,h,p,c,f,s,m,g,b,x.length,d),l}var rye={kernelName:Tl,backendName:"wasm",kernelFunc:tye,setupFunc:eye},nye=Ir(cl),aye=Ir(Mi),qT;function sye(e){qT=e.wasm.cwrap(fl,null,["number","number","number","number","number","number","array","number","number"])}function iye(e){let{backend:t,inputs:r,attrs:n}=e,{indices:a,updates:s}=r,{shape:i}=n,o=t.makeOutput(i,s.dtype);if(w.sizeFromShape(i)===0)return o;let{sliceRank:l,numUpdates:u,sliceSize:d,strides:h,outputSize:p}=k2.calculateShapes(s,a,i),c=t.dataIdMap.get(a.dataId).id,f=t.dataIdMap.get(s.dataId).id,m=new Uint8Array(new Int32Array(h).buffer),g=t.dataIdMap.get(o.dataId).id;return qT(c,f,Vt[s.dtype],l,u,d,m,p,g),o}var oye={kernelName:fl,backendName:"wasm",setupFunc:sye,kernelFunc:iye},KT;function lye(e){KT=e.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function uye(e){let{inputs:t,backend:r}=e,{condition:n,t:a,e:s}=t,i=r.dataIdMap.get(n.dataId).id,o=r.dataIdMap.get(a.dataId).id,l=r.dataIdMap.get(s.dataId).id,u=r.makeOutput(a.shape,a.dtype),d=r.dataIdMap.get(u.dataId).id,h=n.shape.length,p=a.shape.length,c=h===0||h>1||p===1?1:w.sizeFromShape(a.shape.slice(1));return KT(i,o,l,c,d),u}var dye={kernelName:ml,backendName:"wasm",kernelFunc:uye,setupFunc:lye},XT;function pye(e){XT=e.wasm.cwrap($i,null,["number","number"])}function hye(e){let{backend:t,inputs:{x:r}}=e,n=t.dataIdMap.get(r.dataId).id,a=t.makeOutput(r.shape,r.dtype),s=t.dataIdMap.get(a.dataId).id;return w.sizeFromShape(a.shape)===0||XT(n,s),a}var cye={kernelName:"Sigmoid",backendName:"wasm",setupFunc:pye,kernelFunc:hye},fye=Ir(Fi),ZT;function mye(e){ZT=e.wasm.cwrap(zi,null,["number","number","number","number"])}function gye(e){let{backend:t,inputs:{logits:r},attrs:{dim:n}}=e,a=t.dataIdMap.get(r.dataId).id,s=t.makeOutput(r.shape,r.dtype),i=t.dataIdMap.get(s.dataId).id,o=r.shape[n],l=w.sizeFromShape(r.shape)/o;return w.sizeFromShape(s.shape)===0||ZT(a,i,o,l),s}var yye={kernelName:zi,backendName:"wasm",setupFunc:mye,kernelFunc:gye};function Aye(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,{blockShape:s,paddings:i}=n,o=w.sizeFromShape(s),l=[[0,0]];l.push(...i);for(let g=1+s.length;g<a.shape.length;++g)l.push([0,0]);let u=WT.kernelFunc({inputs:{x:a},backend:r,attrs:{paddings:l,constantValue:0}}),d=N.getReshaped(u.shape,s,o,!1),h=N.getPermuted(d.length,s.length,!1),p=N.getReshapedPermuted(u.shape,s,o,!1),c=tn({inputs:{x:u},backend:r,attrs:{shape:d}}),f=Hs({inputs:{x:c},backend:r,attrs:{perm:h}}),m=tn({inputs:{x:f},backend:r,attrs:{shape:p}});return r.disposeData(u.dataId),r.disposeData(c.dataId),r.disposeData(f.dataId),m}var xye={kernelName:Al,backendName:"wasm",kernelFunc:Aye},YT;function bye(e){YT=e.wasm.cwrap("SparseFillEmptyRows","number",["number","number","number","number","number","number","number","number","number","number","number","number"])}function vye(e){let{backend:t,inputs:r}=e,{indices:n,values:a,denseShape:s,defaultValue:i}=r,o=n.shape[0],l=n.shape[1],u=t.readSync(s.dataId)[0],d=[o+u,l],h=t.dataIdMap.get(n.dataId).id,p=t.dataIdMap.get(a.dataId).id,c=t.dataIdMap.get(i.dataId).id,f=t.makeOutput(d,n.dtype),m=t.dataIdMap.get(f.dataId).id,g=t.makeOutput(d.slice(0,1),a.dtype),y=t.dataIdMap.get(g.dataId).id,A=t.makeOutput([u],"bool"),x=t.dataIdMap.get(A.dataId).id,b=t.makeOutput([o],n.dtype),v=t.dataIdMap.get(b.dataId).id,S=t.makeOutput([4],"int32"),T=t.dataIdMap.get(S.dataId).id,E=YT(h,p,Vt[a.dtype],o,u,l,c,m,y,x,v,T),R=t.readSync(S.dataId),_;switch(R[0]){case 1:{_=N.getSparseFillEmptyRowsIndicesDenseShapeMismatch(R[1]);break}case 2:{_=N.getSparseFillEmptyRowsNegativeIndexErrorMessage(R[1],R[2]);break}case 3:_=N.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(R[1],R[2],R[3]);break;default:_=""}if(t.disposeData(S.dataId),_)throw t.disposeData(f.dataId),t.disposeData(g.dataId),t.disposeData(A.dataId),t.disposeData(b.dataId),new Error(_);let M=f,I=g;return E!==d[0]&&(M=Lo({inputs:{x:f},attrs:{begin:0,size:[E,l]},backend:t}),I=Lo({inputs:{x:g},attrs:{begin:0,size:E},backend:t}),t.disposeData(f.dataId),t.disposeData(g.dataId)),[M,I,A,b]}var wye={kernelName:sh,backendName:"wasm",setupFunc:bye,kernelFunc:vye},JT;function kye(e){JT=e.wasm.cwrap(id,null,["number","number","number","number","number","number","number"])}function Iye(e){let{backend:t,inputs:r}=e,{inputIndices:n,inputShape:a,newShape:s}=r;if(n.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
|
|
${n.shape}`);if(a.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
|
|
${a.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=t.dataIdMap.get(n.dataId).id,o=t.dataIdMap.get(a.dataId).id,l=t.dataIdMap.get(s.dataId).id,u=n.shape[0],d=w.sizeFromShape(s.shape),h=t.makeOutput([u,d],n.dtype),p=t.dataIdMap.get(h.dataId).id,c=t.makeOutput([d],s.dtype),f=t.dataIdMap.get(c.dataId).id,m=t.makeOutput([3],"int32"),g=t.dataIdMap.get(m.dataId).id;JT(i,o,l,u,p,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(a.dataId)),b=Array.from(t.readSync(c.dataId));A=N.getSparseReshapeInputOutputMultipleErrorMessage(x,b);break}case 4:{let x=Array.from(t.readSync(a.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(h.dataId),t.disposeData(c.dataId),new Error(A);return[h,c]}var Sye={kernelName:id,backendName:"wasm",setupFunc:kye,kernelFunc:Iye},QT;function eN(e){QT=e.wasm.cwrap("SparseSegmentReduction",null,["number","number","number","number","number","number","number","number","number"])}function tN(e,t){let{backend:r,inputs:n}=e,{data:a,indices:s,segmentIds:i}=n,o=s.shape[0],l=r.readSync(i.dataId,o-1,o)[0],u=o>0?l+1:0;if(u<0)throw new Error(N.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let d=a.shape.slice();d[0]=u;let h=r.dataIdMap.get(a.dataId).id,p=r.dataIdMap.get(s.dataId).id,c=r.dataIdMap.get(i.dataId).id,f=r.makeOutput(d,a.dtype),m=r.dataIdMap.get(f.dataId).id,g=r.makeOutput([4],"int32"),y=r.dataIdMap.get(g.dataId).id;QT(h,Vt[a.dtype],a.shape[0],p,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 Tye(e){return tN(e,!0)}var Nye={kernelName:ih,backendName:"wasm",setupFunc:eN,kernelFunc:Tye};function Cye(e){return tN(e,!1)}var Eye={kernelName:oh,backendName:"wasm",setupFunc:eN,kernelFunc:Cye};function Rye(e){let{inputs:t,attrs:r,backend:n}=e,{x:a}=t,{numOrSizeSplits:s,axis:i}=r,o=w.parseAxisParam(i,a.shape)[0],l=N.prepareSplitSize(a,s,o),u=new Array(a.shape.length).fill(0),d=a.shape.slice();return l.map(h=>{let p=[...d];p[o]=h;let c=Lo({inputs:{x:a},attrs:{begin:u,size:p},backend:n});return u[o]+=h,c})}var Mye={kernelName:xl,backendName:"wasm",kernelFunc:Rye},Fye=Ir(Pi),$ye=Ir(od),Pye=!0,_ye=qr(Oi,Pye),rN;function zye(e){rN=e.wasm.cwrap(Wi,null,["number","number","number","number"])}function Oye(e){let{backend:t,inputs:r,attrs:n}=e,{alpha:a}=n,{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 rN(i,a,Vt[s.dtype],l),o}var Dye={kernelName:Wi,backendName:"wasm",setupFunc:zye,kernelFunc:Oye},nN;function Lye(e){nN=e.wasm.cwrap(bl,null,["number","array","number","array","array","array","array","array","number","number"])}function Bye(e){let{backend:t,inputs:r,attrs:n}=e,{x:a}=r,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:d,newAxisMask:h,shrinkAxisMask:p}=n,{finalShapeSparse:c,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:A,end:x,strides:b}=zt.sliceInfo(a.shape,s,i,o,l,u,d,h,p),v;if(m)v=tn({inputs:{x:a},backend:t,attrs:{shape:f}});else if(g||y){w.assert(a.shape.length>=1,()=>`Input must have rank at least 1, got: ${a.shape.length}`);let S=zt.computeOutShape(A,x,b),T=Lo({inputs:{x:a},backend:t,attrs:{begin:A,size:S}});v=tn({inputs:{x:T},backend:t,attrs:{shape:f}}),t.disposeData(T.dataId)}else{let S=t.makeOutput(c,"float32"),T=t.dataIdMap.get(a.dataId).id,E=new Uint8Array(new Int32Array(w.computeStrides(a.shape)).buffer),R=new Uint8Array(new Int32Array(A).buffer),_=new Uint8Array(new Int32Array(x).buffer),M=new Uint8Array(new Int32Array(b).buffer),I=new Uint8Array(new Int32Array(c).buffer),z=new Uint8Array(new Int32Array(w.computeStrides(c)).buffer),O=t.dataIdMap.get(S.dataId).id;nN(T,E,a.shape.length,R,_,M,I,z,c.length,O),v=tn({inputs:{x:S},backend:t,attrs:{shape:f}}),t.disposeData(S.dataId)}return v}var Wye={kernelName:bl,backendName:"wasm",setupFunc:Lye,kernelFunc:Bye},Vye=!0,Uye=qr(Di,Vye),aN;function Gye(e){aN=e.wasm.cwrap(_i,null,["number","number","number","number"])}function jye(e){let{backend:t,inputs:r,attrs:n}=e,{axis:a,keepDims:s}=n,{x:i}=r,o=t.dataIdMap.get(i.dataId).id,l=o,u=i,{transposed:d,axes:h,originalAxes:p,inputWasTransposed:c}=qi(i,a,t),f=h;if(c){let x=t.dataIdMap.get(d.dataId).id;x!==o&&(u=d,l=x,f=N.getInnerMostAxes(f.length,u.shape.length))}N.assertAxesAreInnerMostDims("sum",f,u.shape.length);let[m,g]=N.computeOutAndReduceShapes(u.shape,f),y=w.sizeFromShape(g),A=t.makeOutput(m,u.dtype);if(w.sizeFromShape(u.shape)!==0){let x=t.dataIdMap.get(A.dataId).id;aN(l,y,Vt[A.dtype],x)}if(c&&t.disposeData(d.dataId),s){let x=N.expandShapeToKeepDim(A.shape,p);A.shape=x}return A}var Hye={kernelName:_i,backendName:"wasm",setupFunc:Gye,kernelFunc:jye},qye=Ir(vl),Kye=Ir(Li),sN;function Xye(e){sN=e.wasm.cwrap(es,null,["number","array","number","array","number","number"])}function Zye(e){let{inputs:t,backend:r,attrs:n}=e,{x:a}=t,s=r.dataIdMap.get(a.dataId).id,{reps:i}=n,o=new Array(a.shape.length);for(let p=0;p<o.length;p++)o[p]=a.shape[p]*i[p];let l=new Uint8Array(new Int32Array(a.shape).buffer),u=new Uint8Array(new Int32Array(o).buffer),d=r.makeOutput(o,a.dtype),h=r.dataIdMap.get(d.dataId).id;return sN(s,l,a.shape.length,u,o.length,Vt[d.dtype],h),d}var Yye={kernelName:es,backendName:"wasm",setupFunc:Xye,kernelFunc:Zye},iN;function Jye(e){iN=e.wasm.cwrap(wl,null,["number","array","number","number","number","bool","number","number"])}var Qye=({inputs:e,backend:t,attrs:r})=>{let{x:n}=e,{k:a,sorted:s}=r,i=t.dataIdMap.get(n.dataId).id,o=new Uint8Array(new Int32Array(n.shape).buffer),l=n.shape.slice();l[l.length-1]=a;let u=t.makeOutput(l,n.dtype),d=t.dataIdMap.get(u.dataId).id,h=t.makeOutput(l,"int32"),p=t.dataIdMap.get(h.dataId).id;return iN(i,o,n.shape.length,Vt[n.dtype],a,s,d,p),[u,h]},e2e={kernelName:wl,backendName:"wasm",setupFunc:Jye,kernelFunc:Qye},oN;function t2e(e){oN=e.wasm.cwrap(kl,null,["number","number","bool","number","number","number","number","number","number","array","number","number","number","number","number"])}function r2e(e){let{backend:t,inputs:r,attrs:n}=e,{image:a,transforms:s}=r,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=n,[d,h,p,c]=a.shape,[f,m]=u!=null?u:[h,p],g=[d,f,m,c],y=new Uint8Array(new Int32Array(w.computeStrides(a.shape)).buffer),A=t.makeOutput(g,a.dtype),x=t.dataIdMap.get(A.dataId).id,b=t.dataIdMap.get(a.dataId).id,v=t.dataIdMap.get(s.dataId).id,S=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 oN(b,v,s.shape[0]>1,d,f,m,c,p,h,y,a.shape.length-1,S,T,l,x),A}var n2e={kernelName:kl,backendName:"wasm",setupFunc:t2e,kernelFunc:r2e};function a2e(e){let{inputs:t,backend:r,attrs:n}=e,{value:a}=t,{axis:s}=n;s<0&&(s+=a.shape.length);let i=a.shape[s],o=a.shape.length,l=new Array(o-1),u=0;for(let c=0;c<o;c++)c!==s&&(l[u++]=a.shape[c]);let d=new Array(i),h=new Array(o).fill(0),p=a.shape.slice();p[s]=1;for(let c=0;c<d.length;c++)h[s]=c,d[c]=Lo({inputs:{x:a},attrs:{begin:h,size:p},backend:r});return d.map(({dataId:c,dtype:f})=>({dataId:c,dtype:f,shape:l}))}var s2e={kernelName:Il,backendName:"wasm",kernelFunc:a2e};function i2e(e){let{inputs:{x:t},backend:r}=e,n=r.makeOutput(t.shape,t.dtype);return r.typedArrayFromHeap(n).fill(0),n}var o2e={kernelName:Sl,backendName:"wasm",kernelFunc:i2e},l2e=[Zme,Yme,Qme,r0e,d0e,c0e,g0e,x0e,k0e,E0e,R0e,M0e,P0e,_0e,D0e,W0e,V0e,U0e,H0e,X0e,J0e,tge,age,sge,oge,lge,uge,dge,cge,fge,gge,xge,wge,Sge,Cge,Mge,$ge,_ge,n0e,Dge,Bge,Vge,Uge,jge,Kge,Zge,Qge,r1e,s1e,o1e,d1e,h1e,c1e,g1e,x1e,w1e,I1e,N1e,E1e,M1e,WT,_1e,D1e,W1e,U1e,j1e,H1e,q1e,b0e,Z1e,Q1e,rye,nye,aye,oye,dye,cye,fye,N0e,yye,xye,wye,Sye,Nye,Eye,Mye,Fye,$ye,_ye,Dye,Wye,Uye,Hye,qye,Kye,Yye,e2e,n2e,o0e,s2e,o2e];for(let e of l2e)jn(e);var o2=Y();o2.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])));o2.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(o2.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 mw=Bo(dR()),u2e=`"use strict";var Module={};var ENVIRONMENT_IS_NODE=typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string";if(ENVIRONMENT_IS_NODE){var nodeWorkerThreads=require("worker_threads");var parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",function(data){onmessage({data:data})});var fs=require("fs");Object.assign(global,{self:global,require:require,Module:Module,location:{href:__filename},Worker:nodeWorkerThreads.Worker,importScripts:function(f){(0,eval)(fs.readFileSync(f,"utf8"))},postMessage:function(msg){parentPort.postMessage(msg)},performance:global.performance||{now:function(){return Date.now()}}})}function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");if(ENVIRONMENT_IS_NODE){fs.writeSync(2,text+"
|
|
");return}console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;self.alert=threadAlert;Module["instantiateWasm"]=((info,receiveInstance)=>{var instance=new WebAssembly.Instance(Module["wasmModule"],info);receiveInstance(instance);Module["wasmModule"]=null;return instance.exports});self.onmessage=(e=>{try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;if(typeof e.data.urlOrBlob==="string"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}WasmBackendModuleThreadedSimd(Module).then(function(instance){Module=instance})}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;Module["__emscripten_thread_init"](e.data.threadInfoStruct,0,0,1);Module["establishStackSpace"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].threadInit();try{var result=Module["invokeEntryPoint"](e.data.start_routine,e.data.arg);if(Module["keepRuntimeAlive"]()){Module["PThread"].setExitStatus(result)}else{Module["__emscripten_thread_exit"](result)}}catch(ex){if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["keepRuntimeAlive"]()){}else{Module["__emscripten_thread_exit"](ex.status)}}else{throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["__emscripten_thread_exit"](-1)}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(Module["_pthread_self"]()){Module["_emscripten_current_thread_process_queued_calls"]()}}else if(e.data.cmd==="processProxyingQueue"){if(Module["_pthread_self"]()){Module["_emscripten_proxy_execute_queue"](e.data.queue)}}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);if(Module["__emscripten_thread_crashed"]){Module["__emscripten_thread_crashed"]()}throw ex}});`,d2e=Bo(pR()),lN=class extends $u{constructor(e){super(),this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.initWithThreadsCount(uN),l2=this.wasm.tfjs.getThreadsCount(),this.dataIdMap=new qp(this,nr())}write(e,t,r){let n={id:this.dataIdNextNumber++};return this.move(n,e,t,r,1),n}numDataIds(){return this.dataIdMap.numDataIds()}async time(e){let t=w.now();return e(),{kernelMs:w.now()-t}}move(e,t,r,n,a){let s=this.dataIdNextNumber++;if(n==="string"){let u=t;this.dataIdMap.set(e,{id:s,stringBytes:u,shape:r,dtype:n,memoryOffset:null,refCount:a});return}let i=w.sizeFromShape(r),o=i*w.bytesPerElement(n),l=this.wasm._malloc(o);this.dataIdMap.set(e,{id:s,memoryOffset:l,shape:r,dtype:n,refCount:a}),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:n,dtype:a,shape:s,stringBytes:i}=this.dataIdMap.get(e);if(a==="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(a),l=this.wasm.HEAPU8.slice(n+t*o,n+r*o);return c2e(l.buffer,a)}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 n;if(r==null)n=this.write(null,e,t);else{let a=this.dataIdNextNumber++;n={id:a},this.dataIdMap.set(n,{id:a,memoryOffset:r,shape:e,dtype:t,refCount:1});let s=w.sizeFromShape(e);this.wasm.tfjs.registerTensor(a,s,r)}return{dataId:n,shape:e,dtype:t}}typedArrayFromHeap({shape:e,dtype:t,dataId:r}){let n=this.wasm.HEAPU8.buffer,{memoryOffset:a}=this.dataIdMap.get(r),s=w.sizeFromShape(e);switch(t){case"float32":return new Float32Array(n,a,s);case"int32":return new Int32Array(n,a,s);case"bool":return new Uint8Array(n,a,s);default:throw new Error(`Unknown dtype ${t}`)}}};function p2e(e){return(t,r)=>(w.fetch(e,{credentials:"same-origin"}).then(n=>{n.ok||t.env.a(`failed to load wasm binary file at '${e}'`),n.arrayBuffer().then(a=>{WebAssembly.instantiate(a,t).then(s=>{r(s.instance,s.module)})})}),{})}function gw(e,t,r){if(Uf!=null)return Uf;let n="tfjs-backend-wasm.wasm";return e&&t?n="tfjs-backend-wasm-threaded-simd.wasm":e&&(n="tfjs-backend-wasm-simd.wasm"),Mp!=null&&Mp[n]!=null?Mp[n]:r+n}async function h2e(){let[e,t]=await Promise.all([Y().getAsync("WASM_HAS_SIMD_SUPPORT"),Y().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise((r,n)=>{let a={};a.locateFile=(o,l)=>{if(o.endsWith(".worker.js")){let u=u2e.replace(/\n/g,"\\n"),d=new Blob([u],{type:"application/javascript"});return URL.createObjectURL(d)}return o.endsWith(".wasm")?gw(e,t,Np!=null?Np:l):l+o},Cb&&(a.instantiateWasm=p2e(gw(e,t,Np!=null?Np:"")));let s=!1;a.onAbort=()=>{s||Fp||(Fp=!0,n({message:"Make sure the server can serve the `.wasm` file relative to the bundled js file. For more details see https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/README.md#using-bundlers"}))};let i;t&&e&&Uf==null?(a.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+mw.default.toString()],{type:"text/javascript"}),i=(0,mw.default)(a)):i=(0,d2e.default)(a),i.then(o=>{s=!0,Fp=!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 c2e(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 f2e=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"],Uf=null,Np=null,Mp={},Fp=!1,Cb=!1;function m2e(e,t=!1){if(R2("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."),Fp)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");Uf=e,Cb=t}function Eb(e,t=!1){if(Fp)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")Np=e;else{Mp=e;let r=f2e.filter(n=>Mp[n]==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.`)}Cb=t}var uN=-1,l2=-1;function g2e(e){uN=e}function y2e(){if(l2===-1)throw new Error("WASM backend not initialized.");return l2}var A2e="0.0.0",x2e=2;Cl("wasm",async()=>{let{wasm:e}=await h2e();return new lN(e)},x2e);var ws="3.15.0-20220414",Hh={tfjs:ws,"tfjs-core":ws,"tfjs-data":ws,"tfjs-layers":ws,"tfjs-converter":ws,"tfjs-backend-cpu":ws,"tfjs-backend-webgl":ws,"tfjs-backend-wasm":ws};var dN=`
|
|
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 pN=`
|
|
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];
|
|
}
|
|
`,hN=`
|
|
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;
|
|
}
|
|
`,cN=`
|
|
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);
|
|
}
|
|
`,fN=`
|
|
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;
|
|
}
|
|
`,mN=`
|
|
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 Rb=(e,t,r)=>{let n=new RegExp("\\b"+t+" \\w+ (\\w+)","ig");e.replace(n,(a,s)=>(r[s]=0,a))},Mb=class{constructor(t,r,n){fe(this,"uniform",{});fe(this,"attribute",{});fe(this,"gl");fe(this,"id");fe(this,"compile",(t,r)=>{let n=this.gl.createShader(r);return n?(this.gl.shaderSource(n,t),this.gl.compileShader(n),this.gl.getShaderParameter(n,this.gl.COMPILE_STATUS)?n:(se(`filter: gl compile failed: ${this.gl.getShaderInfoLog(n)}`),null)):(se("filter: could not create shader"),null)});this.gl=t;let a=this.compile(r,this.gl.VERTEX_SHADER),s=this.compile(n,this.gl.FRAGMENT_SHADER);if(this.id=this.gl.createProgram(),!(!a||!s)){if(!this.id){se("filter: could not create webgl program");return}if(this.gl.attachShader(this.id,a),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),Rb(r,"attribute",this.attribute);for(let i in this.attribute)this.attribute[i]=this.gl.getAttribLocation(this.id,i);Rb(r,"uniform",this.uniform),Rb(n,"uniform",this.uniform);for(let i in this.uniform)this.uniform[i]=this.gl.getUniformLocation(this.id,i)}}};function gN(){let e=0,t=null,r=!1,n=-1,a=[null,null],s=[],i=null,o=null,l=Kr(100,100),u={},d={INTERMEDIATE:1},h=l.getContext("webgl");if(!h){se("filter: cannot get webgl context");return}this.gl=h;function p(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=h.createBuffer(),h.bindBuffer(h.ARRAY_BUFFER,i),h.bufferData(h.ARRAY_BUFFER,b,h.STATIC_DRAW),h.pixelStorei(h.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0)}h.viewport(0,0,l.width,l.height),a=[null,null]}}function c(A,x){let b=h.createFramebuffer();h.bindFramebuffer(h.FRAMEBUFFER,b);let v=h.createRenderbuffer();h.bindRenderbuffer(h.RENDERBUFFER,v);let S=h.createTexture();return h.bindTexture(h.TEXTURE_2D,S),h.texImage2D(h.TEXTURE_2D,0,h.RGBA,A,x,0,h.RGBA,h.UNSIGNED_BYTE,null),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_MAG_FILTER,h.LINEAR),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_MIN_FILTER,h.LINEAR),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),h.framebufferTexture2D(h.FRAMEBUFFER,h.COLOR_ATTACHMENT0,h.TEXTURE_2D,S,0),h.bindTexture(h.TEXTURE_2D,null),h.bindFramebuffer(h.FRAMEBUFFER,null),{fbo:b,texture:S}}function f(A){return a[A]=a[A]||c(l.width,l.height),a[A]}function m(A=0){if(!o)return;let x=null,b=null,v=!1;e===0?x=t:x=f(n).texture||null,e++,r&&!(A&d.INTERMEDIATE)?(b=null,v=e%2===0):(n=(n+1)%2,b=f(n).fbo||null),h.bindTexture(h.TEXTURE_2D,x),h.bindFramebuffer(h.FRAMEBUFFER,b),h.uniform1f(o.uniform.flipY,v?-1:1),h.drawArrays(h.TRIANGLES,0,6)}function g(A){if(u[A])return o=u[A],h.useProgram((o?o.id:null)||null),o;if(o=new Mb(h,dN,A),!o)return se("filter: could not get webgl program"),null;let x=Float32Array.BYTES_PER_ELEMENT,b=4*x;return h.enableVertexAttribArray(o.attribute.pos),h.vertexAttribPointer(o.attribute.pos,2,h.FLOAT,!1,b,0*x),h.enableVertexAttribArray(o.attribute.uv),h.vertexAttribPointer(o.attribute.uv,2,h.FLOAT,!1,b,2*x),u[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?hN:pN,v=g(b);!v||(h.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,S=.715,T=.072;y.colorMatrix([v+x*(1-v)+b*-v,S+x*-S+b*-S,T+x*-T+b*(1-T),0,0,v+x*-v+b*.143,S+x*(1-S)+b*.14,T+x*-T+b*-.283,0,0,v+x*-v+b*-(1-v),S+x*-S+b*S,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,S=g(mN);!S||(h.uniform1fv(S.uniform.m,x),h.uniform2f(S.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(fN);!v||(h.uniform2f(v.uniform.px,0,b),m(d.INTERMEDIATE),h.uniform2f(v.uniform.px,x,0),m())},pixelate:A=>{let x=A/l.width,b=A/l.height,v=g(cN);!v||(h.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){p(A.width,A.height),e=0,t||(t=h.createTexture()),h.bindTexture(h.TEXTURE_2D,t),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_S,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_WRAP_T,h.CLAMP_TO_EDGE),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_MIN_FILTER,h.NEAREST),h.texParameteri(h.TEXTURE_2D,h.TEXTURE_MAG_FILTER,h.NEAREST),h.texImage2D(h.TEXTURE_2D,0,h.RGBA,h.RGBA,h.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 C0(e){let t=e.shape.length===4?rt(e):e,r=Xt(t,3,2),n=[Ds(r[0]),Ds(r[1]),Ds(r[2])],a=[gr(r[0]),gr(r[1]),gr(r[2])],s=await Promise.all(a.map(c=>c.data())),i=.99*Math.max(s[0][0],s[1][0],s[2][0]),o=[ce(r[0],n[0]),ce(r[1],n[1]),ce(r[2],n[2])],l=[ce(a[0],n[0]),ce(a[1],n[1]),ce(a[2],n[2])],u=[pe(i,l[0]),pe(i,l[1]),pe(i,l[2])],d=[L(o[0],u[0]),L(o[1],u[1]),L(o[2],u[2])],h=lr([d[0],d[1],d[2]],2),p=G(h,[1,t.shape[0],t.shape[1],3]);return re([...r,...n,...a,...o,...l,...u,...d,h,t]),p}var E0=2048,ut=null,Jt=null,Md=null,Nt,os={inputSum:0,cacheDiff:1,sumMethod:0,inputTensor:void 0};function Kr(e,t){let r;if(he.browser)if(he.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 he.Canvas!="undefined"?r=new he.Canvas(e,t):typeof globalThis.Canvas!="undefined"&&(r=new globalThis.Canvas(e,t));return r}function R0(e,t){let r=t||Kr(e.width,e.height);return r.getContext("2d").drawImage(e,0,0),r}async function Fd(e,t,r=!0){if(!e)return t.debug&&se("input error: input is missing"),{tensor:null,canvas:null};if(!(e instanceof nt)&&!(typeof Image!="undefined"&&e instanceof Image)&&!(typeof he.Canvas!="undefined"&&e instanceof he.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 nt){let n=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)n=qt(e,0);else if(e.shape[2]===4){let a=Ml(e,[0,0,0],[-1,-1,3]);n=qt(a,0),re(a)}}else e.shape.length===4&&(e.shape[3]===3?n=Br(e):e.shape[3]===4&&(n=$o(e,[0,0,0,0],[-1,-1,-1,3])));if(n==null||n.shape.length!==4||n.shape[0]!==1||n.shape[3]!==3)throw new Error(`input error: attempted to use tensor with unrecognized shape: ${e.shape}`);if(n.dtype==="int32"){let a=me(n,"float32");re(n),n=a}return{tensor:n,canvas:t.filter.return?Jt:null}}else{if(typeof e.readyState!="undefined"&&e.readyState<=2)return t.debug&&se("input stream is not ready"),{tensor:null,canvas:ut};let n=e.naturalWidth||e.videoWidth||e.width||e.shape&&e.shape[1]>0,a=e.naturalHeight||e.videoHeight||e.height||e.shape&&e.shape[2]>0;if(!n||!a)return t.debug&&se("cannot determine input dimensions"),{tensor:null,canvas:ut};let s=n,i=a;if(s>E0&&(s=E0,i=Math.trunc(s*a/n)),i>E0&&(i=E0,s=Math.trunc(i*n/a)),(t.filter.width||0)>0?s=t.filter.width:(t.filter.height||0)>0&&(s=n*((t.filter.height||0)/a)),(t.filter.height||0)>0?i=t.filter.height:(t.filter.width||0)>0&&(i=a*((t.filter.width||0)/n)),!s||!i)throw new Error("input error: cannot determine dimension");(!ut||(ut==null?void 0:ut.width)!==s||(ut==null?void 0:ut.height)!==i)&&(ut=Kr(s,i));let o=ut.getContext("2d");if(typeof ImageData!="undefined"&&e instanceof ImageData?o.putImageData(e,0,0):t.filter.flip&&typeof o.translate!="undefined"?(o.translate(n,0),o.scale(-1,1),o.drawImage(e,0,0,n,a,0,0,ut==null?void 0:ut.width,ut==null?void 0:ut.height),o.setTransform(1,0,0,1,0,0)):o.drawImage(e,0,0,n,a,0,0,ut==null?void 0:ut.width,ut==null?void 0:ut.height),(!Jt||ut.width!==Jt.width||(ut==null?void 0:ut.height)!==(Jt==null?void 0:Jt.height))&&(Jt=Kr(ut.width,ut.height)),t.filter.enabled&&he.webgl.supported?(Nt||(Nt=he.browser?new gN:null),he.filter=!!Nt,!Nt||!Nt.add?(t.debug&&se("input process error: cannot initialize filters"),he.webgl.supported=!1,t.filter.enabled=!1,R0(ut,Jt)):(Nt.reset(),t.filter.brightness!==0&&Nt.add("brightness",t.filter.brightness),t.filter.contrast!==0&&Nt.add("contrast",t.filter.contrast),t.filter.sharpness!==0&&Nt.add("sharpen",t.filter.sharpness),t.filter.blur!==0&&Nt.add("blur",t.filter.blur),t.filter.saturation!==0&&Nt.add("saturation",t.filter.saturation),t.filter.hue!==0&&Nt.add("hue",t.filter.hue),t.filter.negative&&Nt.add("negative"),t.filter.sepia&&Nt.add("sepia"),t.filter.vintage&&Nt.add("brownie"),t.filter.sepia&&Nt.add("sepia"),t.filter.kodachrome&&Nt.add("kodachrome"),t.filter.technicolor&&Nt.add("technicolor"),t.filter.polaroid&&Nt.add("polaroid"),t.filter.pixelate!==0&&Nt.add("pixelate",t.filter.pixelate),Nt.get()>0?Jt=Nt.apply(ut):Jt=Nt.draw(ut))):(R0(ut,Jt),Nt&&(Nt=null),he.filter=!!Nt),!r)return{tensor:null,canvas:Jt};if(!Jt)throw new Error("canvas error: cannot create output");let l,u=3;if(typeof ImageData!="undefined"&&e instanceof ImageData||e.data&&e.width&&e.height)if(he.browser&&_n)l=_n?_n.fromPixels(e):null;else{u=e.data.length/e.height/e.width;let p=new Uint8Array(e.data.buffer);l=ct(p,[e.height,e.width,u],"int32")}else if((!Md||Jt.width!==Md.width||Jt.height!==Md.height)&&(Md=Kr(Jt.width,Jt.height)),_n&&he.browser)t.backend==="webgl"||t.backend==="humangl"||t.backend==="webgpu"?l=_n.fromPixels(Jt):(Md=R0(Jt),l=_n.fromPixels(Md));else{let f=R0(Jt).getContext("2d").getImageData(0,0,s,i);u=f.data.length/s/i;let m=new Uint8Array(f.data.buffer);l=ct(m,[s,i,u])}if(u===4){let p=Ml(l,[0,0,0],[-1,-1,3]);re(l),l=p}if(!l)throw new Error("input error: cannot create tensor");let d=me(l,"float32"),h=t.filter.equalization?await C0(d):qt(d,0);return re([l,d]),{tensor:h,canvas:t.filter.return?Jt:null}}}async function yN(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(!os.inputTensor)os.inputTensor=Br(t);else if(os.inputTensor.shape[1]!==t.shape[1]||os.inputTensor.shape[2]!==t.shape[2])re(os.inputTensor),os.inputTensor=Br(t);else{let n={};n.diff=ce(t,os.inputTensor),n.squared=L(n.diff,n.diff),n.sum=ke(n.squared);let s=(await n.sum.data())[0]/(t.shape[1]||1)/(t.shape[2]||1)/255/3;re([os.inputTensor,n.diff,n.squared,n.sum]),os.inputTensor=Br(t),r=s<=(e.cacheSensitivity||0)}return r}async function AN(e,t,r){let n={};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;n.input1=Br(t),n.input2=t.shape[1]!==r.shape[1]||t.shape[2]!==r.shape[2]?Ie.resizeBilinear(r,[t.shape[1],t.shape[2]]):Br(r),n.diff=ce(n.input1,n.input2),n.squared=L(n.diff,n.diff),n.sum=ke(n.squared);let s=(await n.sum.data())[0]/(t.shape[1]||1)/(t.shape[2]||1)/255/3;return re([n.input1,n.input2,n.diff,n.squared,n.sum]),s}var Fb=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:Hh["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(nr().registryFactory),this.wasm.supported=typeof WebAssembly!="undefined",this.wasm.backend=this.backends.includes("wasm"),this.wasm.supported&&this.wasm.backend&&Ur()==="wasm"&&(this.wasm.simd=await Y().getAsync("WASM_HAS_SIMD_SUPPORT"),this.wasm.multithread=await Y().getAsync("WASM_HAS_MULTITHREAD_SUPPORT"));let t=Kr(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&&(Ur()==="webgl"||Ur()==="humangl")){let n=zn().gpgpu!=="undefined"?await zn().getGPGPUContext().gl:null;n&&(this.webgl.version=n.getParameter(n.VERSION),this.webgl.renderer=n.getParameter(n.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(n){this.webgpu.supported=!1}try{this.kernels=Ra(Ur()).map(n=>n.kernelName.toLowerCase())}catch(n){}}async updateCPU(){let t={model:"",flags:[]};this.node&&this.platform.startsWith("linux"),this.cpu?this.cpu=t:Object.defineProperty(this,"cpu",{value:t})}},he=new Fb;var ls={cacheModels:!1,verbose:!0,debug:!1,modelBasePath:""};async function k2e(e,t){return ls.debug&&se("load model fetch:",e,t),fetch(e,t)}function xN(e){ls.cacheModels=e.cacheModels,ls.verbose=e.debug,ls.modelBasePath=e.modelBasePath}async function Ge(e){let t=R3(ls.modelBasePath,e||""),r=t.split("/"),n="indexeddb://"+r[r.length-1].replace(".json",""),a=await Tr.listModels(),s=ls.cacheModels&&Object.keys(a).includes(n),i=typeof fetch=="undefined"?{}:{fetchFunc:(u,d)=>k2e(u,d)},o=new m0(s?n:t,i),l=!1;try{o.findIOHandler(),ls.debug&&se("model load handler:",o.handler);let u=await o.handler.load();o.loadSync(u),ls.verbose&&se("load model:",o.modelUrl),l=!0}catch(u){se("error loading model:",t,u)}if(l&&ls.cacheModels&&!s)try{let u=await o.save(n);se("model saved:",n,u)}catch(u){se("error saving model:",t,u)}return o}var $b="2.7.0";var pg={};bs(pg,{Models:()=>rc,load:()=>H5,reset:()=>dg,validate:()=>q5});var Zn,Pb=[],T2e=["white","black","asian","indian","other"],N2e=[15,23,28,35.5,45.5,55.5,65],bN=0,vN=0,_b=Number.MAX_SAFE_INTEGER;async function wN(e){return he.initial&&(Zn=null),Zn?e.debug&&se("cached model:",Zn.modelUrl):Zn=await Ge(e.face.gear),Zn}async function zb(e,t,r,n){var i,o;if(!Zn)return{age:0,gender:"unknown",genderScore:0,race:[]};let a=_b<(((i=t.face.gear)==null?void 0:i.skipFrames)||0),s=(((o=t.face.gear)==null?void 0:o.skipTime)||0)>oe()-vN;return t.skipAllowed&&s&&a&&bN===n&&Pb[r]?(_b++,Pb[r]):(_b=0,new Promise(async l=>{var y,A;if(!(Zn!=null&&Zn.inputs[0].shape))return;let u={},d=[[0,.1,.9,.9]];u.resize=Ie.cropAndResize(e,d,[0],[Zn.inputs[0].shape[2],Zn.inputs[0].shape[1]]);let h={age:0,gender:"unknown",genderScore:0,race:[]};(y=t.face.gear)!=null&&y.enabled&&([u.age,u.gender,u.race]=Zn.execute(u.resize,["age_output","gender_output","race_output"]));let p=await u.gender.data();h.gender=p[0]>p[1]?"male":"female",h.genderScore=Math.round(100*(p[0]>p[1]?p[0]:p[1]))/100;let c=await u.race.data();for(let x=0;x<c.length;x++)c[x]>(((A=t.face.gear)==null?void 0:A.minConfidence)||.2)&&h.race.push({score:Math.round(100*c[x])/100,race:T2e[x]});h.race.sort((x,b)=>b.score-x.score);let m=Array.from(await u.age.data()).map((x,b)=>[N2e[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);h.age=Math.round(10*g)/10,Object.keys(u).forEach(x=>re(u[x])),Pb[r]=h,bN=n,vN=oe(),l(h)}))}var Qe={tf255:255,tf1:1,tf2:2,tf05:.5,tf127:127.5,rgb:[.2989,.587,.114]};function IN(){Qe.tf255=Se(255,"float32"),Qe.tf1=Se(1,"float32"),Qe.tf2=Se(2,"float32"),Qe.tf05=Se(.5,"float32"),Qe.tf127=Se(127.5,"float32"),Qe.rgb=St([.2989,.587,.114],"float32")}var mn,M0=[],SN=0,TN=0,Ob=Number.MAX_SAFE_INTEGER;async function NN(e){return he.initial&&(mn=null),mn?e.debug&&se("cached model:",mn.modelUrl):mn=await Ge(e.face.ssrnet.modelPathAge),mn}async function Db(e,t,r,n){var i,o,l,u;if(!mn)return{age:0};let a=Ob<(((i=t.face.ssrnet)==null?void 0:i.skipFrames)||0),s=(((o=t.face.ssrnet)==null?void 0:o.skipTime)||0)>oe()-TN;return t.skipAllowed&&a&&s&&SN===n&&((l=M0[r])==null?void 0:l.age)&&((u=M0[r])==null?void 0:u.age)>0?(Ob++,M0[r]):(Ob=0,new Promise(async d=>{if(!(mn!=null&&mn.inputs)||!mn.inputs[0]||!mn.inputs[0].shape)return;let h={};h.resize=Ie.resizeBilinear(e,[mn.inputs[0].shape[2],mn.inputs[0].shape[1]],!1),h.enhance=L(h.resize,Qe.tf255);let p={age:0};if(t.face.ssrnet.enabled&&(h.age=mn.execute(h.enhance)),h.age){let c=await h.age.data();p.age=Math.trunc(10*c[0])/10}Object.keys(h).forEach(c=>re(h[c])),M0[r]=p,SN=n,TN=oe(),d(p)}))}var Yn,F0=[],EN=0,RN=0,Lb=Number.MAX_SAFE_INTEGER,Bb=[.2989,.587,.114];async function MN(e){return he.initial&&(Yn=null),Yn?e.debug&&se("cached model:",Yn.modelUrl):Yn=await Ge(e.face.ssrnet.modelPathGender),Yn}async function Wb(e,t,r,n){var i,o,l,u;if(!Yn)return{gender:"unknown",genderScore:0};let a=Lb<(((i=t.face.ssrnet)==null?void 0:i.skipFrames)||0),s=(((o=t.face.ssrnet)==null?void 0:o.skipTime)||0)>oe()-RN;return t.skipAllowed&&a&&s&&EN===n&&((l=F0[r])==null?void 0:l.gender)&&((u=F0[r])==null?void 0:u.genderScore)>0?(Lb++,F0[r]):(Lb=0,new Promise(async d=>{if(!(Yn!=null&&Yn.inputs[0].shape))return;let h={};h.resize=Ie.resizeBilinear(e,[Yn.inputs[0].shape[2],Yn.inputs[0].shape[1]],!1),h.enhance=K(()=>{let[f,m,g]=Xt(h.resize,3,3),y=L(f,Bb[0]),A=L(m,Bb[1]),x=L(g,Bb[2]),b=bm([y,A,x]);return L(ce(b,Qe.tf05),2)});let p={gender:"unknown",genderScore:0};t.face.ssrnet.enabled&&(h.gender=Yn.execute(h.enhance));let c=await h.gender.data();p.gender=c[0]>c[1]?"female":"male",p.genderScore=c[0]>c[1]?Math.trunc(100*c[0])/100:Math.trunc(100*c[1])/100,Object.keys(h).forEach(f=>re(h[f])),F0[r]=p,EN=n,RN=oe(),d(p)}))}var Rr,$0=[],Vb=Number.MAX_SAFE_INTEGER,$N=0,PN=0;async function _N(e){var t;return he.initial&&(Rr=null),Rr?e.debug&&se("cached model:",Rr.modelUrl):Rr=await Ge((t=e.face.antispoof)==null?void 0:t.modelPath),Rr}async function Ub(e,t,r,n){var i,o;if(!Rr)return 0;let a=(((i=t.face.antispoof)==null?void 0:i.skipTime)||0)>oe()-PN,s=Vb<(((o=t.face.antispoof)==null?void 0:o.skipFrames)||0);return t.skipAllowed&&a&&s&&$N===n&&$0[r]?(Vb++,$0[r]):(Vb=0,new Promise(async l=>{let u=Ie.resizeBilinear(e,[Rr!=null&&Rr.inputs[0].shape?Rr.inputs[0].shape[2]:0,Rr!=null&&Rr.inputs[0].shape?Rr.inputs[0].shape[1]:0],!1),d=Rr==null?void 0:Rr.execute(u),h=(await d.data())[0];$0[r]=Math.round(100*h)/100,$N=n,PN=oe(),re([u,d]),l($0[r])}))}var Jn={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]},Gb={count:468,mouth:13,symmetryLine:[13,Jn.midwayBetweenEyes[0]]},Kh={leftEye:0,rightEye:1,nose:2,mouth:3,leftEar:4,rightEar:5,symmetryLine:[3,2]},jb=[{key:"EyeUpper0",indices:[9,10,11,12,13,14,15]},{key:"EyeUpper1",indices:[25,26,27,28,29,30,31]},{key:"EyeUpper2",indices:[41,42,43,44,45,46,47]},{key:"EyeLower0",indices:[0,1,2,3,4,5,6,7,8]},{key:"EyeLower1",indices:[16,17,18,19,20,21,22,23,24]},{key:"EyeLower2",indices:[32,33,34,35,36,37,38,39,40]},{key:"EyeLower3",indices:[54,55,56,57,58,59,60,61,62]},{key:"EyebrowUpper",indices:[63,64,65,66,67,68,69,70]},{key:"EyebrowLower",indices:[48,49,50,51,52,53]}],Xh=[[.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]],Dl=[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 E2e=[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],R2e=[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],M2e=[33,133,362,263,1,78,308],d7e=E2e.map(e=>Xh[e]),p7e=R2e.map(e=>Xh[e]),h7e=M2e.map(e=>Xh[e]);var $d=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],Xb=(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],Zb=(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],LN=(e,t)=>{let r=[e.startPoint[0]*t[0],e.startPoint[1]*t[1]],n=[e.endPoint[0]*t[0],e.endPoint[1]*t[1]];return{startPoint:r,endPoint:n,landmarks:e.landmarks,confidence:e.confidence}},qb=(e,t,r)=>{let n=t.shape[1],a=t.shape[2],s=[e.startPoint[1]/n,e.startPoint[0]/a,e.endPoint[1]/n,e.endPoint[0]/a],i=Ie.cropAndResize(t,[s],[0],r),o=pe(i,Qe.tf255);return re(i),o},_0=(e,t)=>{let r=P0(e),n=$d(e),a=[t*n[0]/2,t*n[1]/2];return{startPoint:[r[0]-a[0],r[1]-a[1]],endPoint:[r[0]+a[0],r[1]+a[1]],landmarks:e.landmarks,confidence:e.confidence}},z0=e=>{let t=P0(e),r=$d(e),n=Math.max(...r)/2;return{startPoint:[Math.round(t[0]-n),Math.round(t[1]-n)],endPoint:[Math.round(t[0]+n),Math.round(t[1]+n)],landmarks:e.landmarks,confidence:e.confidence}},BN=e=>{let t=e.map(n=>n[0]),r=e.map(n=>n[1]);return{startPoint:[Math.min(...t),Math.min(...r)],endPoint:[Math.max(...t),Math.max(...r)],landmarks:e}},Kb=[[1,0,0],[0,1,0],[0,0,1]],F2e=e=>e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI)),$2e=(e,t)=>F2e(Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]));var ON=(e,t)=>[[1,0,e],[0,1,t],[0,0,1]],Ll=(e,t)=>{let r=0;for(let n=0;n<e.length;n++)r+=e[n]*t[n];return r},P2e=(e,t)=>{let r=[];for(let n=0;n<e.length;n++)r.push(e[n][t]);return r},DN=(e,t)=>{let r=[],n=e.length;for(let a=0;a<n;a++){r.push([]);for(let s=0;s<n;s++)r[a].push(Ll(e[a],P2e(t,s)))}return r},WN=(e,t)=>{let r=Math.cos(e),n=Math.sin(e),a=[[r,-n,0],[n,r,0],[0,0,1]],s=ON(t[0],t[1]),i=DN(s,a),o=ON(-t[0],-t[1]);return DN(i,o)},_2e=e=>{let t=[[e[0][0],e[1][0]],[e[0][1],e[1][1]]],r=[e[0][2],e[1][2]],n=[-Ll(t[0],r),-Ll(t[1],r)];return[t[0].concat(n[0]),t[1].concat(n[1]),[0,0,1]]},z2e=(e,t)=>[Ll(e,t[0]),Ll(e,t[1])];function VN(e){let t={strides:[e/16,e/8],anchors:[2,6]},r=[];for(let n=0;n<t.strides.length;n++){let a=t.strides[n],s=Math.floor((e+a-1)/a),i=Math.floor((e+a-1)/a),o=t.anchors[n];for(let l=0;l<s;l++){let u=a*(l+.5);for(let d=0;d<i;d++){let h=a*(d+.5);for(let p=0;p<o;p++)r.push([h,u])}}}return r}function UN(e,t,r,n,a){let s=$d(t),i=e.map(c=>[s[0]/a*(c[0]-a/2),s[1]/a*(c[1]-a/2),c[2]||0]),o=r&&r!==0&&Math.abs(r)>.2,l=o?WN(r,[0,0]):Kb,u=o?i.map(c=>[...z2e(c,l),c[2]]):i,d=o?_2e(n):Kb,h=P0(t),p=[Ll(h,d[0]),Ll(h,d[1])];return u.map(c=>[Math.trunc(c[0]+p[0]),Math.trunc(c[1]+p[1]),Math.trunc(c[2]||0)])}function GN(e,t,r,n){let a=t.landmarks.length>=Gb.count?Gb.symmetryLine:Kh.symmetryLine,s=0,i=Kb,o;if(e&&he.kernels.includes("rotatewithoffset"))if(s=$2e(t.landmarks[a[0]],t.landmarks[a[1]]),s&&s!==0&&Math.abs(s)>.2){let u=P0(t),d=[u[0]/r.shape[2],u[1]/r.shape[1]],h=Ie.rotateWithOffset(r,s,0,d);i=WN(-s,u),o=qb(t,h,[n,n]),re(h)}else o=qb(t,r,[n,n]);else o=qb(t,r,[n,n]);return[s,i,o]}var O2e=e=>{let t=e.map(n=>n[0]),r=e.map(n=>n[1]);return[Math.min(...t)+(Math.max(...t)-Math.min(...t))/2,Math.min(...r)+(Math.max(...r)-Math.min(...r))/2]},jN=(e,t)=>{let r=O2e(e),n=$d(t);return{startPoint:[r[0]-n[0]/2,r[1]-n[1]/2],endPoint:[r[0]+n[0]/2,r[1]+n[1]/2]}};var HN=6,D2e=1.4,Oa,qN=null,Ki=0,Zh=null,O0=()=>Ki;async function KN(e){var t;return he.initial&&(Oa=null),Oa?e.debug&&se("cached model:",Oa.modelUrl):Oa=await Ge((t=e.face.detector)==null?void 0:t.modelPath),Ki=Oa.inputs[0].shape?Oa.inputs[0].shape[2]:0,Zh=Se(Ki,"int32"),qN=pa(VN(Ki)),Oa}function L2e(e){let t={};t.boxStarts=Pe(e,[0,1],[-1,2]),t.centers=le(t.boxStarts,qN),t.boxSizes=Pe(e,[0,3],[-1,2]),t.boxSizesNormalized=pe(t.boxSizes,Zh),t.centersNormalized=pe(t.centers,Zh),t.halfBoxSize=pe(t.boxSizesNormalized,Qe.tf2),t.starts=ce(t.centersNormalized,t.halfBoxSize),t.ends=le(t.centersNormalized,t.halfBoxSize),t.startNormalized=L(t.starts,Zh),t.endNormalized=L(t.ends,Zh);let r=ud([t.startNormalized,t.endNormalized],1);return Object.keys(t).forEach(n=>re(t[n])),r}async function XN(e,t){var o,l,u,d;if(!e||e.isDisposedInternal||e.shape.length!==4||e.shape[1]<1||e.shape[2]<1)return[];let r={};r.resized=Ie.resizeBilinear(e,[Ki,Ki]),r.div=pe(r.resized,Qe.tf127),r.normalized=ce(r.div,Qe.tf05);let n=Oa==null?void 0:Oa.execute(r.normalized);if(Array.isArray(n)){let h=n.sort((p,c)=>p.size-c.size);r.concat384=kt([h[0],h[2]],2),r.concat512=kt([h[1],h[3]],2),r.concat=kt([r.concat512,r.concat384],1),r.batch=rt(r.concat,0)}else r.batch=rt(n);re(n),r.boxes=L2e(r.batch),r.logits=Pe(r.batch,[0,0],[-1,1]),r.sigmoid=Nr(r.logits),r.scores=rt(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,((u=t.face.detector)==null?void 0:u.minConfidence)||0);let a=await r.nms.array(),s=[],i=await r.scores.data();for(let h=0;h<a.length;h++){let p=i[a[h]];if(p>(((d=t.face.detector)==null?void 0:d.minConfidence)||0)){let c={};c.bbox=Pe(r.boxes,[a[h],0],[1,-1]),c.slice=Pe(r.batch,[a[h],HN-1],[1,-1]),c.squeeze=rt(c.slice),c.landmarks=G(c.squeeze,[HN,-1]);let f=await c.bbox.data(),m={startPoint:[f[0],f[1]],endPoint:[f[2],f[3]],landmarks:await c.landmarks.array(),confidence:p},g=LN(m,[(e.shape[2]||0)/Ki,(e.shape[1]||0)/Ki]),y=_0(g,t.face.scale||D2e),A=z0(y);s.push(A),Object.keys(c).forEach(x=>re(c[x]))}}return Object.keys(r).forEach(h=>re(r[h])),s}var D0={};bs(D0,{connected:()=>Qb,kpt:()=>Jb});var Jb=["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"],Qb={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 YN=224,B2e,W2e=5,L0=[8,16,32,32,32];async function JN(){let e=[],t=0;for(;t<W2e;){let r=0,n=t;for(;n<L0.length&&L0[n]===L0[t];)r+=2,n++;let a=L0[t],s=Math.ceil(YN/a),i=Math.ceil(YN/a);for(let o=0;o<s;++o)for(let l=0;l<i;++l)for(let u=0;u<r;++u)e.push({x:(l+.5)/i,y:(o+.5)/s});t=n}B2e={x:St(e.map(r=>r.x)),y:St(e.map(r=>r.y))}}function us(e,t=[1,1]){let r=[e.map(o=>o[0]),e.map(o=>o[1])],n=[Math.min(...r[0]),Math.min(...r[1])],a=[Math.max(...r[0]),Math.max(...r[1])],s=[n[0],n[1],a[0]-n[0],a[1]-n[1]],i=[s[0]/t[0],s[1]/t[1],s[2]/t[0],s[3]/t[1]];return{box:s,boxRaw:i}}function QN(e,t=[1,1]){let r=[e.map(u=>u[0]),e.map(u=>u[1])],n=[Math.min(...r[0]),Math.min(...r[1])],a=[Math.max(...r[0]),Math.max(...r[1])],s=[(n[0]+a[0])/2,(n[1]+a[1])/2],i=Math.max(s[0]-n[0],s[1]-n[1],-s[0]+a[0],-s[1]+a[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 B0(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 rC={initial:!0},gn={detector:null,landmarks:null},Pd={detector:[224,224],landmarks:[256,256]},e5=Number.MAX_SAFE_INTEGER,U2e={landmarks:["ld_3d","activation_segmentation","activation_heatmap","world_3d","output_poseflag"],detector:[]},V0=null,Yh,Xi=[[0,0],[0,0],[0,0],[0,0]],eC=0,tC=e=>1-1/(1+Math.exp(e));async function nC(e){if(rC.initial&&(gn.detector=null),!gn.detector&&e.body.detector&&e.body.detector.modelPath){gn.detector=await Ge(e.body.detector.modelPath);let t=Object.values(gn.detector.modelSignature.inputs);Pd.detector[0]=Array.isArray(t)?parseInt(t[0].tensorShape.dim[1].size):0,Pd.detector[1]=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):0}else e.debug&&gn.detector&&se("cached model:",gn.detector.modelUrl);return await JN(),gn.detector}async function aC(e){if(rC.initial&&(gn.landmarks=null),gn.landmarks)e.debug&&se("cached model:",gn.landmarks.modelUrl);else{gn.landmarks=await Ge(e.body.modelPath);let t=Object.values(gn.landmarks.modelSignature.inputs);Pd.landmarks[0]=Array.isArray(t)?parseInt(t[0].tensorShape.dim[1].size):0,Pd.landmarks[1]=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):0}return gn.landmarks}async function G2e(e,t){let r={};if(!e.shape||!e.shape[1]||!e.shape[2])return e;let n;if(Yh&&(r.cropped=Ie.cropAndResize(e,[Yh],[0],[e.shape[1],e.shape[2]])),e.shape[1]!==e.shape[2]){let a=[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];Xi=[[0,0],a,s,[0,0]],r.pad=Hn(r.cropped||e,Xi),r.resize=Ie.resizeBilinear(r.pad,[t,t]),n=pe(r.resize,Qe.tf255)}else e.shape[1]!==t?(r.resize=Ie.resizeBilinear(r.cropped||e,[t,t]),n=pe(r.resize,Qe.tf255)):n=pe(r.cropped||e,Qe.tf255);return Object.keys(r).forEach(a=>re(r[a])),n}function j2e(e,t){for(let r of e)r.position=[Math.trunc(r.position[0]*(t[0]+Xi[2][0]+Xi[2][1])/t[0]-Xi[2][0]),Math.trunc(r.position[1]*(t[1]+Xi[1][0]+Xi[1][1])/t[1]-Xi[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(Yh)for(let r of e)r.positionRaw=[r.positionRaw[0]+Yh[1],r.positionRaw[1]+Yh[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 H2e(e){let t=e.find(o=>o.part==="leftPalm"),r=e.find(o=>o.part==="leftWrist"),n=e.find(o=>o.part==="leftIndex");t.position[2]=((r.position[2]||0)+(n.position[2]||0))/2;let a=e.find(o=>o.part==="rightPalm"),s=e.find(o=>o.part==="rightWrist"),i=e.find(o=>o.part==="rightIndex");a.position[2]=((s.position[2]||0)+(i.position[2]||0))/2}async function q2e(e,t,r){var f;let n={};[n.ld,n.segmentation,n.heatmap,n.world,n.poseflag]=(f=gn.landmarks)==null?void 0:f.execute(e,U2e.landmarks);let a=(await n.poseflag.data())[0],s=await n.ld.data(),i=await n.world.data();Object.keys(n).forEach(m=>re(n[m]));let o=[],l=5;for(let m=0;m<s.length/l;m++){let g=tC(s[l*m+3]),y=tC(s[l*m+4]),A=Math.trunc(100*g*y*a)/100,x=[s[l*m+0]/Pd.landmarks[0],s[l*m+1]/Pd.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:Jb[m],positionRaw:x,position:b,distance:v,score:A})}if(a<(t.body.minConfidence||0))return null;H2e(o);let u=j2e(o,r),d=u.map(m=>m.position),h=us(d,[r[0],r[1]]),p={};for(let[m,g]of Object.entries(Qb)){let y=[];for(let A=0;A<g.length-1;A++){let x=u.find(v=>v.part===g[A]),b=u.find(v=>v.part===g[A+1]);x&&b&&y.push([x.position,b.position])}p[m]=y}return{id:0,score:Math.trunc(100*a)/100,box:h.box,boxRaw:h.boxRaw,keypoints:u,annotations:p}}async function t5(e,t){let r=[e.shape[2]||0,e.shape[1]||0],n=(t.body.skipTime||0)>oe()-eC,a=e5<(t.body.skipFrames||0);if(t.skipAllowed&&n&&a&&V0!==null)e5++;else{let s={};s.landmarks=await G2e(e,256),V0=await q2e(s.landmarks,t,r),Object.keys(s).forEach(i=>re(s[i])),eC=oe(),e5=0}return V0?[V0]:[]}var _d=[{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 ds,Bl=0,r5=[],iC=0,n5=Number.MAX_SAFE_INTEGER;async function oC(e){if(he.initial&&(ds=null),ds)e.debug&&se("cached model:",ds.modelUrl);else{ds=await Ge(e.object.modelPath);let t=Object.values(ds.modelSignature.inputs);Bl=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):0}return ds}async function K2e(e,t,r){if(!e)return[];let n={},a=[],s=await e.array();n.squeeze=rt(e);let i=Xt(n.squeeze,6,1);n.stack=lr([i[1],i[0],i[3],i[2]],1),n.boxes=rt(n.stack),n.scores=rt(i[4]),n.classes=rt(i[5]),re([e,...i]),n.nms=await Ie.nonMaxSuppressionAsync(n.boxes,n.scores,r.object.maxDetected,r.object.iouThreshold,r.object.minConfidence||0);let o=await n.nms.data(),l=0;for(let u of Array.from(o)){let d=Math.trunc(100*s[0][u][4])/100,h=s[0][u][5],p=_d[h].label,[c,f]=[s[0][u][0]/Bl,s[0][u][1]/Bl],m=[c,f,s[0][u][2]/Bl-c,s[0][u][3]/Bl-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])];a.push({id:l++,score:d,class:h,label:p,box:g,boxRaw:m})}return Object.keys(n).forEach(u=>re(n[u])),a}async function a5(e,t){let r=(t.object.skipTime||0)>oe()-iC,n=n5<(t.object.skipFrames||0);return t.skipAllowed&&r&&n&&r5.length>0?(n5++,r5):(n5=0,new Promise(async a=>{let s=[e.shape[2]||0,e.shape[1]||0],i=Ie.resizeBilinear(e,[Bl,Bl]),o=t.object.enabled?ds==null?void 0:ds.execute(i,["tower_0/detections"]):null;iC=oe(),re(i);let l=await K2e(o,s,t);r5=l,a(l)}))}var U0={};bs(U0,{connected:()=>i5,kpt:()=>s5});var s5=["head","neck","rightShoulder","rightElbow","rightWrist","chest","leftShoulder","leftElbow","leftWrist","bodyCenter","rightHip","rightKnee","rightAnkle","leftHip","leftKnee","leftAnkle"],i5={leftLeg:["leftHip","leftKnee","leftAnkle"],rightLeg:["rightHip","rightKnee","rightAnkle"],torso:["leftShoulder","rightShoulder","rightHip","leftHip","leftShoulder"],leftArm:["leftShoulder","leftElbow","leftWrist"],rightArm:["rightShoulder","rightElbow","rightWrist"],head:[]};var Mr,uC=0,Xr={id:0,keypoints:[],box:[0,0,0,0],boxRaw:[0,0,0,0],score:0,annotations:{}},o5=Number.MAX_SAFE_INTEGER;async function dC(e){return he.initial&&(Mr=null),Mr?e.debug&&se("cached model:",Mr.modelUrl):Mr=await Ge(e.body.modelPath),Mr}async function X2e(e,t){let[r,n]=e.shape,a=G(e,[n*r]),s=gr(a,0),i=(await s.data())[0];if(re([a,s]),i>t){let o=Cn(a,0),l=hd(o,r),u=(await l.data())[0],d=pe(o,Se(r,"int32")),h=(await d.data())[0];return re([l,d]),[u,h,i]}return[0,0,i]}async function l5(e,t){let r=(t.body.skipTime||0)>oe()-uC,n=o5<(t.body.skipFrames||0);return t.skipAllowed&&r&&n&&Object.keys(Xr.keypoints).length>0?(o5++,[Xr]):(o5=0,new Promise(async a=>{var h;let s=K(()=>{if(!(Mr!=null&&Mr.inputs[0].shape))return null;let p=Ie.resizeBilinear(e,[Mr.inputs[0].shape[2],Mr.inputs[0].shape[1]],!1),c=L(p,Qe.tf2);return ce(c,Qe.tf1)}),i;if(t.body.enabled&&(i=Mr==null?void 0:Mr.execute(s)),uC=oe(),re(s),i){Xr.keypoints.length=0;let p=i.squeeze();re(i);let c=p.unstack(2);re(p);for(let f=0;f<c.length;f++){let[m,g,y]=await X2e(c[f],t.body.minConfidence);y>(((h=t.body)==null?void 0:h.minConfidence)||0)&&Xr.keypoints.push({score:Math.round(100*y)/100,part:s5[f],positionRaw:[m/Mr.inputs[0].shape[2],g/Mr.inputs[0].shape[1]],position:[Math.round(e.shape[2]*m/Mr.inputs[0].shape[2]),Math.round(e.shape[1]*g/Mr.inputs[0].shape[1])]})}c.forEach(f=>re(f))}Xr.score=Xr.keypoints.reduce((p,c)=>c.score>p?c.score:p,0);let o=Xr.keypoints.map(p=>p.position[0]),l=Xr.keypoints.map(p=>p.position[1]);Xr.box=[Math.min(...o),Math.min(...l),Math.max(...o)-Math.min(...o),Math.max(...l)-Math.min(...l)];let u=Xr.keypoints.map(p=>p.positionRaw[0]),d=Xr.keypoints.map(p=>p.positionRaw[1]);Xr.boxRaw=[Math.min(...u),Math.min(...d),Math.max(...u)-Math.min(...u),Math.max(...d)-Math.min(...d)];for(let[p,c]of Object.entries(i5)){let f=[];for(let m=0;m<c.length-1;m++){let g=Xr.keypoints.find(A=>A.part===c[m]),y=Xr.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])}Xr.annotations[p]=f}a([Xr])}))}var Z2e=["angry","disgust","fear","happy","sad","surprise","neutral"],Dn,G0=[],hC=0,cC=0,u5=Number.MAX_SAFE_INTEGER;async function fC(e){var t;return he.initial&&(Dn=null),Dn?e.debug&&se("cached model:",Dn.modelUrl):Dn=await Ge((t=e.face.emotion)==null?void 0:t.modelPath),Dn}async function d5(e,t,r,n){var i,o;if(!Dn)return[];let a=u5<(((i=t.face.emotion)==null?void 0:i.skipFrames)||0),s=(((o=t.face.emotion)==null?void 0:o.skipTime)||0)>oe()-cC;return t.skipAllowed&&s&&a&&hC===n&&G0[r]&&G0[r].length>0?(u5++,G0[r]):(u5=0,new Promise(async l=>{var d,h;let u=[];if((d=t.face.emotion)!=null&&d.enabled){let p={},c=Dn!=null&&Dn.inputs[0].shape?Dn.inputs[0].shape[2]:0;p.resize=Ie.resizeBilinear(e,[c,c],!1),p.channels=L(p.resize,Qe.rgb),p.grayscale=ke(p.channels,3,!0),p.grayscaleSub=ce(p.grayscale,Qe.tf05),p.grayscaleMul=L(p.grayscaleSub,Qe.tf2),p.emotion=Dn==null?void 0:Dn.execute(p.grayscaleMul),cC=oe();let f=await p.emotion.data();for(let m=0;m<f.length;m++)f[m]>(((h=t.face.emotion)==null?void 0:h.minConfidence)||0)&&u.push({score:Math.min(.99,Math.trunc(100*f[m])/100),emotion:Z2e[m]});u.sort((m,g)=>g.score-m.score),Object.keys(p).forEach(m=>re(p[m]))}G0[r]=u,hC=n,l(u)}))}var yn,p5=[],gC=0,yC=0,AC=Number.MAX_SAFE_INTEGER;async function xC(e){return he.initial&&(yn=null),yn?e.debug&&se("cached model:",yn.modelUrl):yn=await Ge(e.face.mobilefacenet.modelPath),yn}async function h5(e,t,r,n){var i,o;if(!yn)return[];let a=AC<(((i=t.face.embedding)==null?void 0:i.skipFrames)||0),s=(((o=t.face.embedding)==null?void 0:o.skipTime)||0)>oe()-yC;return t.skipAllowed&&s&&a&&gC===n&&p5[r]?(AC++,p5[r]):new Promise(async l=>{var d;let u=[];if(((d=t.face.embedding)==null?void 0:d.enabled)&&(yn==null?void 0:yn.inputs[0].shape)){let h={};h.crop=Ie.resizeBilinear(e,[yn.inputs[0].shape[2],yn.inputs[0].shape[1]],!1),h.data=yn==null?void 0:yn.execute(h.crop);let p=await h.data.data();u=Array.from(p)}p5[r]=u,gC=n,yC=oe(),l(u)})}var ps,Zi=0,Y2e=2.3,c5=Jn.leftEyeLower0,f5=Jn.rightEyeLower0,zd={leftBounds:[c5[0],c5[c5.length-1]],rightBounds:[f5[0],f5[f5.length-1]]},Od={upperCenter:3,lowerCenter:4,index:71,numCoordinates:76};async function IC(e){var t;return he.initial&&(ps=null),ps?e.debug&&se("cached model:",ps.modelUrl):ps=await Ge((t=e.face.iris)==null?void 0:t.modelPath),Zi=ps.inputs[0].shape?ps.inputs[0].shape[2]:0,Zi===-1&&(Zi=64),ps}function j0(e,t,r,n){for(let a=0;a<jb.length;a++){let{key:s,indices:i}=jb[a],o=Jn[`${r}${s}`];if(!n||n.includes(s))for(let l=0;l<i.length;l++){let u=i[l];e[o[l]]=[t[u][0],t[u][1],(t[u][2]+e[o[l]][2])/2]}}}var J2e=e=>{let t=e[zd.leftBounds[0]][2],r=e[zd.rightBounds[0]][2];return t-r},vC=(e,t,r,n,a,s=!1)=>{let i=z0(_0(BN([e[r],e[n]]),Y2e)),o=$d(i),l=Ie.cropAndResize(t,[[i.startPoint[1]/a,i.startPoint[0]/a,i.endPoint[1]/a,i.endPoint[0]/a]],[0],[Zi,Zi]);if(s&&he.kernels.includes("flipleftright")){let u=Ie.flipLeftRight(l);re(l),l=u}return{box:i,boxSize:o,crop:l}},wC=(e,t,r,n=!1)=>{let a=[];for(let s=0;s<Od.numCoordinates;s++){let i=e[s*3],o=e[s*3+1],l=e[s*3+2];a.push([(n?1-i/Zi:i/Zi)*r[0]+t.startPoint[0],o/Zi*r[1]+t.startPoint[1],l])}return{rawCoords:a,iris:a.slice(Od.index)}},kC=(e,t,r)=>{let n=e[Jn[`${r}EyeUpper0`][Od.upperCenter]][2],a=e[Jn[`${r}EyeLower0`][Od.lowerCenter]][2],s=(n+a)/2;return t.map((i,o)=>{let l=s;return o===2?l=n:o===4&&(l=a),[i[0],i[1],l]})};async function SC(e,t,r,n){if(!ps)return r.debug&&se("face mesh iris detection requested, but model is not loaded"),e;let{box:a,boxSize:s,crop:i}=vC(e,t,zd.leftBounds[0],zd.leftBounds[1],n,!0),{box:o,boxSize:l,crop:u}=vC(e,t,zd.rightBounds[0],zd.rightBounds[1],n,!0),d=kt([i,u]);re(i),re(u);let h=ps.execute(d);re(d);let p=await h.data();re(h);let c=p.slice(0,Od.numCoordinates*3),{rawCoords:f,iris:m}=wC(c,a,s,!0),g=p.slice(Od.numCoordinates*3),{rawCoords:y,iris:A}=wC(g,o,l,!1),x=J2e(e);Math.abs(x)<30?(j0(e,f,"left",null),j0(e,y,"right",null)):x<1?j0(e,f,"left",["EyeUpper0","EyeLower0"]):j0(e,y,"right",["EyeUpper0","EyeLower0"]);let b=kC(e,m,"left"),v=kC(e,A,"right");return e.concat(b).concat(v)}var Yi={eyeLLower:[33,7,163,144,145,153,154,155,133],eyeRLower:[263,249,390,373,374,380,381,382,362],lips:[61,76,91,181,84,17,314,405,321,291,291,185,40,39,37,0,267,269,270,291,62,183,88,178,87,14,268,303,304,408,291,184,42,178,87,14,268,303,304,408,61,62,90,180,85,16,315,404,307,308,291,185,40,73,72,0,302,269,270,409,61,184,95,179,86,15,316,403,324,408,291,184,74,41,38,11,268,303,304,408],eyeL:[33,7,163,144,145,153,154,155,133,246,161,160,159,158,157,173,130,25,110,24,23,22,26,112,243,247,30,29,27,28,56,190,226,31,228,229,230,231,232,233,244,113,225,224,223,222,221,189,35,124,46,53,52,65,143,111,117,118,119,120,121,128,245,156,70,63,105,66,107,55,193],eyeR:[263,249,390,373,374,380,381,382,362,466,388,387,386,385,384,398,359,255,339,254,253,252,256,341,463,467,260,259,257,258,286,414,446,261,448,449,450,451,452,453,464,342,445,444,443,442,441,413,265,353,276,283,282,295,372,340,346,347,348,349,350,357,465,383,300,293,334,296,336,285,417]};async function NC(e,t){let r={irisL:t[3].dataSync(),irisR:t[1].dataSync(),eyeL:t[0].dataSync(),eyeR:t[6].dataSync(),lips:t[5].dataSync()},n=Yi.eyeRLower.reduce((s,i)=>s+=e[i][2],0)/Yi.eyeRLower.length;for(let s=0;s<r.irisR.length/2;s++)e.push([r.irisR[2*s+0],r.irisR[2*s+1],n]);let a=Yi.eyeLLower.reduce((s,i)=>s+=e[i][2],0)/Yi.eyeLLower.length;for(let s=0;s<r.irisL.length/2;s++)e.push([r.irisL[2*s+0],r.irisL[2*s+1],a]);for(let s=0;s<r.eyeL.length/2;s++)e[Yi.eyeL[s]]=[r.eyeL[2*s+0],r.eyeL[2*s+1],e[Yi.eyeL[s]][2]];for(let s=0;s<r.eyeR.length/2;s++)e[Yi.eyeR[s]]=[r.eyeR[2*s+0],r.eyeR[2*s+1],e[Yi.eyeR[s]][2]];return e}var Da={boxes:[],skipped:Number.MAX_SAFE_INTEGER,timestamp:0},La=null,Dd=0;async function CC(e,t){var o,l,u,d,h,p,c,f,m,g;let r=(((o=t.face.detector)==null?void 0:o.skipTime)||0)>oe()-Da.timestamp,n=Da.skipped<(((l=t.face.detector)==null?void 0:l.skipFrames)||0);!t.skipAllowed||!r||!n||Da.boxes.length===0?(Da.boxes=await XN(e,t),Da.timestamp=oe(),Da.skipped=0):Da.skipped++;let a=[],s=[],i=0;for(let y=0;y<Da.boxes.length;y++){let A=Da.boxes[y],x=0,b,v={id:i++,mesh:[],meshRaw:[],box:[0,0,0,0],boxRaw:[0,0,0,0],score:0,boxScore:0,faceScore:0,annotations:{}};if([x,b,v.tensor]=GN((u=t.face.detector)==null?void 0:u.rotation,A,e,(d=t.face.mesh)!=null&&d.enabled?Dd:O0()),(h=t==null?void 0:t.filter)!=null&&h.equalization){let S=await C0(v.tensor);re(v.tensor),v.tensor=S}if(v.boxScore=Math.round(100*A.confidence)/100,(p=t.face.mesh)!=null&&p.enabled)if(!La)t.debug&&se("face mesh detection requested, but model is not loaded");else{let S=La.execute(v.tensor),T=S.find(I=>I.shape[I.shape.length-1]===1),E=S.find(I=>I.shape[I.shape.length-1]===1404),R=await T.data();v.faceScore=Math.round(100*R[0])/100;let _=G(E,[-1,3]),M=await _.array();if(v.faceScore<(((c=t.face.detector)==null?void 0:c.minConfidence)||1))A.confidence=v.faceScore;else{(f=t.face.attention)!=null&&f.enabled?M=await NC(M,S):(m=t.face.iris)!=null&&m.enabled&&(M=await SC(M,v.tensor,t,Dd)),v.mesh=UN(M,A,x,b,Dd),v.meshRaw=v.mesh.map(z=>[z[0]/(e.shape[2]||0),z[1]/(e.shape[1]||0),(z[2]||0)/Dd]);for(let z of Object.keys(Jn))v.annotations[z]=Jn[z].map(O=>v.mesh[O]);v.score=v.faceScore;let I={...jN(v.mesh,A),confidence:A.confidence,landmarks:A.landmarks};v.box=Xb(I,e),v.boxRaw=Zb(I,e),s.push(I)}re([...S,_])}else{v.box=Xb(A,e),v.boxRaw=Zb(A,e),v.score=v.boxScore,v.mesh=A.landmarks.map(S=>[(A.startPoint[0]+A.endPoint[0])/2+(A.endPoint[0]+A.startPoint[0])*S[0]/O0(),(A.startPoint[1]+A.endPoint[1])/2+(A.endPoint[1]+A.startPoint[1])*S[1]/O0()]),v.meshRaw=v.mesh.map(S=>[S[0]/(e.shape[2]||0),S[1]/(e.shape[1]||0),(S[2]||0)/Dd]);for(let S of Object.keys(Kh))v.annotations[S]=[v.mesh[Kh[S]]]}v.score>(((g=t.face.detector)==null?void 0:g.minConfidence)||1)?a.push(v):re(v.tensor)}return Da.boxes=s,a}async function EC(e){var t,r,n;return he.initial&&(La=null),La?e.debug&&se("cached model:",La.modelUrl):(t=e.face.attention)!=null&&t.enabled?La=await Ge((r=e.face.attention)==null?void 0:r.modelPath):La=await Ge((n=e.face.mesh)==null?void 0:n.modelPath),Dd=La.inputs[0].shape?La.inputs[0].shape[2]:0,La}var RC=Dl,MC=Xh;var An,H0=[],FC=0,$C=0,g5=Number.MAX_SAFE_INTEGER;async function PC(e){var t;return he.initial&&(An=null),An?e.debug&&se("cached model:",An.modelUrl):An=await Ge((t=e.face.description)==null?void 0:t.modelPath),An}function y5(e){let t=e.image||e.tensor||e;if(!(An!=null&&An.inputs[0].shape))return t;let r=Ie.resizeBilinear(t,[An.inputs[0].shape[2],An.inputs[0].shape[1]],!1),n=L(r,Qe.tf255);return re(r),n}async function A5(e,t,r,n){var i,o,l,u;if(!An)return{age:0,gender:"unknown",genderScore:0,descriptor:[]};let a=g5<(((i=t.face.description)==null?void 0:i.skipFrames)||0),s=(((o=t.face.description)==null?void 0:o.skipTime)||0)>oe()-FC;return t.skipAllowed&&a&&s&&$C===n&&((l=H0[r])==null?void 0:l.age)&&((u=H0[r])==null?void 0:u.age)>0?(g5++,H0[r]):(g5=0,new Promise(async d=>{var p,c;let h={age:0,gender:"unknown",genderScore:0,descriptor:[]};if((p=t.face.description)!=null&&p.enabled){let f=y5(e),m=An==null?void 0:An.execute(f);FC=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)&&(h.gender=y[0]<=.5?"female":"male",h.genderScore=Math.min(.99,A));let x=Cn(m.find(R=>R.shape[1]===100),1),b=(await x.data())[0];re(x);let S=await m.find(R=>R.shape[1]===100).data();h.age=Math.round(S[b-1]>S[b+1]?10*b-100*S[b-1]:10*b+100*S[b+1])/10;let T=m.find(R=>R.shape[1]===1024),E=T?await T.data():[];h.descriptor=Array.from(E),m.forEach(R=>re(R))}H0[r]=h,$C=n,d(h)}))}function q0(e){return[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])]}function Jh(e){return[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2]}function OC(e,t,r){let n=t.shape[1],a=t.shape[2],s=[[e.startPoint[1]/n,e.startPoint[0]/a,e.endPoint[1]/n,e.endPoint[0]/a]];return Ie.cropAndResize(t,s,[0],r)}function DC(e,t){let r=[e.startPoint[0]*t[0],e.startPoint[1]*t[1]],n=[e.endPoint[0]*t[0],e.endPoint[1]*t[1]],a=e.palmLandmarks.map(s=>[s[0]*t[0],s[1]*t[1]]);return{startPoint:r,endPoint:n,palmLandmarks:a,confidence:e.confidence}}function K0(e,t=1.5){let r=Jh(e),n=q0(e),a=[t*n[0]/2,t*n[1]/2],s=[r[0]-a[0],r[1]-a[1]],i=[r[0]+a[0],r[1]+a[1]];return{startPoint:s,endPoint:i,palmLandmarks:e.palmLandmarks}}function X0(e){let t=Jh(e),r=q0(e),a=Math.max(...r)/2,s=[t[0]-a,t[1]-a],i=[t[0]+a,t[1]+a];return{startPoint:s,endPoint:i,palmLandmarks:e.palmLandmarks}}function eAe(e){return e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI))}function LC(e,t){let r=Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]);return eAe(r)}var _C=(e,t)=>[[1,0,e],[0,1,t],[0,0,1]];function Ji(e,t){let r=0;for(let n=0;n<e.length;n++)r+=e[n]*t[n];return r}function tAe(e,t){let r=[];for(let n=0;n<e.length;n++)r.push(e[n][t]);return r}function zC(e,t){let r=[],n=e.length;for(let a=0;a<n;a++){r.push([]);for(let s=0;s<n;s++)r[a].push(Ji(e[a],tAe(t,s)))}return r}function b5(e,t){let r=Math.cos(e),n=Math.sin(e),a=[[r,-n,0],[n,r,0],[0,0,1]],s=_C(t[0],t[1]),i=zC(s,a),o=_C(-t[0],-t[1]);return zC(i,o)}function BC(e){let t=[[e[0][0],e[1][0]],[e[0][1],e[1][1]]],r=[e[0][2],e[1][2]],n=[-Ji(t[0],r),-Ji(t[1],r)];return[t[0].concat(n[0]),t[1].concat(n[1]),[0,0,1]]}function v5(e,t){return[Ji(e,t[0]),Ji(e,t[1])]}var VC=[{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 Z0=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=VC.map(r=>[r.x,r.y]),this.anchorsTensor=pa(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=Pe(t,[0,0],[-1,2]),r.boxSizes=Pe(t,[0,2],[-1,2]),r.div=pe(r.boxOffsets,this.inputSizeTensor),r.boxCenterPoints=le(r.div,this.anchorsTensor),r.halfBoxSizes=pe(r.boxSizes,this.doubleInputSizeTensor),r.sub=ce(r.boxCenterPoints,r.halfBoxSizes),r.startPoints=L(r.sub,this.inputSizeTensor),r.add=le(r.boxCenterPoints,r.halfBoxSizes),r.endPoints=L(r.add,this.inputSizeTensor);let n=ud([r.startPoints,r.endPoints],1);return Object.keys(r).forEach(a=>re(r[a])),n}normalizeLandmarks(t,r){let n={};n.reshape=G(t,[-1,7,2]),n.div=pe(n.reshape,this.inputSizeTensor),n.landmarks=le(n.div,this.anchors[r]);let a=L(n.landmarks,this.inputSizeTensor);return Object.keys(n).forEach(s=>re(n[s])),a}async predict(t,r){let n={};n.resize=Ie.resizeBilinear(t,[this.inputSize,this.inputSize]),n.div=pe(n.resize,Qe.tf127),n.image=ce(n.div,Qe.tf1),n.batched=this.model.execute(n.image),n.predictions=rt(n.batched),n.slice=Pe(n.predictions,[0,0],[-1,1]),n.sigmoid=Nr(n.slice),n.scores=rt(n.sigmoid);let a=await n.scores.data();n.boxes=Pe(n.predictions,[0,1],[-1,4]),n.norm=this.normalizeBoxes(n.boxes),n.nms=await Ie.nonMaxSuppressionAsync(n.norm,n.scores,3*r.hand.maxDetected,r.hand.iouThreshold,r.hand.minConfidence);let s=await n.nms.array(),i=[];for(let o of s){let l={};l.box=Pe(n.norm,[o,0],[1,-1]),l.slice=Pe(n.predictions,[o,5],[1,14]),l.norm=this.normalizeLandmarks(l.slice,o),l.palmLandmarks=G(l.norm,[-1,2]);let u=await l.box.data(),d=u.slice(0,2),h=u.slice(2,4),p=await l.palmLandmarks.array(),c={startPoint:d,endPoint:h,palmLandmarks:p,confidence:a[o]},f=DC(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(n).forEach(o=>re(n[o])),i}};var aAe=5,UC=1.65,GC=[0,5,9,13,17,1,2],sAe=0,iAe=2,jC=0,Y0=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]),n=t.map(i=>i[1]),a=[Math.min(...r),Math.min(...n)],s=[Math.max(...r),Math.max(...n)];return{startPoint:a,endPoint:s}}getBoxForPalmLandmarks(t,r){let n=t.map(s=>v5([...s,1],r)),a=this.calculateLandmarksBoundingBox(n);return K0(X0(a),aAe)}getBoxForHandLandmarks(t){let r=this.calculateLandmarksBoundingBox(t),n=K0(X0(r),UC);n.palmLandmarks=[];for(let a=0;a<GC.length;a++)n.palmLandmarks.push(t[GC[a]].slice(0,2));return n}transformRawCoords(t,r,n,a){let s=q0(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=b5(n,[0,0]),u=o.map(c=>[...v5(c,l),c[2]]),d=BC(a),h=[...Jh(r),1],p=[Ji(h,d[0]),Ji(h,d[1])];return u.map(c=>[Math.trunc(c[0]+p[0]),Math.trunc(c[1]+p[1]),Math.trunc(c[2])])}async estimateHands(t,r){let n=!1,a,s=(r.hand.skipTime||0)>oe()-jC,i=this.skipped<(r.hand.skipFrames||0);r.skipAllowed&&s&&i&&(a=await this.handDetector.predict(t,r),this.skipped=0),r.skipAllowed&&this.skipped++,a&&a.length>0&&(a.length!==this.detectedHands&&this.detectedHands!==r.hand.maxDetected||!r.hand.landmarks)&&(this.detectedHands=0,this.storedBoxes=[...a],this.storedBoxes.length>0&&(n=!0));let o=[];for(let l=0;l<this.storedBoxes.length;l++){let u=this.storedBoxes[l];if(!!u)if(r.hand.landmarks){let d=r.hand.rotation?LC(u.palmLandmarks[sAe],u.palmLandmarks[iAe]):0,h=Jh(u),p=[h[0]/t.shape[2],h[1]/t.shape[1]],c=r.hand.rotation&&he.kernels.includes("rotatewithoffset")?Ie.rotateWithOffset(t,d,0,p):t.clone(),f=b5(-d,h),m=n?this.getBoxForPalmLandmarks(u.palmLandmarks,f):u,g=OC(m,c,[this.inputSize,this.inputSize]),y=pe(g,Qe.tf255);re(g),re(c);let[A,x]=this.handPoseModel.execute(y);jC=oe(),re(y);let b=(await A.data())[0];if(re(A),b>=r.hand.minConfidence/4){let v=G(x,[-1,3]),S=await v.array();re(x),re(v);let T=this.transformRawCoords(S,m,d,f),E=this.getBoxForHandLandmarks(T);this.storedBoxes[l]={...E,confidence:b};let R={landmarks:T,confidence:b,boxConfidence:u.confidence,fingerConfidence:b,box:{topLeft:E.startPoint,bottomRight:E.endPoint}};o.push(R)}else this.storedBoxes[l]=null;re(x)}else{let d=K0(X0(u),UC),h={confidence:u.confidence,boxConfidence:u.confidence,fingerConfidence:0,box:{topLeft:d.startPoint,bottomRight:d.endPoint},landmarks:[]};o.push(h)}}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 Zr={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=>Zr.nameMapping[e],getPoints:e=>Zr.pointsMapping[e]},eo={none:0,half:1,full:2,nameMapping:{0:"none",1:"half",2:"full"},getName:e=>eo.nameMapping[e]},Lt={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=>Lt.nameMapping[e]},Qi=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,n){typeof this.curls[t]=="undefined"&&(this.curls[t]=[]),this.curls[t].push([r,n])}direction(t,r,n){this.directions[t]||(this.directions[t]=[]),this.directions[t].push([r,n])}weight(t,r){this.weights[t]=r;let n=this.weights.reduce((a,s)=>a+s,0);this.weightsRelative=this.weights.map(a=>a*5/n)}matchAgainst(t,r){let n=0;for(let a in t){let s=t[a],i=this.curls[a];if(typeof i=="undefined"){n+=this.weightsRelative[a];continue}for(let[o,l]of i)if(s===o){n+=l*this.weightsRelative[a];break}}for(let a in r){let s=r[a],i=this.directions[a];if(typeof i=="undefined"){n+=this.weightsRelative[a];continue}for(let[o,l]of i)if(s===o){n+=l*this.weightsRelative[a];break}}return n/10}};var{thumb:ba,index:hs,middle:cs,ring:Wl,pinky:Vl}=Zr,{none:va,half:lAe,full:wa}=eo,{verticalUp:Ld,verticalDown:t4e,horizontalLeft:w5,horizontalRight:uAe,diagonalUpRight:dAe,diagonalUpLeft:Bd,diagonalDownRight:r4e,diagonalDownLeft:n4e}=Lt,to=new Qi("thumbs up");to.curl(ba,va,1);to.direction(ba,Ld,1);to.direction(ba,Bd,.25);to.direction(ba,dAe,.25);for(let e of[Zr.index,Zr.middle,Zr.ring,Zr.pinky])to.curl(e,wa,1),to.direction(e,w5,1),to.direction(e,uAe,1);var Qt=new Qi("victory");Qt.curl(ba,lAe,.5);Qt.curl(ba,va,.5);Qt.direction(ba,Ld,1);Qt.direction(ba,Bd,1);Qt.curl(hs,va,1);Qt.direction(hs,Ld,.75);Qt.direction(hs,Bd,1);Qt.curl(cs,va,1);Qt.direction(cs,Ld,1);Qt.direction(cs,Bd,.75);Qt.curl(Wl,wa,1);Qt.direction(Wl,Ld,.2);Qt.direction(Wl,Bd,1);Qt.direction(Wl,w5,.2);Qt.curl(Vl,wa,1);Qt.direction(Vl,Ld,.2);Qt.direction(Vl,Bd,1);Qt.direction(Vl,w5,.2);Qt.weight(hs,2);Qt.weight(cs,2);var ro=new Qi("point");ro.curl(ba,wa,1);ro.curl(hs,va,.5);ro.curl(cs,wa,.5);ro.curl(Wl,wa,.5);ro.curl(Vl,wa,.5);ro.weight(hs,2);ro.weight(cs,2);var no=new Qi("middle finger");no.curl(ba,va,1);no.curl(hs,wa,.5);no.curl(cs,wa,.5);no.curl(Wl,wa,.5);no.curl(Vl,wa,.5);no.weight(hs,2);no.weight(cs,2);var Wd=new Qi("open palm");Wd.curl(ba,va,.75);Wd.curl(hs,va,.75);Wd.curl(cs,va,.75);Wd.curl(Wl,va,.75);Wd.curl(Vl,va,.75);var HC=[to,Qt,ro,no,Wd];var pAe=.7,Ul={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 qC(e,t,r,n){let a=(t-n)/(e-r),s=Math.atan(a)*180/Math.PI;return s<=0?s=-s:s>0&&(s=180-s),s}function XC(e,t){if(!e||!t)return[0,0];let r=qC(e[0],e[1],t[0],t[1]);if(e.length===2)return r;let n=qC(e[1],e[2],t[1],t[2]);return[r,n]}function KC(e,t=1){let r=0,n=0,a=0;return e>=75&&e<=105?r=1*t:e>=25&&e<=155?n=1*t:a=1*t,[r,n,a]}function hAe(e,t,r){let n=e[0]-t[0],a=e[0]-r[0],s=t[0]-r[0],i=e[1]-t[1],o=e[1]-r[1],l=t[1]-r[1],u=e[2]-t[2],d=e[2]-r[2],h=t[2]-r[2],p=Math.sqrt(n*n+i*i+u*u),c=Math.sqrt(a*a+o*o+d*d),f=Math.sqrt(s*s+l*l+h*h),m=(f*f+p*p-c*c)/(2*f*p);m>1?m=1:m<-1&&(m=-1);let g=Math.acos(m);g=57.2958*g%180;let y;return g>Ul.NO_CURL_START_LIMIT?y=eo.none:g>Ul.HALF_CURL_START_LIMIT?y=eo.half:y=eo.full,y}function ZC(e,t,r,n){let a;return n===Math.abs(e)?e>0?a=Lt.horizontalLeft:a=Lt.horizontalRight:n===Math.abs(t)?t>0?a=Lt.horizontalLeft:a=Lt.horizontalRight:r>0?a=Lt.horizontalLeft:a=Lt.horizontalRight,a}function YC(e,t,r,n){let a;return n===Math.abs(e)?e<0?a=Lt.verticalDown:a=Lt.verticalUp:n===Math.abs(t)?t<0?a=Lt.verticalDown:a=Lt.verticalUp:r<0?a=Lt.verticalDown:a=Lt.verticalUp,a}function cAe(e,t,r,n,a,s,i,o){let l,u=YC(e,t,r,n),d=ZC(a,s,i,o);return u===Lt.verticalUp?d===Lt.horizontalLeft?l=Lt.diagonalUpLeft:l=Lt.diagonalUpRight:d===Lt.horizontalLeft?l=Lt.diagonalDownLeft:l=Lt.diagonalDownRight,l}function fAe(e,t,r,n){let a=e[0]-t[0],s=e[0]-r[0],i=t[0]-r[0],o=e[1]-t[1],l=e[1]-r[1],u=t[1]-r[1],d=Math.max(Math.abs(a),Math.abs(s),Math.abs(i)),h=Math.max(Math.abs(o),Math.abs(l),Math.abs(u)),p=0,c=0,f=0,m=h/(d+1e-5);m>1.5?p+=Ul.DISTANCE_VOTE_POWER:m>.66?c+=Ul.DISTANCE_VOTE_POWER:f+=Ul.DISTANCE_VOTE_POWER;let g=Math.sqrt(a*a+o*o),y=Math.sqrt(s*s+l*l),A=Math.sqrt(i*i+u*u),x=Math.max(g,y,A),b=e[0],v=e[1],S=r[0],T=r[1];x===g?(S=r[0],T=r[1]):x===A&&(b=t[0],v=t[1]);let _=XC([b,v],[S,T]),M=KC(_,Ul.TOTAL_ANGLE_VOTE_POWER);p+=M[0],c+=M[1],f+=M[2];for(let z of n){let O=KC(z,Ul.SINGLE_ANGLE_VOTE_POWER);p+=O[0],c+=O[1],f+=O[2]}let I;return p===Math.max(p,c,f)?I=YC(l,o,u,h):f===Math.max(c,f)?I=ZC(s,a,i,d):I=cAe(l,o,u,h,s,a,i,d),I}function JC(e){let t=[],r=[],n=[],a=[];if(!e)return{curls:n,directions:a};for(let s of Zr.all){let i=Zr.getPoints(s),o=[],l=[];for(let u of i){let d=e[u[0]],h=e[u[1]],p=XC(d,h),c=p[0],f=p[1];o.push(c),l.push(f)}t.push(o),r.push(l)}for(let s of Zr.all){let i=s===Zr.thumb?1:0,o=Zr.getPoints(s),l=e[o[i][0]],u=e[o[i+1][1]],d=e[o[3][1]],h=hAe(l,u,d),p=fAe(l,u,d,t[s].slice(i));n[s]=h,a[s]=p}return{curls:n,directions:a}}function J0(e){if(!e||e.length===0)return null;let t=JC(e),r={};for(let n of Zr.all)r[Zr.getName(n)]={curl:eo.getName(t.curls[n]),direction:Lt.getName(t.directions[n])};return r}function QC(e){let t=[];if(!e||e.length===0)return t;let r=JC(e);for(let n of HC){let a=n.matchAgainst(r.curls,r.directions);a>=pAe&&t.push({name:n.name,confidence:a})}return t}var e9={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]},Vd,Ud,t9;async function I5(e,t){let r=await t9.estimateHands(e,t);if(!r)return[];let n=[];for(let a=0;a<r.length;a++){let s={};if(r[a].landmarks)for(let d of Object.keys(e9))s[d]=e9[d].map(h=>r[a].landmarks[h]);let i=r[a].landmarks,o=[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,0,0],l=[0,0,0,0];if(i&&i.length>0){for(let d of i)d[0]<o[0]&&(o[0]=d[0]),d[1]<o[1]&&(o[1]=d[1]),d[0]>o[2]&&(o[2]=d[0]),d[1]>o[3]&&(o[3]=d[1]);o[2]-=o[0],o[3]-=o[1],l=[o[0]/(e.shape[2]||0),o[1]/(e.shape[1]||0),o[2]/(e.shape[2]||0),o[3]/(e.shape[1]||0)]}else o=r[a].box?[Math.trunc(Math.max(0,r[a].box.topLeft[0])),Math.trunc(Math.max(0,r[a].box.topLeft[1])),Math.trunc(Math.min(e.shape[2]||0,r[a].box.bottomRight[0])-Math.max(0,r[a].box.topLeft[0])),Math.trunc(Math.min(e.shape[1]||0,r[a].box.bottomRight[1])-Math.max(0,r[a].box.topLeft[1]))]:[0,0,0,0],l=[r[a].box.topLeft[0]/(e.shape[2]||0),r[a].box.topLeft[1]/(e.shape[1]||0),(r[a].box.bottomRight[0]-r[a].box.topLeft[0])/(e.shape[2]||0),(r[a].box.bottomRight[1]-r[a].box.topLeft[1])/(e.shape[1]||0)];let u=J0(i);n.push({id:a,score:Math.round(100*r[a].confidence)/100,boxScore:Math.round(100*r[a].boxConfidence)/100,fingerScore:Math.round(100*r[a].fingerConfidence)/100,label:"hand",box:o,boxRaw:l,keypoints:i,annotations:s,landmarks:u})}return n}async function S5(e){var r,n;he.initial&&(Vd=null,Ud=null),!Vd||!Ud?[Vd,Ud]=await Promise.all([e.hand.enabled?Ge((r=e.hand.detector)==null?void 0:r.modelPath):null,e.hand.landmarks?Ge((n=e.hand.skeleton)==null?void 0:n.modelPath):null]):(e.debug&&se("cached model:",Vd.modelUrl),e.debug&&se("cached model:",Ud.modelUrl));let t=new Z0(Vd);return t9=new Y0(t,Ud),[Vd,Ud]}var dr=[null,null],mAe=["StatefulPartitionedCall/Postprocessor/Slice","StatefulPartitionedCall/Postprocessor/ExpandDims_1"],ao=[[0,0],[0,0]],gAe=["hand","fist","pinch","point","face","tip","pinchtip"],n9=4,a9=1.6,yAe=512,AAe=1.4,Q0=Number.MAX_SAFE_INTEGER,T5=0,fs=[0,0],jt={boxes:[],hands:[]},s9={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 i9(e){var t;if(he.initial&&(dr[0]=null),dr[0])e.debug&&se("cached model:",dr[0].modelUrl);else{eg(["tensorlistreserve","enter","tensorlistfromtensor","merge","loopcond","switch","exit","tensorliststack","nextiteration","tensorlistsetitem","tensorlistgetitem","reciprocal","shape","split","where"],e),dr[0]=await Ge((t=e.hand.detector)==null?void 0:t.modelPath);let r=Object.values(dr[0].modelSignature.inputs);ao[0][0]=Array.isArray(r)?parseInt(r[0].tensorShape.dim[1].size):0,ao[0][1]=Array.isArray(r)?parseInt(r[0].tensorShape.dim[2].size):0}return dr[0]}async function o9(e){var t;if(he.initial&&(dr[1]=null),dr[1])e.debug&&se("cached model:",dr[1].modelUrl);else{dr[1]=await Ge((t=e.hand.skeleton)==null?void 0:t.modelPath);let r=Object.values(dr[1].modelSignature.inputs);ao[1][0]=Array.isArray(r)?parseInt(r[0].tensorShape.dim[1].size):0,ao[1][1]=Array.isArray(r)?parseInt(r[0].tensorShape.dim[2].size):0}return dr[1]}async function xAe(e,t){let r=[];if(!e||!dr[0])return r;let n={},a=(e.shape[2]||1)/(e.shape[1]||1),s=Math.min(Math.round((e.shape[1]||0)/8)*8,yAe),i=Math.round(s*a/8)*8;n.resize=Ie.resizeBilinear(e,[s,i]),n.cast=me(n.resize,"int32"),[n.rawScores,n.rawBoxes]=await dr[0].executeAsync(n.cast,mAe),n.boxes=rt(n.rawBoxes,[0,2]),n.scores=rt(n.rawScores,[0]);let o=rn(n.scores,1);re(o[n9]),o.splice(n9,1),n.filtered=lr(o,1),re(o),n.max=gr(n.filtered,1),n.argmax=Cn(n.filtered,1);let l=0;n.nms=await Ie.nonMaxSuppressionAsync(n.boxes,n.max,(t.hand.maxDetected||0)+1,t.hand.iouThreshold||0,t.hand.minConfidence||1);let u=await n.nms.data(),d=await n.max.data(),h=await n.argmax.data();for(let p of Array.from(u)){let c=Pe(n.boxes,p,1),f=await c.data();re(c);let m=[f[1],f[0],f[3]-f[1],f[2]-f[0]],g=B0(m,AAe),y=[Math.trunc(m[0]*fs[0]),Math.trunc(m[1]*fs[1]),Math.trunc(m[2]*fs[0]),Math.trunc(m[3]*fs[1])],A=d[p],x=gAe[h[p]],b={id:l++,score:A,box:y,boxRaw:g,label:x};r.push(b)}return Object.keys(n).forEach(p=>re(n[p])),r.sort((p,c)=>c.score-p.score),r.length>(t.hand.maxDetected||1)&&(r.length=t.hand.maxDetected||1),r}async function N5(e,t,r){let n={id:t.id,score:Math.round(100*t.score)/100,boxScore:Math.round(100*t.score)/100,fingerScore:0,box:t.box,boxRaw:t.boxRaw,label:t.label,keypoints:[],landmarks:{},annotations:{}};if(e&&dr[1]&&r.hand.landmarks&&t.score>(r.hand.minConfidence||0)){let a={},s=[t.boxRaw[1],t.boxRaw[0],t.boxRaw[3]+t.boxRaw[1],t.boxRaw[2]+t.boxRaw[0]];a.crop=Ie.cropAndResize(e,[s],[0],[ao[1][0],ao[1][1]],"bilinear"),a.div=pe(a.crop,Qe.tf255),[a.score,a.keypoints]=dr[1].execute(a.div,["Identity_1","Identity"]);let i=(await a.score.data())[0],o=(100-Math.trunc(100/(1+Math.exp(i))))/100;if(o>=(r.hand.minConfidence||0)){n.fingerScore=o,a.reshaped=G(a.keypoints,[-1,3]);let d=(await a.reshaped.array()).map(h=>[h[0]/ao[1][1],h[1]/ao[1][0],h[2]||0]).map(h=>[h[0]*t.boxRaw[2],h[1]*t.boxRaw[3],h[2]||0]);n.keypoints=d.map(h=>[fs[0]*(h[0]+t.boxRaw[0]),fs[1]*(h[1]+t.boxRaw[1]),h[2]||0]),n.landmarks=J0(n.keypoints);for(let h of Object.keys(s9))n.annotations[h]=s9[h].map(p=>n.landmarks&&n.keypoints[p]?n.keypoints[p]:null)}Object.keys(a).forEach(l=>re(a[l]))}return n}async function C5(e,t){var a,s;if(!dr[0]||!dr[1]||!((a=dr[0])!=null&&a.inputs[0].shape)||!((s=dr[1])!=null&&s.inputs[0].shape))return[];fs=[e.shape[2]||0,e.shape[1]||0],Q0++;let r=(t.hand.skipTime||0)>oe()-T5,n=Q0<(t.hand.skipFrames||0);return t.skipAllowed&&r&&n?jt.hands:new Promise(async i=>{let o=3*(t.hand.skipTime||0)>oe()-T5,l=Q0<3*(t.hand.skipFrames||0);t.skipAllowed&&jt.hands.length===t.hand.maxDetected?jt.hands=await Promise.all(jt.boxes.map(d=>N5(e,d,t))):t.skipAllowed&&o&&l&&jt.hands.length>0?jt.hands=await Promise.all(jt.boxes.map(d=>N5(e,d,t))):(jt.boxes=await xAe(e,t),T5=oe(),jt.hands=await Promise.all(jt.boxes.map(d=>N5(e,d,t))),Q0=0);let u=[...jt.boxes];if(jt.boxes.length=0,t.cacheSensitivity>0)for(let d=0;d<jt.hands.length;d++){let h=QN(jt.hands[d].keypoints,fs);if(h.box[2]/(e.shape[2]||1)>.05&&h.box[3]/(e.shape[1]||1)>.05&&jt.hands[d].fingerScore&&jt.hands[d].fingerScore>(t.hand.minConfidence||0)){let p=B0(h.box,a9),c=B0(h.boxRaw,a9);jt.boxes.push({...u[d],box:p,boxRaw:c})}}for(let d=0;d<jt.hands.length;d++){let h=us(jt.hands[d].keypoints,fs);jt.hands[d].box=h.box,jt.hands[d].boxRaw=h.boxRaw}i(jt.hands)})}var Fr,tg=[],E5=Number.MAX_SAFE_INTEGER,u9=0,d9=0;async function p9(e){var t;return he.initial&&(Fr=null),Fr?e.debug&&se("cached model:",Fr.modelUrl):Fr=await Ge((t=e.face.liveness)==null?void 0:t.modelPath),Fr}async function R5(e,t,r,n){var i,o;if(!Fr)return 0;let a=(((i=t.face.liveness)==null?void 0:i.skipTime)||0)>oe()-d9,s=E5<(((o=t.face.liveness)==null?void 0:o.skipFrames)||0);return t.skipAllowed&&a&&s&&u9===n&&tg[r]?(E5++,tg[r]):(E5=0,new Promise(async l=>{let u=Ie.resizeBilinear(e,[Fr!=null&&Fr.inputs[0].shape?Fr.inputs[0].shape[2]:0,Fr!=null&&Fr.inputs[0].shape?Fr.inputs[0].shape[1]:0],!1),d=Fr==null?void 0:Fr.execute(u),h=(await d.data())[0];tg[r]=Math.round(100*h)/100,u9=n,d9=oe(),re([u,d]),l(tg[r])}))}var Qh={};bs(Qh,{connected:()=>ng,horizontal:()=>M5,kpt:()=>rg,relative:()=>$5,vertical:()=>F5});var rg=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],M5=[["leftEye","rightEye"],["leftEar","rightEar"],["leftShoulder","rightShoulder"],["leftElbow","rightElbow"],["leftWrist","rightWrist"],["leftHip","rightHip"],["leftKnee","rightKnee"],["leftAnkle","rightAnkle"]],F5=[["leftKnee","leftShoulder"],["rightKnee","rightShoulder"],["leftAnkle","leftKnee"],["rightAnkle","rightKnee"]],$5=[[["leftHip","rightHip"],["leftShoulder","rightShoulder"]],[["leftElbow","rightElbow"],["leftShoulder","rightShoulder"]]],ng={leftLeg:["leftHip","leftKnee","leftAnkle"],rightLeg:["rightHip","rightKnee","rightAnkle"],torso:["leftShoulder","rightShoulder","rightHip","leftHip","leftShoulder"],leftArm:["leftShoulder","leftElbow","leftWrist"],rightArm:["rightShoulder","rightElbow","rightWrist"],head:[]};var c9=.005,xn={keypoints:[],padding:[[0,0],[0,0],[0,0],[0,0]]};function P5(e){for(let t of M5){let r=e.keypoints.findIndex(a=>a.part===t[0]),n=e.keypoints.findIndex(a=>a.part===t[1]);if(e.keypoints[r]&&e.keypoints[n]&&e.keypoints[r].position[0]<e.keypoints[n].position[0]){let a=e.keypoints[r];e.keypoints[r]=e.keypoints[n],e.keypoints[n]=a}}for(let t of F5){let r=e.keypoints.findIndex(a=>a&&a.part===t[0]),n=e.keypoints.findIndex(a=>a&&a.part===t[1]);e.keypoints[r]&&e.keypoints[n]&&e.keypoints[r].position[1]<e.keypoints[n].position[1]&&e.keypoints.splice(r,1)}for(let[t,r]of $5){let n=e.keypoints.findIndex(u=>u&&u.part===t[0]),a=e.keypoints.findIndex(u=>u&&u.part===t[1]),s=e.keypoints.findIndex(u=>u&&u.part===r[0]),i=e.keypoints.findIndex(u=>u&&u.part===r[1]);if(!e.keypoints[s]||!e.keypoints[i])continue;let o=e.keypoints[n]?[Math.abs(e.keypoints[s].position[0]-e.keypoints[n].position[0]),Math.abs(e.keypoints[i].position[0]-e.keypoints[n].position[0])]:[0,0],l=e.keypoints[a]?[Math.abs(e.keypoints[i].position[0]-e.keypoints[a].position[0]),Math.abs(e.keypoints[s].position[0]-e.keypoints[a].position[0])]:[0,0];if(o[0]>o[1]||l[0]>l[1]){let u=e.keypoints[n];e.keypoints[n]=e.keypoints[a],e.keypoints[a]=u}}}function f9(e){for(let t=0;t<e.length;t++)if(e[t]&&xn.keypoints[t]){let r=[Math.abs(e[t].positionRaw[0]-xn.keypoints[t].positionRaw[0]),Math.abs(e[t].positionRaw[1]-xn.keypoints[t].positionRaw[1])];r[0]<c9&&r[1]<c9?e[t]=xn.keypoints[t]:xn.keypoints[t]=e[t]}else xn.keypoints[t]=e[t];return e}function m9(e,t){let r={};if(!e.shape||!e.shape[1]||!e.shape[2])return e;xn.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=Hn(e,xn.padding),r.resize=Ie.resizeBilinear(r.pad,[t,t]);let n=me(r.resize,"int32");return Object.keys(r).forEach(a=>re(r[a])),n}function g9(e,t){e.keypoints=e.keypoints.filter(n=>n&&n.position);for(let n of e.keypoints)n.position=[n.position[0]*(t[0]+xn.padding[2][0]+xn.padding[2][1])/t[0]-xn.padding[2][0],n.position[1]*(t[1]+xn.padding[1][0]+xn.padding[1][1])/t[1]-xn.padding[1][0]],n.positionRaw=[n.position[0]/t[0],n.position[1]/t[1]];let r=us(e.keypoints.map(n=>n.position),t);return e.box=r.box,e.boxRaw=r.boxRaw,e}var bn,ag=0,_5=Number.MAX_SAFE_INTEGER,Gl={boxes:[],bodies:[],last:0};async function y9(e){return he.initial&&(bn=null),bn?e.debug&&se("cached model:",bn.modelUrl):(eg(["size"],e),bn=await Ge(e.body.modelPath)),ag=bn.inputs[0].shape?bn.inputs[0].shape[2]:0,ag<64&&(ag=256),bn}async function vAe(e,t,r){let n=e[0][0],a=[],s=0;for(let d=0;d<n.length;d++)if(s=n[d][2],s>t.body.minConfidence){let h=[n[d][1],n[d][0]];a.push({score:Math.round(100*s)/100,part:rg[d],positionRaw:h,position:[Math.round((r.shape[2]||0)*h[0]),Math.round((r.shape[1]||0)*h[1])]})}s=a.reduce((d,h)=>h.score>d?h.score:d,0);let i=[],o=us(a.map(d=>d.position),[r.shape[2],r.shape[1]]),l={};for(let[d,h]of Object.entries(ng)){let p=[];for(let c=0;c<h.length-1;c++){let f=a.find(g=>g.part===h[c]),m=a.find(g=>g.part===h[c+1]);f&&m&&f.score>(t.body.minConfidence||0)&&m.score>(t.body.minConfidence||0)&&p.push([f.position,m.position])}l[d]=p}let u={id:0,score:s,box:o.box,boxRaw:o.boxRaw,keypoints:a,annotations:l};return P5(u),i.push(u),i}async function wAe(e,t,r){let n=[];for(let a=0;a<e[0].length;a++){let s=e[0][a],i=Math.round(100*s[51+4])/100;if(i>t.body.minConfidence){let o=[];for(let h=0;h<17;h++){let p=s[3*h+2];if(p>t.body.minConfidence){let c=[s[3*h+1],s[3*h+0]];o.push({part:rg[h],score:Math.round(100*p)/100,positionRaw:c,position:[Math.round((r.shape[2]||0)*c[0]),Math.round((r.shape[1]||0)*c[1])]})}}let l=us(o.map(h=>h.position),[r.shape[2],r.shape[1]]),u={};for(let[h,p]of Object.entries(ng)){let c=[];for(let f=0;f<p.length-1;f++){let m=o.find(y=>y.part===p[f]),g=o.find(y=>y.part===p[f+1]);m&&g&&m.score>(t.body.minConfidence||0)&&g.score>(t.body.minConfidence||0)&&c.push([m.position,g.position])}u[h]=c}let d={id:a,score:i,box:l.box,boxRaw:l.boxRaw,keypoints:[...o],annotations:u};P5(d),n.push(d)}}return n.sort((a,s)=>s.score-a.score),n.length>t.body.maxDetected&&(n.length=t.body.maxDetected),n}async function z5(e,t){if(!bn||!(bn!=null&&bn.inputs[0].shape))return[];t.skipAllowed||(Gl.boxes.length=0),_5++;let r=(t.body.skipTime||0)>oe()-Gl.last,n=_5<(t.body.skipFrames||0);return t.skipAllowed&&r&&n?Gl.bodies:new Promise(async a=>{let s={};_5=0,s.input=m9(e,ag),s.res=bn==null?void 0:bn.execute(s.input),Gl.last=oe();let i=await s.res.array();Gl.bodies=s.res.shape[2]===17?await vAe(i,t,e):await wAe(i,t,e);for(let o of Gl.bodies)g9(o,[e.shape[2]||1,e.shape[1]||1]),f9(o.keypoints);Object.keys(s).forEach(o=>re(s[o])),a(Gl.bodies)})}var Gd,sg=[],x9=0,O5=Number.MAX_SAFE_INTEGER,og=0,ig=2.5;async function b9(e){if(!Gd||he.initial){Gd=await Ge(e.object.modelPath);let t=Object.values(Gd.modelSignature.inputs);og=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):0}else e.debug&&se("cached model:",Gd.modelUrl);return Gd}async function kAe(e,t,r){let n=0,a=[];for(let l of[1,2,4])K(async()=>{let u=l*13,d=rt(e.find(m=>m.shape[1]===u**2&&(m.shape[2]||0)===_d.length)),h=rt(e.find(m=>m.shape[1]===u**2&&(m.shape[2]||0)<_d.length)),c=await h.reshape([-1,4,h.shape[1]/4]).argMax(2).array(),f=await d.array();for(let m=0;m<d.shape[0];m++)for(let g=0;g<d.shape[1];g++){let y=f[m][g];if(y>(r.object.minConfidence||0)&&g!==61){let A=(.5+Math.trunc(m%u))/u,x=(.5+Math.trunc(m/u))/u,b=c[m].map(I=>I*(u/l/og)),[v,S]=[A-ig/l*b[0],x-ig/l*b[1]],[T,E]=[A+ig/l*b[2]-v,x+ig/l*b[3]-S],R=[v,S,T,E];R=R.map(I=>Math.max(0,Math.min(I,1)));let _=[R[0]*t[0],R[1]*t[1],R[2]*t[0],R[3]*t[1]],M={id:n++,score:Math.round(100*y)/100,class:g+1,label:_d[g].label,box:_.map(I=>Math.trunc(I)),boxRaw:R};a.push(M)}}});e.forEach(l=>re(l));let s=a.map(l=>[l.boxRaw[1],l.boxRaw[0],l.boxRaw[3],l.boxRaw[2]]),i=a.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 a=a.filter((l,u)=>o.includes(u)).sort((l,u)=>u.score-l.score),a}async function D5(e,t){let r=(t.object.skipTime||0)>oe()-x9,n=O5<(t.object.skipFrames||0);return t.skipAllowed&&r&&n&&sg.length>0?(O5++,sg):(O5=0,!he.kernels.includes("mod")||!he.kernels.includes("sparsetodense")?sg:new Promise(async a=>{let s=[e.shape[2]||0,e.shape[1]||0],i=Ie.resizeBilinear(e,[og,og],!1),o=pe(i,Qe.tf255),l=o.transpose([0,3,1,2]);re(o),re(i);let u;t.object.enabled&&(u=Gd.execute(l)),x9=oe(),re(l);let d=await kAe(u,s,t);sg=d,a(d)}))}var tc=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],IAe=tc.length,ec=tc.reduce((e,t,r)=>(e[t]=r,e),{}),SAe=[["leftHip","leftShoulder"],["leftElbow","leftShoulder"],["leftElbow","leftWrist"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["rightHip","rightShoulder"],["rightElbow","rightShoulder"],["rightElbow","rightWrist"],["rightHip","rightKnee"],["rightKnee","rightAnkle"],["leftShoulder","rightShoulder"],["leftHip","rightHip"]],N4e=SAe.map(([e,t])=>[ec[e],ec[t]]),w9=[["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 k9(e){let t=e.reduce(({maxX:r,maxY:n,minX:a,minY:s},{position:{x:i,y:o}})=>({maxX:Math.max(r,i),maxY:Math.max(n,o),minX:Math.min(a,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 I9(e,[t,r],[n,a]){let s=t/n,i=r/a,o=(u,d)=>({id:d,score:u.score,boxRaw:[u.box[0]/a,u.box[1]/n,u.box[2]/a,u.box[3]/n],box:[Math.trunc(u.box[0]*i),Math.trunc(u.box[1]*s),Math.trunc(u.box[2]*i),Math.trunc(u.box[3]*s)],keypoints:u.keypoints.map(({score:h,part:p,position:c})=>({score:h,part:p,position:[Math.trunc(c.x*i),Math.trunc(c.y*s)],positionRaw:[c.x/n,c.y/n]})),annotations:{}});return e.map((u,d)=>o(u,d))}var lg=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 n=this.priorityQueue[t];this.priorityQueue[t]=this.priorityQueue[r],this.priorityQueue[r]=n}};function L5(e,t,r,n){return{y:n.get(e,t,r),x:n.get(e,t,r+IAe)}}function B5(e,t,r){let{heatmapY:n,heatmapX:a,id:s}=e,{y:i,x:o}=L5(n,a,s,r);return{x:e.heatmapX*t+o,y:e.heatmapY*t+i}}function W5(e,t,r){return e<t?t:e>r?r:e}function S9(e,t,r,n){let a=r-e,s=n-t;return a*a+s*s}function V5(e,t){return{x:e.x+t.x,y:e.y+t.y}}var ka,NAe=["MobilenetV1/offset_2/BiasAdd","MobilenetV1/heatmap_2/BiasAdd","MobilenetV1/displacement_fwd_2/BiasAdd","MobilenetV1/displacement_bwd_2/BiasAdd"],ug=1,jd=16,CAe=50**2;function T9(e,t,r,n,a,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:W5(Math.round(y.y/jd),0,A-1),x:W5(Math.round(y.x/jd),0,x-1)}),[u,d]=n.shape,h=l(t.position,u,d),p=o(h),f=V5(t.position,p);for(let y=0;y<i;y++){let A=l(f,u,d),x=L5(A.y,A.x,r,a);f=V5({x:A.x*jd,y:A.y*jd},{x:x.x,y:x.y})}let m=l(f,u,d),g=n.get(m.y,m.x,r);return{position:f,part:tc[r],score:g}}function EAe(e,t,r,n,a){let s=w9.map(([p,c])=>[ec[p],ec[c]]),i=s.map(([,p])=>p),o=s.map(([p])=>p),l=t.shape[2],u=i.length,d=new Array(l),h=B5(e.part,jd,r);d[e.part.id]={score:e.score,part:tc[e.part.id],position:h};for(let p=u-1;p>=0;--p){let c=i[p],f=o[p];d[c]&&!d[f]&&(d[f]=T9(p,d[c],f,t,r,a))}for(let p=0;p<u;++p){let c=o[p],f=i[p];d[c]&&!d[f]&&(d[f]=T9(p,d[c],f,t,r,n))}return d}function RAe(e,t,r,n,a){let[s,i]=a.shape,o=!0,l=Math.max(r-ug,0),u=Math.min(r+ug+1,s);for(let d=l;d<u;++d){let h=Math.max(n-ug,0),p=Math.min(n+ug+1,i);for(let c=h;c<p;++c)if(a.get(d,c,e)>t){o=!1;break}if(!o)break}return o}function MAe(e,t){let[r,n,a]=t.shape,s=new lg(r*n*a,({score:i})=>i);for(let i=0;i<r;++i)for(let o=0;o<n;++o)for(let l=0;l<a;++l){let u=t.get(i,o,l);u<e||RAe(l,u,i,o,t)&&s.enqueue({score:u,part:{heatmapY:i,heatmapX:o,id:l}})}return s}function N9(e,{x:t,y:r},n){return e.some(({keypoints:a})=>{var i;let s=(i=a[n])==null?void 0:i.position;return s?S9(r,t,s.y,s.x)<=CAe:!1})}function FAe(e,t){return t.reduce((n,{position:a,score:s},i)=>(N9(e,a,i)||(n+=s),n),0)/t.length}function $Ae(e,t,r,n,a,s){let i=[],o=MAe(s,t);for(;i.length<a&&!o.empty();){let l=o.dequeue(),u=B5(l.part,jd,e);if(N9(i,u,l.part.id))continue;let d=EAe(l,t,e,r,n);d=d.filter(c=>c.score>s);let h=FAe(i,d),p=k9(d);h>s&&i.push({keypoints:d,box:p,score:Math.round(100*h)/100})}return i}async function U5(e,t){let r=K(()=>{if(!ka.inputs[0].shape)return[];let i=Ie.resizeBilinear(e,[ka.inputs[0].shape[2],ka.inputs[0].shape[1]]),o=ce(pe(me(i,"float32"),127.5),1),u=ka.execute(o,NAe).map(d=>rt(d,[0]));return u[1]=Nr(u[1]),u}),n=await Promise.all(r.map(i=>i.buffer()));for(let i of r)re(i);let a=await $Ae(n[0],n[1],n[2],n[3],t.body.maxDetected,t.body.minConfidence);return ka.inputs[0].shape?I9(a,[e.shape[1],e.shape[2]],[ka.inputs[0].shape[2],ka.inputs[0].shape[1]]):[]}async function C9(e){return!ka||he.initial?ka=await Ge(e.body.modelPath):e.debug&&se("cached model:",ka.modelUrl),ka}var Ba,G5=!1;async function j5(e){return!Ba||he.initial?Ba=await Ge(e.segmentation.modelPath):e.debug&&se("cached model:",Ba.modelUrl),Ba}async function R9(e,t,r){var m,g;if(G5)return{data:[],canvas:null,alpha:null};G5=!0,Ba||await j5(r);let n=await Fd(e,r),a=((m=n.tensor)==null?void 0:m.shape[2])||0,s=((g=n.tensor)==null?void 0:g.shape[1])||0;if(!n.tensor)return{data:[],canvas:null,alpha:null};let i={};i.resize=Ie.resizeBilinear(n.tensor,[Ba.inputs[0].shape?Ba.inputs[0].shape[1]:0,Ba.inputs[0].shape?Ba.inputs[0].shape[2]:0],!1),re(n.tensor),i.norm=pe(i.resize,Qe.tf255),i.res=Ba.execute(i.norm),i.squeeze=rt(i.res,0),i.squeeze.shape[2]===2?(i.softmax=fd(i.squeeze),[i.bg,i.fg]=rn(i.softmax,2),i.expand=qt(i.fg,2),i.pad=qt(i.expand,0),i.crop=Ie.cropAndResize(i.pad,[[0,0,.5,.5]],[0],[a,s]),i.data=rt(i.crop,0)):i.data=Ie.resizeBilinear(i.squeeze,[s,a]);let o=Array.from(await i.data.data());if(he.node&&!he.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=Kr(a,s);_n&&await _n.toPixels(i.data,l);let u=l.getContext("2d");r.segmentation.blur&&r.segmentation.blur>0&&(u.filter=`blur(${r.segmentation.blur}px)`);let d=u.getImageData(0,0,a,s),h=Kr(a,s),p=h.getContext("2d");n.canvas&&p.drawImage(n.canvas,0,0),p.globalCompositeOperation="darken",r.segmentation.blur&&r.segmentation.blur>0&&(p.filter=`blur(${r.segmentation.blur}px)`),p.drawImage(l,0,0),p.globalCompositeOperation="source-over",p.filter="none";let c=p.getImageData(0,0,a,s);for(let y=0;y<a*s;y++)c.data[4*y+3]=d.data[4*y+0];p.putImageData(c,0,0);let f=null;if(t&&h){f=Kr(a,s);let y=await Fd(t,r);re(y.tensor);let A=f.getContext("2d");A.drawImage(y.canvas,0,0,f.width,f.height),A.drawImage(h,0,0)}return Object.keys(i).forEach(y=>re(i[y])),G5=!1,{data:o,canvas:h,alpha:l}}var rc=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 dg(e){for(let t of Object.keys(e.models))e.models[t]=null}async function H5(e){var t,r,n,a,s,i,o,l,u,d,h,p,c,f,m,g,y,A,x,b,v,S,T,E,R,_,M,I,z,O,j;he.initial&&dg(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 S5(e.config)),!e.models.handskeleton&&e.config.hand.landmarks&&((a=(n=e.config.hand.detector)==null?void 0:n.modelPath)==null?void 0:a.includes("handdetect"))&&([e.models.handpose,e.models.handskeleton]=await S5(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=aC(e.config)),e.config.body.enabled&&!e.models.blazeposedetect&&e.config.body.detector&&e.config.body.detector.modelPath&&(e.models.blazeposedetect=nC(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=dC(e.config)),e.config.body.enabled&&!e.models.movenet&&((d=(u=e.config.body)==null?void 0:u.modelPath)==null?void 0:d.includes("movenet"))&&(e.models.movenet=y9(e.config)),e.config.body.enabled&&!e.models.posenet&&((p=(h=e.config.body)==null?void 0:h.modelPath)==null?void 0:p.includes("posenet"))&&(e.models.posenet=C9(e.config)),e.config.face.enabled&&!e.models.facedetect&&(e.models.facedetect=KN(e.config)),e.config.face.enabled&&((c=e.config.face.antispoof)==null?void 0:c.enabled)&&!e.models.antispoof&&(e.models.antispoof=_N(e.config)),e.config.face.enabled&&((f=e.config.face.liveness)==null?void 0:f.enabled)&&!e.models.liveness&&(e.models.liveness=p9(e.config)),e.config.face.enabled&&((m=e.config.face.description)==null?void 0:m.enabled)&&!e.models.faceres&&(e.models.faceres=PC(e.config)),e.config.face.enabled&&((g=e.config.face.emotion)==null?void 0:g.enabled)&&!e.models.emotion&&(e.models.emotion=fC(e.config)),e.config.face.enabled&&((y=e.config.face.iris)==null?void 0:y.enabled)&&!((A=e.config.face.attention)!=null&&A.enabled)&&!e.models.faceiris&&(e.models.faceiris=IC(e.config)),e.config.face.enabled&&((x=e.config.face.mesh)==null?void 0:x.enabled)&&!e.models.facemesh&&(e.models.facemesh=EC(e.config)),e.config.face.enabled&&((b=e.config.face.gear)==null?void 0:b.enabled)&&!e.models.gear&&(e.models.gear=wN(e.config)),e.config.face.enabled&&((v=e.config.face.ssrnet)==null?void 0:v.enabled)&&!e.models.ssrnetage&&(e.models.ssrnetage=NN(e.config)),e.config.face.enabled&&((S=e.config.face.ssrnet)==null?void 0:S.enabled)&&!e.models.ssrnetgender&&(e.models.ssrnetgender=MN(e.config)),e.config.face.enabled&&((T=e.config.face.mobilefacenet)==null?void 0:T.enabled)&&!e.models.mobilefacenet&&(e.models.mobilefacenet=xC(e.config)),e.config.hand.enabled&&!e.models.handtrack&&((R=(E=e.config.hand.detector)==null?void 0:E.modelPath)==null?void 0:R.includes("handtrack"))&&(e.models.handtrack=i9(e.config)),e.config.hand.enabled&&e.config.hand.landmarks&&!e.models.handskeleton&&((M=(_=e.config.hand.detector)==null?void 0:_.modelPath)==null?void 0:M.includes("handtrack"))&&(e.models.handskeleton=o9(e.config)),e.config.object.enabled&&!e.models.centernet&&((z=(I=e.config.object)==null?void 0:I.modelPath)==null?void 0:z.includes("centernet"))&&(e.models.centernet=oC(e.config)),e.config.object.enabled&&!e.models.nanodet&&((j=(O=e.config.object)==null?void 0:O.modelPath)==null?void 0:j.includes("nanodet"))&&(e.models.nanodet=b9(e.config)),e.config.segmentation.enabled&&!e.models.segmentation&&(e.models.segmentation=j5(e.config));for await(let X of Object.keys(e.models))e.models[X]&&typeof e.models[X]!="undefined"&&(e.models[X]=await e.models[X])}async function q5(e){let t=["const","placeholder","noop","pad","squeeze","add","sub","mul","div"];for(let r of Object.keys(e.models)){let n=e.models[r];if(!n)continue;let a=[],s=n==null?void 0:n.executor;if(s&&s.graph.nodes)for(let o of Object.values(s.graph.nodes)){let l=o.op.toLowerCase();a.includes(l)||a.push(l)}else!s&&e.config.debug&&se("model signature not determined:",r);let i=[];for(let o of a)!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 Ct={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 PAe(){let e=Ct.gl;!e||(Ct.extensions=e.getSupportedExtensions())}async function F9(e){var t;if(e.config.backend==="humangl"&&(Ct.name in nr().registry&&(!Ct.gl||!Ct.gl.getParameter(Ct.gl.VERSION))&&(se("error: humangl backend invalid context"),dg(e)),!F2(Ct.name))){try{Ct.canvas=await Kr(100,100)}catch(n){se("error: cannot create canvas:",n);return}try{if(Ct.gl=(t=Ct.canvas)==null?void 0:t.getContext("webgl2",Ct.webGLattr),!Ct.gl.getParameter(Ct.gl.VERSION).includes("2.0")){se("override: using fallback webgl backend as webgl 2.0 is not detected"),e.config.backend="webgl";return}Ct.canvas&&(Ct.canvas.addEventListener("webglcontextlost",async a=>{throw se("error: humangl:",a.type),se("possible browser memory leak using webgl or conflict with multiple backend registrations"),e.emit("error"),new Error("backend error: webgl context lost")}),Ct.canvas.addEventListener("webglcontextrestored",a=>{se("error: humangl context restored:",a)}),Ct.canvas.addEventListener("webglcontextcreationerror",a=>{se("error: humangl context create:",a)}))}catch(n){se("error: cannot get WebGL context:",n);return}try{A0(2,Ct.gl)}catch(n){se("error: cannot set WebGL context:",n);return}try{let n=new Au(Ct.gl);Cl(Ct.name,()=>new Oh(n),Ct.priority)}catch(n){se("error: cannot register WebGL backend:",n);return}try{Ra("webgl").forEach(a=>{let s={...a,backendName:Ct.name};jn(s)})}catch(n){se("error: cannot update WebGL backend registration:",n);return}let r=zn().getGPGPUContext?zn().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,Ct.gl);return}try{Aa.set("WEBGL_VERSION",2)}catch(n){se("error: cannot set WebGL backend flags:",n);return}PAe(),se("backend registered:",Ct.name)}}function _Ae(){if(!he.kernels.includes("mod")){let e={kernelName:"Mod",backendName:Ur(),kernelFunc:t=>K(()=>ce(t.inputs.a,L(pe(t.inputs.a,t.inputs.b),t.inputs.b)))};jn(e),he.kernels.push("mod")}if(!he.kernels.includes("floormod")){let e={kernelName:"FloorMod",backendName:Ur(),kernelFunc:t=>K(()=>gh(t.inputs.a/t.inputs.b)*t.inputs.b+hd(t.inputs.a,t.inputs.b))};jn(e),he.kernels.push("floormod")}}async function hg(e,t=!1){if(e.state="backend",t||he.initial||e.config.backend&&e.config.backend.length>0&&Ur()!==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"),he.browser&&e.config.backend==="tensorflow"&&(e.config.debug&&se("override: backend set to tensorflow while running in browser"),e.config.backend="humangl"),he.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"),he.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 a=await navigator.gpu.requestAdapter();e.config.debug&&se("enumerated webgpu adapter:",a)}e.config.backend==="humangl"&&await F9(e);let n=Object.keys(nr().registryFactory);if(e.config.debug&&se("available backends:",n),n.includes(e.config.backend)||(se(`error: backend ${e.config.backend} not found in registry`),e.config.backend=he.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(Ue==null?void 0:Ue.setWasmPaths)!="undefined")await Eb(e.config.wasmPath,e.config.wasmPlatformFetch);else throw new Error("backend error: attempting to use wasm backend but wasm path is not set");let a=await Y().getAsync("WASM_HAS_SIMD_SUPPORT"),s=await Y().getAsync("WASM_HAS_MULTITHREAD_SUPPORT");e.config.debug&&se(`wasm execution: ${a?"SIMD":"no SIMD"} ${s?"multithreaded":"singlethreaded"}`),e.config.debug&&!a&&se("warning: wasm simd support is not enabled")}try{await M2(e.config.backend),await ld(),IN()}catch(a){return se("error: cannot set backend:",e.config.backend,a),!1}}if(Ur()==="humangl"&&(Aa.set("CHECK_COMPUTATION_FOR_ERRORS",!1),Aa.set("WEBGL_CPU_FORWARD",!0),Aa.set("WEBGL_USE_SHAPES_UNIFORMS",!0),Aa.set("CPU_HANDOFF_SIZE_THRESHOLD",256),typeof e.config.deallocate!="undefined"&&e.config.deallocate&&(se("changing webgl: WEBGL_DELETE_TEXTURE_THRESHOLD:",!0),Aa.set("WEBGL_DELETE_TEXTURE_THRESHOLD",0)),zn().getGPGPUContext)){let n=await zn().getGPGPUContext().gl;e.config.debug&&se(`gl version:${n.getParameter(n.VERSION)} renderer:${n.getParameter(n.RENDERER)}`)}Ur(),E2(),await ld(),e.performance.initBackend=Math.trunc(oe()-r),e.config.backend=Ur(),await he.updateBackend(),_Ae()}return!0}function eg(e,t){for(let r of e){let n={kernelName:r,backendName:t.backend,kernelFunc:()=>{t.debug&&se("kernelFunc",r,t.backend)}};jn(n)}he.kernels=Ra(Ur()).map(r=>r.kernelName.toLowerCase())}var e3={};bs(e3,{all:()=>Q5,body:()=>qd,canvas:()=>J5,face:()=>Hd,gesture:()=>Zd,hand:()=>Kd,object:()=>Xd,options:()=>br,person:()=>Y5});var br={color:"rgba(173, 216, 230, 0.6)",labelColor:"rgba(173, 216, 230, 1)",shadowColor:"black",alpha:.5,font:'small-caps 16px "Segoe UI"',lineHeight:18,lineWidth:4,pointSize:2,roundRect:8,drawPoints:!1,drawLabels:!0,drawBoxes:!0,drawAttention:!0,drawGestures:!0,drawPolygons:!0,drawGaze:!0,fillPolygons:!1,useDepth:!0,useCurves:!1};var Ln=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},jl=e=>Math.round(e*180/Math.PI),Wa=(e,t=[!0,!0,!1])=>{let r=t[0]?127+Math.trunc(3*e):255,n=t[1]?127-Math.trunc(3*e):255,a=t[2]?127-Math.trunc(3*e):255;return`rgba(${r}, ${n}, ${a}, ${br.alpha})`};function Hl(e,t,r,n,a){n=n||0,e.fillStyle=a.useDepth&&n?Wa(n,n===-255?[!0,!1,!0]:[!0,!1,!1]):a.color,e.beginPath(),e.arc(t,r,a.pointSize,0,2*Math.PI),e.fill()}function Va(e,t,r,n,a,s){if(e.beginPath(),e.lineWidth=s.lineWidth,s.useCurves){let i=(t+t+n)/2,o=(r+r+a)/2;e.ellipse(i,o,n/2,a/2,0,0,2*Math.PI)}else e.moveTo(t+s.roundRect,r),e.lineTo(t+n-s.roundRect,r),e.quadraticCurveTo(t+n,r,t+n,r+s.roundRect),e.lineTo(t+n,r+a-s.roundRect),e.quadraticCurveTo(t+n,r+a,t+n-s.roundRect,r+a),e.lineTo(t+s.roundRect,r+a),e.quadraticCurveTo(t,r+a,t,r+a-s.roundRect),e.lineTo(t,r+s.roundRect),e.quadraticCurveTo(t,r,t+s.roundRect,r),e.closePath();e.stroke()}function K5(e,t,r){if(!(t.length<2)){e.beginPath(),e.moveTo(t[0][0],t[0][1]);for(let n of t){let a=n[2]||0;e.strokeStyle=r.useDepth&&a!==0?Wa(a):r.color,e.fillStyle=r.useDepth&&a!==0?Wa(a):r.color,e.lineTo(n[0],Math.round(n[1]))}e.stroke(),r.fillPolygons&&(e.closePath(),e.fill())}}function P9(e,t,r){if(!(t.length<2)){if(e.lineWidth=r.lineWidth,!r.useCurves||t.length<=2){K5(e,t,r);return}e.moveTo(t[0][0],t[0][1]);for(let n=0;n<t.length-2;n++){let a=(t[n][0]+t[n+1][0])/2,s=(t[n][1]+t[n+1][1])/2;e.quadraticCurveTo(t[n][0],t[n][1],a,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 X5(e,t,r,n=5){let a,s,i;e.beginPath(),e.moveTo(t[0],t[1]),e.lineTo(r[0],r[1]),a=Math.atan2(r[1]-t[1],r[0]-t[0]),s=n*Math.cos(a)+r[0],i=n*Math.sin(a)+r[1],e.moveTo(s,i),a+=1/3*(2*Math.PI),s=n*Math.cos(a)+r[0],i=n*Math.sin(a)+r[1],e.lineTo(s,i),a+=1/3*(2*Math.PI),s=n*Math.cos(a)+r[0],i=n*Math.sin(a)+r[1],e.lineTo(s,i),e.closePath(),e.stroke(),e.fill()}async function Hd(e,t,r){var s,i,o,l,u;let n=Ut(br,r);if(!t||!e)return;let a=Ln(e);if(!!a)for(let d of t){if(a.font=n.font,a.strokeStyle=n.color,a.fillStyle=n.color,n.drawBoxes&&Va(a,d.box[0],d.box[1],d.box[2],d.box[3],n),n.drawLabels){let h=[];if(h.push(`face: ${Math.trunc(100*d.score)}%`),d.genderScore&&h.push(`${d.gender||""} ${Math.trunc(100*d.genderScore)}%`),d.age&&h.push(`age: ${d.age||""}`),d.iris&&h.push(`distance: ${d.iris}`),d.real&&h.push(`real: ${Math.trunc(100*d.real)}%`),d.live&&h.push(`live: ${Math.trunc(100*d.live)}%`),d.emotion&&d.emotion.length>0){let p=d.emotion.map(c=>`${Math.trunc(100*c.score)}% ${c.emotion}`);p.length>3&&(p.length=3),h.push(p.join(" "))}d.rotation&&d.rotation.angle&&d.rotation.gaze&&(d.rotation.angle.roll&&h.push(`roll: ${jl(d.rotation.angle.roll)}\xB0 yaw:${jl(d.rotation.angle.yaw)}\xB0 pitch:${jl(d.rotation.angle.pitch)}\xB0`),d.rotation.gaze.bearing&&h.push(`gaze: ${jl(d.rotation.gaze.bearing)}\xB0`)),h.length===0&&h.push("face"),a.fillStyle=n.color;for(let p=h.length-1;p>=0;p--){let c=Math.max(d.box[0],0),f=p*n.lineHeight+d.box[1];n.shadowColor&&n.shadowColor!==""&&(a.fillStyle=n.shadowColor,a.fillText(h[p],c+5,f+16)),a.fillStyle=n.labelColor,a.fillText(h[p],c+4,f+15)}}if(a.lineWidth=2,d.mesh&&d.mesh.length>0){if(n.drawPoints){let h=Math.max(468,d.mesh.length);for(let p=0;p<h;p++)Hl(a,d.mesh[p][0],d.mesh[p][1],d.mesh[p][2],n)}if(n.drawAttention&&d.mesh.length>468)for(let h=468;h<d.mesh.length;h++)Hl(a,d.mesh[h][0],d.mesh[h][1],-255,n);if(n.drawPolygons){if(d.mesh.length>450)for(let h=0;h<Dl.length/3;h++){let p=[Dl[h*3+0],Dl[h*3+1],Dl[h*3+2]].map(c=>d.mesh[c]);K5(a,p,n)}if(d.annotations&&d.annotations.leftEyeIris&&d.annotations.leftEyeIris[0]){a.strokeStyle=n.useDepth?"rgba(255, 200, 255, 0.3)":n.color,a.beginPath();let h=Math.abs(d.annotations.leftEyeIris[3][0]-d.annotations.leftEyeIris[1][0])/2,p=Math.abs(d.annotations.leftEyeIris[4][1]-d.annotations.leftEyeIris[2][1])/2;a.ellipse(d.annotations.leftEyeIris[0][0],d.annotations.leftEyeIris[0][1],h,p,0,0,2*Math.PI),a.stroke(),n.fillPolygons&&(a.fillStyle=n.useDepth?"rgba(255, 255, 200, 0.3)":n.color,a.fill())}if(d.annotations&&d.annotations.rightEyeIris&&d.annotations.rightEyeIris[0]){a.strokeStyle=n.useDepth?"rgba(255, 200, 255, 0.3)":n.color,a.beginPath();let h=Math.abs(d.annotations.rightEyeIris[3][0]-d.annotations.rightEyeIris[1][0])/2,p=Math.abs(d.annotations.rightEyeIris[4][1]-d.annotations.rightEyeIris[2][1])/2;a.ellipse(d.annotations.rightEyeIris[0][0],d.annotations.rightEyeIris[0][1],h,p,0,0,2*Math.PI),a.stroke(),n.fillPolygons&&(a.fillStyle=n.useDepth?"rgba(255, 255, 200, 0.3)":n.color,a.fill())}if(n.drawGaze&&((s=d.rotation)==null?void 0:s.angle)&&typeof Path2D!="undefined"){a.strokeStyle="pink";let h=d.box[0]+d.box[2]/2-d.box[3]*jl(d.rotation.angle.yaw)/90,p=d.box[1]+d.box[3]/2+d.box[2]*jl(d.rotation.angle.pitch)/90,c=new Path2D(`
|
|
M ${d.box[0]+d.box[2]/2} ${d.box[1]}
|
|
C
|
|
${h} ${d.box[1]},
|
|
${h} ${d.box[1]+d.box[3]},
|
|
${d.box[0]+d.box[2]/2} ${d.box[1]+d.box[3]}
|
|
`),f=new Path2D(`
|
|
M ${d.box[0]} ${d.box[1]+d.box[3]/2}
|
|
C
|
|
${d.box[0]} ${p},
|
|
${d.box[0]+d.box[2]} ${p},
|
|
${d.box[0]+d.box[2]} ${d.box[1]+d.box[3]/2}
|
|
`);a.stroke(f),a.stroke(c)}if(n.drawGaze&&((o=(i=d.rotation)==null?void 0:i.gaze)==null?void 0:o.strength)&&((u=(l=d.rotation)==null?void 0:l.gaze)==null?void 0:u.bearing)&&d.annotations.leftEyeIris&&d.annotations.rightEyeIris&&d.annotations.leftEyeIris[0]&&d.annotations.rightEyeIris[0]){a.strokeStyle="pink",a.fillStyle="pink";let h=[d.annotations.leftEyeIris[0][0]+Math.sin(d.rotation.gaze.bearing)*d.rotation.gaze.strength*d.box[3],d.annotations.leftEyeIris[0][1]+Math.cos(d.rotation.gaze.bearing)*d.rotation.gaze.strength*d.box[2]];X5(a,[d.annotations.leftEyeIris[0][0],d.annotations.leftEyeIris[0][1]],[h[0],h[1]],4);let p=[d.annotations.rightEyeIris[0][0]+Math.sin(d.rotation.gaze.bearing)*d.rotation.gaze.strength*d.box[3],d.annotations.rightEyeIris[0][1]+Math.cos(d.rotation.gaze.bearing)*d.rotation.gaze.strength*d.box[2]];X5(a,[d.annotations.rightEyeIris[0][0],d.annotations.rightEyeIris[0][1]],[p[0],p[1]],4)}}}}}async function qd(e,t,r){var s;let n=Ut(br,r);if(!t||!e)return;let a=Ln(e);if(!!a){a.lineJoin="round";for(let i=0;i<t.length;i++){if(a.strokeStyle=n.color,a.fillStyle=n.color,a.lineWidth=n.lineWidth,a.font=n.font,n.drawBoxes&&t[i].box&&((s=t[i].box)==null?void 0:s.length)===4&&(Va(a,t[i].box[0],t[i].box[1],t[i].box[2],t[i].box[3],n),n.drawLabels&&(n.shadowColor&&n.shadowColor!==""&&(a.fillStyle=n.shadowColor,a.fillText(`body ${100*t[i].score}%`,t[i].box[0]+3,1+t[i].box[1]+n.lineHeight,t[i].box[2])),a.fillStyle=n.labelColor,a.fillText(`body ${100*t[i].score}%`,t[i].box[0]+2,0+t[i].box[1]+n.lineHeight,t[i].box[2]))),n.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||(a.fillStyle=n.useDepth&&t[i].keypoints[o].position[2]?Wa(t[i].keypoints[o].position[2]||0):n.color,Hl(a,t[i].keypoints[o].position[0],t[i].keypoints[o].position[1],0,n));if(n.drawLabels&&t[i].keypoints){a.font=n.font;for(let o of t[i].keypoints)!o.score||o.score===0||(a.fillStyle=n.useDepth&&o.position[2]?Wa(o.position[2]):n.color,a.fillText(`${o.part} ${Math.trunc(100*o.score)}%`,o.position[0]+4,o.position[1]+4))}if(n.drawPolygons&&t[i].keypoints&&t[i].annotations)for(let o of Object.values(t[i].annotations))for(let l of o)P9(a,l,n)}}}async function Kd(e,t,r){let n=Ut(br,r);if(!t||!e)return;let a=Ln(e);if(!!a){a.lineJoin="round",a.font=n.font;for(let s of t){if(n.drawBoxes&&(a.strokeStyle=n.color,a.fillStyle=n.color,Va(a,s.box[0],s.box[1],s.box[2],s.box[3],n),n.drawLabels&&(n.shadowColor&&n.shadowColor!==""&&(a.fillStyle=n.shadowColor,a.fillText(`hand:${Math.trunc(100*s.score)}%`,s.box[0]+3,1+s.box[1]+n.lineHeight,s.box[2])),a.fillStyle=n.labelColor,a.fillText(`hand:${Math.trunc(100*s.score)}%`,s.box[0]+2,0+s.box[1]+n.lineHeight,s.box[2])),a.stroke()),n.drawPoints&&s.keypoints&&s.keypoints.length>0)for(let i of s.keypoints)a.fillStyle=n.useDepth?Wa(i[2]||0):n.color,Hl(a,i[0],i[1],0,n);if(n.drawLabels&&s.annotations){let i=(o,l)=>{if(!o||o.length===0||!o[0])return;let u=o[o.length-1][2]||0;a.fillStyle=n.useDepth?Wa(u):n.color,a.fillText(l,o[o.length-1][0]+4,o[o.length-1][1]+4)};a.font=n.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(n.drawPolygons&&s.annotations){let i=o=>{if(!(!o||o.length===0||!o[0]))for(let l=0;l<o.length;l++){a.beginPath();let u=o[l][2]||0;a.strokeStyle=n.useDepth?Wa(l*u):n.color,a.moveTo(o[l>0?l-1:0][0],o[l>0?l-1:0][1]),a.lineTo(o[l][0],o[l][1]),a.stroke()}};a.lineWidth=n.lineWidth,i(s.annotations.index),i(s.annotations.middle),i(s.annotations.ring),i(s.annotations.pinky),i(s.annotations.thumb)}}}}async function Xd(e,t,r){let n=Ut(br,r);if(!t||!e)return;let a=Ln(e);if(!!a){a.lineJoin="round",a.font=n.font;for(let s of t)if(n.drawBoxes){if(a.strokeStyle=n.color,a.fillStyle=n.color,Va(a,s.box[0],s.box[1],s.box[2],s.box[3],n),n.drawLabels){let i=`${s.label} ${Math.round(100*s.score)}%`;n.shadowColor&&n.shadowColor!==""&&(a.fillStyle=n.shadowColor,a.fillText(i,s.box[0]+3,1+s.box[1]+n.lineHeight,s.box[2])),a.fillStyle=n.labelColor,a.fillText(i,s.box[0]+2,0+s.box[1]+n.lineHeight,s.box[2])}a.stroke()}}}async function Zd(e,t,r){let n=Ut(br,r);if(!(!t||!e)&&n.drawGestures){let a=Ln(e);if(!a)return;a.font=n.font,a.fillStyle=n.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 u=o[1]>0?`#${o[1]}`:"",d=`${o[0]} ${u}: ${l[1]}`;n.shadowColor&&n.shadowColor!==""&&(a.fillStyle=n.shadowColor,a.fillText(d,8,2+s*n.lineHeight)),a.fillStyle=n.labelColor,a.fillText(d,6,0+s*n.lineHeight),s+=1}}}}var Z5=0;async function Y5(e,t,r){let n=Ut(br,r);if(!t||!e)return;let a=Ln(e);if(!!a){a.lineJoin="round",a.font=n.font;for(let s=0;s<t.length;s++)if(n.drawBoxes){if(a.strokeStyle=n.color,a.fillStyle=n.color,Va(a,t[s].box[0],t[s].box[1],t[s].box[2],t[s].box[3],n),n.drawLabels){let i=`person #${s}`;n.shadowColor&&n.shadowColor!==""&&(a.fillStyle=n.shadowColor,a.fillText(i,t[s].box[0]+3,1+t[s].box[1]+n.lineHeight,t[s].box[2])),a.fillStyle=n.labelColor,a.fillText(i,t[s].box[0]+2,0+t[s].box[1]+n.lineHeight,t[s].box[2])}a.stroke()}}}async function J5(e,t){if(!e||!t)return;let r=Ln(t);!r||r.drawImage(e,0,0)}async function Q5(e,t,r){if(!t||!t.performance||!t||!e)return null;let n=oe(),a=Ut(br,r),s=Promise.all([Hd(e,t.face,a),qd(e,t.body,a),Kd(e,t.hand,a),Xd(e,t.object,a),Zd(e,t.gesture,a)]);return Z5=he.perfadd?Z5+Math.round(oe()-n):Math.round(oe()-n),t.performance.draw=Z5,s}var Yd=.1,t3=.5;function OAe(e,t,r){let n=!1,a=r.length-1;for(let s=0;s<r.length;a=s++)r[s].y>t!=r[a].y>t&&e<(r[a].x-r[s].x)*(t-r[s].y)/(r[a].y-r[s].y)+r[s].x&&(n=!n);return n}async function _9(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,n=await e.tensor.buffer(),a=[];for(let i of Jn.silhouette)a.push({x:(e.mesh[i][0]-e.box[0])/e.box[2],y:(e.mesh[i][1]-e.box[1])/e.box[3]});Yd&&Yd>0&&(a=a.map(i=>({x:i.x>.5?i.x+Yd:i.x-Yd,y:i.y>.5?i.y+Yd:i.y-Yd})));for(let i=0;i<t;i++)for(let o=0;o<r;o++)OAe(i/t,o/t,a)||(n.set(t3*n.get(0,o,i,0),0,o,i,0),n.set(t3*n.get(0,o,i,1),0,o,i,1),n.set(t3*n.get(0,o,i,2),0,o,i,2));let s=n.toTensor();return re(n),s}var LAe=e=>{let t=(h,p)=>Math.atan2(h[1]-p[1],h[0]-p[0]);if(!e.annotations.rightEyeIris||!e.annotations.leftEyeIris)return{bearing:0,strength:0};let r=[0,-.1],n=1,a=(e.mesh[33][2]||0)>(e.mesh[263][2]||0),s=a?e.mesh[473]:e.mesh[468],i=a?[(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=a?[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],n*(s[1]-i[1])/o[1]-r[1]],u=Math.sqrt(l[0]*l[0]+l[1]*l[1]);return u=Math.min(u,e.boxRaw[2]/2,e.boxRaw[3]/2),{bearing:(t([0,0],l)+Math.PI/2)%Math.PI,strength:u}},z9=(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},n=(m,g)=>{let y=m[0]-g[0],A=m[1]-g[1],x=m[2]-g[2];return[y,A,x]},a=(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,S,T,E]=m,R,_,M;return x<1?x>-1?(M=Math.asin(x),_=Math.atan2(-S,g),R=Math.atan2(-v,b)):(M=-Math.PI/2,_=-Math.atan2(T,E),R=0):(M=Math.PI/2,_=Math.atan2(T,E),R=0),isNaN(R)&&(R=0),isNaN(_)&&(_=0),isNaN(M)&&(M=0),{pitch:2*-R,yaw:2*-_,roll:2*-M}},i=e.meshRaw;if(!i||i.length<300)return{angle:{pitch:0,yaw:0,roll:0},matrix:[1,0,0,0,1,0,0,0,1],gaze:{bearing:0,strength:0}};let o=Math.max(e.boxRaw[2]*t[0],e.boxRaw[3]*t[1])/1.5,l=[i[10],i[152],i[234],i[454]].map(m=>[m[0]*t[0]/o,m[1]*t[1]/o,m[2]]),u=r(n(l[1],l[0])),d=r(n(l[3],l[2])),h=r(a(d,u));d=a(u,h);let p=[d[0],d[1],d[2],u[0],u[1],u[2],h[0],h[1],h[2]],c=s(p),f=i.length===478?LAe(e):{bearing:0,strength:0};return{angle:c,matrix:p,gaze:f}};var r3=async(e,t)=>{var c,f,m,g,y,A,x,b,v,S,T,E,R,_,M,I,z,O,j,X,D,Q;let r=oe(),n,a,s,i,o,l,u,d,h=[];e.state="run:face";let p=await CC(t,e.config);if(e.performance.face=he.perfadd?(e.performance.face||0)+Math.trunc(oe()-r):Math.trunc(oe()-r),!t.shape||t.shape.length!==4)return[];if(!p)return[];for(let V=0;V<p.length;V++){if(e.analyze("Get Face"),!p[V].tensor||p[V].tensor.isDisposedInternal){se("Face object is disposed:",p[V].tensor);continue}if((c=e.config.face.detector)!=null&&c.mask){let ae=await _9(p[V]);re(p[V].tensor),p[V].tensor=ae}let ee=p[V].mesh&&p[V].mesh.length>200?z9(p[V],[t.shape[2],t.shape[1]]):null;e.analyze("Start Emotion:"),e.config.async?i=(f=e.config.face.emotion)!=null&&f.enabled?d5(p[V].tensor||ct([]),e.config,V,p.length):[]:(e.state="run:emotion",r=oe(),i=(m=e.config.face.emotion)!=null&&m.enabled?await d5(p[V].tensor||ct([]),e.config,V,p.length):[],e.performance.emotion=he.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&&g.enabled?Ub(p[V].tensor||ct([]),e.config,V,p.length):0:(e.state="run:antispoof",r=oe(),l=(y=e.config.face.antispoof)!=null&&y.enabled?await Ub(p[V].tensor||ct([]),e.config,V,p.length):0,e.performance.antispoof=he.perfadd?(e.performance.antispoof||0)+Math.trunc(oe()-r):Math.trunc(oe()-r)),e.analyze("End AntiSpoof:"),e.analyze("Start Liveness:"),e.config.async?u=(A=e.config.face.liveness)!=null&&A.enabled?R5(p[V].tensor||ct([]),e.config,V,p.length):0:(e.state="run:liveness",r=oe(),u=(x=e.config.face.liveness)!=null&&x.enabled?await R5(p[V].tensor||ct([]),e.config,V,p.length):0,e.performance.liveness=he.perfadd?(e.performance.antispoof||0)+Math.trunc(oe()-r):Math.trunc(oe()-r)),e.analyze("End Liveness:"),e.analyze("Start GEAR:"),e.config.async?a=(b=e.config.face.gear)!=null&&b.enabled?zb(p[V].tensor||ct([]),e.config,V,p.length):null:(e.state="run:gear",r=oe(),a=(v=e.config.face.gear)!=null&&v.enabled?await zb(p[V].tensor||ct([]),e.config,V,p.length):null,e.performance.gear=Math.trunc(oe()-r)),e.analyze("End GEAR:"),e.analyze("Start SSRNet:"),e.config.async?(n=(S=e.config.face.ssrnet)!=null&&S.enabled?Db(p[V].tensor||ct([]),e.config,V,p.length):null,s=(T=e.config.face.ssrnet)!=null&&T.enabled?Wb(p[V].tensor||ct([]),e.config,V,p.length):null):(e.state="run:ssrnet",r=oe(),n=(E=e.config.face.ssrnet)!=null&&E.enabled?await Db(p[V].tensor||ct([]),e.config,V,p.length):null,s=(R=e.config.face.ssrnet)!=null&&R.enabled?await Wb(p[V].tensor||ct([]),e.config,V,p.length):null,e.performance.ssrnet=Math.trunc(oe()-r)),e.analyze("End SSRNet:"),e.analyze("Start MobileFaceNet:"),e.config.async?o=(_=e.config.face.mobilefacenet)!=null&&_.enabled?h5(p[V].tensor||ct([]),e.config,V,p.length):null:(e.state="run:mobilefacenet",r=oe(),o=(M=e.config.face.mobilefacenet)!=null&&M.enabled?await h5(p[V].tensor||ct([]),e.config,V,p.length):null,e.performance.mobilefacenet=Math.trunc(oe()-r)),e.analyze("End MobileFaceNet:"),e.analyze("Start Description:"),e.config.async?d=(I=e.config.face.description)!=null&&I.enabled?A5(p[V].tensor||ct([]),e.config,V,p.length):null:(e.state="run:description",r=oe(),d=(z=e.config.face.description)!=null&&z.enabled?await A5(p[V].tensor||ct([]),e.config,V,p.length):null,e.performance.description=he.perfadd?(e.performance.description||0)+Math.trunc(oe()-r):Math.trunc(oe()-r)),e.analyze("End Description:"),e.config.async&&([n,s,i,o,d,a,l,u]=await Promise.all([n,s,i,o,d,a,l,u])),e.analyze("Finish Face:"),((O=e.config.face.ssrnet)==null?void 0:O.enabled)&&n&&s&&(d={...d,age:n.age,gender:s.gender,genderScore:s.genderScore}),((j=e.config.face.gear)==null?void 0:j.enabled)&&a&&(d={...d,age:a.age,gender:a.gender,genderScore:a.genderScore,race:a.race}),((X=e.config.face.mobilefacenet)==null?void 0:X.enabled)&&o&&(d.descriptor=o),(D=e.config.face.iris)!=null&&D.enabled;let J=p[V].annotations&&p[V].annotations.leftEyeIris&&p[V].annotations.leftEyeIris[0]&&p[V].annotations.rightEyeIris&&p[V].annotations.rightEyeIris[0]&&p[V].annotations.leftEyeIris.length>0&&p[V].annotations.rightEyeIris.length>0&&p[V].annotations.leftEyeIris[0]!==null&&p[V].annotations.rightEyeIris[0]!==null?Math.max(Math.abs(p[V].annotations.leftEyeIris[3][0]-p[V].annotations.leftEyeIris[1][0]),Math.abs(p[V].annotations.rightEyeIris[4][1]-p[V].annotations.rightEyeIris[2][1]))/t.shape[2]:0,ie=(Q=e.config.face.detector)!=null&&Q.return?rt(p[V].tensor):null;re(p[V].tensor),p[V].tensor&&delete p[V].tensor;let Z={...p[V],id:V};d!=null&&d.age&&(Z.age=d.age),d!=null&&d.gender&&(Z.gender=d.gender),d!=null&&d.genderScore&&(Z.genderScore=d==null?void 0:d.genderScore),d!=null&&d.descriptor&&(Z.embedding=d==null?void 0:d.descriptor),d!=null&&d.race&&(Z.race=d==null?void 0:d.race),i&&(Z.emotion=i),l&&(Z.real=l),u&&(Z.live=u),J&&J!==0&&(Z.iris=Math.trunc(500/J/11.7)/100),ee&&(Z.rotation=ee),ie&&(Z.tensor=ie),h.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),h};var O9=e=>{if(!e)return[];let t=[];for(let r=0;r<e.length;r++){let n=e[r].keypoints.find(l=>l.part==="leftWrist"),a=e[r].keypoints.find(l=>l.part==="rightWrist"),s=e[r].keypoints.find(l=>l.part==="nose");s&&n&&a&&n.position[1]<s.position[1]&&a.position[1]<s.position[1]?t.push({body:r,gesture:"i give up"}):s&&n&&n.position[1]<s.position[1]?t.push({body:r,gesture:"raise left hand"}):s&&a&&a.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},D9=e=>{if(!e)return[];let t=[];for(let r=0;r<e.length;r++)if(e[r].mesh&&e[r].mesh.length>450){let n=(e[r].mesh[33][2]||0)-(e[r].mesh[263][2]||0),a=e[r].mesh[33][0]-e[r].mesh[263][0];Math.abs(n/a)<=.15?t.push({face:r,gesture:"facing center"}):t.push({face:r,gesture:`facing ${n<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},L9=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 n=e[r].annotations.leftEyeIris[3][0]-e[r].annotations.leftEyeIris[1][0],a=e[r].annotations.leftEyeIris[4][1]-e[r].annotations.leftEyeIris[2][1],s=Math.abs(n*a),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),u=!1;Math.abs(s-l)/Math.max(s,l)<.25&&(u=!0,t.push({iris:r,gesture:"facing center"}));let h=Math.abs(e[r].mesh[263][0]-e[r].annotations.leftEyeIris[0][0])/e[r].box[2],p=Math.abs(e[r].mesh[33][0]-e[r].annotations.rightEyeIris[0][0])/e[r].box[2];(h>.06||p>.06)&&(u=!1),h>p?h>.05&&t.push({iris:r,gesture:"looking right"}):p>.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)&&(u=!1),(f<.01||c<.01)&&t.push({iris:r,gesture:"looking down"}),(f>.022||c>.022)&&t.push({iris:r,gesture:"looking up"}),u&&t.push({iris:r,gesture:"looking center"})}return t},B9=e=>{if(!e)return[];let t=[];for(let r=0;r<e.length;r++){let n=[];if(e[r].annotations)for(let[a,s]of Object.entries(e[r].annotations))a!=="palmBase"&&Array.isArray(s)&&s[0]&&n.push({name:a.toLowerCase(),position:s[0]});if(n&&n.length>0){let a=n.reduce((i,o)=>(i.position[2]||0)<(o.position[2]||0)?i:o);t.push({hand:r,gesture:`${a.name} forward`});let s=n.reduce((i,o)=>i.position[1]<o.position[1]?i:o);t.push({hand:r,gesture:`${s.name} up`})}if(e[r].keypoints){let a=QC(e[r].keypoints);for(let s of a)t.push({hand:r,gesture:s.name})}}return t};var Ce={face:[],body:[],hand:[],gesture:[],object:[],persons:[],performance:{},timestamp:0,error:null},n3=0;function W9(e,t){var i,o,l,u,d,h,p,c,f,m,g,y,A,x,b,v,S,T,E,R,_,M,I,z,O,j,X;let r=oe();if(!e)return{face:[],body:[],hand:[],gesture:[],object:[],persons:[],performance:{},timestamp:0,error:null};let n=Date.now()-e.timestamp,a=n<1e3?8-Math.log(n+1):1;if(e.canvas&&(Ce.canvas=e.canvas),e.error&&(Ce.error=e.error),!Ce.body||e.body.length!==Ce.body.length)Ce.body=JSON.parse(JSON.stringify(e.body));else for(let D=0;D<e.body.length;D++){let Q=e.body[D].box.map((Z,ae)=>((a-1)*Ce.body[D].box[ae]+Z)/a),V=e.body[D].boxRaw.map((Z,ae)=>((a-1)*Ce.body[D].boxRaw[ae]+Z)/a),ee=e.body[D].keypoints.map((Z,ae)=>{var de,Ae,be,Ee,Me,De,Be,Ze,ot;return{score:Z.score,part:Z.part,position:[Ce.body[D].keypoints[ae]?((a-1)*(Ce.body[D].keypoints[ae].position[0]||0)+(Z.position[0]||0))/a:Z.position[0],Ce.body[D].keypoints[ae]?((a-1)*(Ce.body[D].keypoints[ae].position[1]||0)+(Z.position[1]||0))/a:Z.position[1],Ce.body[D].keypoints[ae]?((a-1)*(Ce.body[D].keypoints[ae].position[2]||0)+(Z.position[2]||0))/a:Z.position[2]],positionRaw:[Ce.body[D].keypoints[ae]?((a-1)*(Ce.body[D].keypoints[ae].positionRaw[0]||0)+(Z.positionRaw[0]||0))/a:Z.positionRaw[0],Ce.body[D].keypoints[ae]?((a-1)*(Ce.body[D].keypoints[ae].positionRaw[1]||0)+(Z.positionRaw[1]||0))/a:Z.positionRaw[1],Ce.body[D].keypoints[ae]?((a-1)*(Ce.body[D].keypoints[ae].positionRaw[2]||0)+(Z.positionRaw[2]||0))/a:Z.positionRaw[2]],distance:[Ce.body[D].keypoints[ae]?((a-1)*(((de=Ce.body[D].keypoints[ae].distance)==null?void 0:de[0])||0)+(((Ae=Z.distance)==null?void 0:Ae[0])||0))/a:(be=Z.distance)==null?void 0:be[0],Ce.body[D].keypoints[ae]?((a-1)*(((Ee=Ce.body[D].keypoints[ae].distance)==null?void 0:Ee[1])||0)+(((Me=Z.distance)==null?void 0:Me[1])||0))/a:(De=Z.distance)==null?void 0:De[1],Ce.body[D].keypoints[ae]?((a-1)*(((Be=Ce.body[D].keypoints[ae].distance)==null?void 0:Be[2])||0)+(((Ze=Z.distance)==null?void 0:Ze[2])||0))/a:(ot=Z.distance)==null?void 0:ot[2]]}}),J={},ie={connected:{}};(o=(i=t.body)==null?void 0:i.modelPath)!=null&&o.includes("efficientpose")?ie=U0:(u=(l=t.body)==null?void 0:l.modelPath)!=null&&u.includes("blazepose")?ie=D0:(h=(d=t.body)==null?void 0:d.modelPath)!=null&&h.includes("movenet")&&(ie=Qh);for(let[Z,ae]of Object.entries(ie.connected)){let de=[];for(let Ae=0;Ae<ae.length-1;Ae++){let be=ee.find(Me=>Me.part===ae[Ae]),Ee=ee.find(Me=>Me.part===ae[Ae+1]);be&&Ee&&de.push([be.position,Ee.position])}J[Z]=de}Ce.body[D]={...e.body[D],box:Q,boxRaw:V,keypoints:ee,annotations:J}}if(!Ce.hand||e.hand.length!==Ce.hand.length)Ce.hand=JSON.parse(JSON.stringify(e.hand));else for(let D=0;D<e.hand.length;D++){let Q=e.hand[D].box.map((ie,Z)=>((a-1)*Ce.hand[D].box[Z]+ie)/a),V=e.hand[D].boxRaw.map((ie,Z)=>((a-1)*Ce.hand[D].boxRaw[Z]+ie)/a);Ce.hand[D].keypoints.length!==e.hand[D].keypoints.length&&(Ce.hand[D].keypoints=e.hand[D].keypoints);let ee=e.hand[D].keypoints&&e.hand[D].keypoints.length>0?e.hand[D].keypoints.map((ie,Z)=>ie.map((ae,de)=>((a-1)*(Ce.hand[D].keypoints[Z][de]||1)+(ae||0))/a)):[],J={};if(Object.keys(Ce.hand[D].annotations).length!==Object.keys(e.hand[D].annotations).length)Ce.hand[D].annotations=e.hand[D].annotations,J=Ce.hand[D].annotations;else if(e.hand[D].annotations)for(let ie of Object.keys(e.hand[D].annotations))J[ie]=e.hand[D].annotations[ie]&&e.hand[D].annotations[ie][0]?e.hand[D].annotations[ie].map((Z,ae)=>Z.map((de,Ae)=>((a-1)*Ce.hand[D].annotations[ie][ae][Ae]+de)/a)):null;Ce.hand[D]={...e.hand[D],box:Q,boxRaw:V,keypoints:ee,annotations:J}}if(!Ce.face||e.face.length!==Ce.face.length)Ce.face=JSON.parse(JSON.stringify(e.face));else for(let D=0;D<e.face.length;D++){let Q=e.face[D].box.map((ee,J)=>((a-1)*Ce.face[D].box[J]+ee)/a),V=e.face[D].boxRaw.map((ee,J)=>((a-1)*Ce.face[D].boxRaw[J]+ee)/a);if(e.face[D].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=(p=e.face[D].rotation)==null?void 0:p.matrix,ee.angle={roll:((a-1)*(((f=(c=Ce.face[D].rotation)==null?void 0:c.angle)==null?void 0:f.roll)||0)+(((g=(m=e.face[D].rotation)==null?void 0:m.angle)==null?void 0:g.roll)||0))/a,yaw:((a-1)*(((A=(y=Ce.face[D].rotation)==null?void 0:y.angle)==null?void 0:A.yaw)||0)+(((b=(x=e.face[D].rotation)==null?void 0:x.angle)==null?void 0:b.yaw)||0))/a,pitch:((a-1)*(((S=(v=Ce.face[D].rotation)==null?void 0:v.angle)==null?void 0:S.pitch)||0)+(((E=(T=e.face[D].rotation)==null?void 0:T.angle)==null?void 0:E.pitch)||0))/a},ee.gaze={bearing:((a-1)*(((_=(R=Ce.face[D].rotation)==null?void 0:R.gaze)==null?void 0:_.bearing)||0)+(((I=(M=e.face[D].rotation)==null?void 0:M.gaze)==null?void 0:I.bearing)||0))/a,strength:((a-1)*(((O=(z=Ce.face[D].rotation)==null?void 0:z.gaze)==null?void 0:O.strength)||0)+(((X=(j=e.face[D].rotation)==null?void 0:j.gaze)==null?void 0:X.strength)||0))/a},Ce.face[D]={...e.face[D],rotation:ee,box:Q,boxRaw:V}}Ce.face[D]={...e.face[D],box:Q,boxRaw:V}}if(!Ce.object||e.object.length!==Ce.object.length)Ce.object=JSON.parse(JSON.stringify(e.object));else for(let D=0;D<e.object.length;D++){let Q=e.object[D].box.map((ee,J)=>((a-1)*Ce.object[D].box[J]+ee)/a),V=e.object[D].boxRaw.map((ee,J)=>((a-1)*Ce.object[D].boxRaw[J]+ee)/a);Ce.object[D]={...e.object[D],box:Q,boxRaw:V}}if(e.persons){let D=e.persons;if(!Ce.persons||D.length!==Ce.persons.length)Ce.persons=JSON.parse(JSON.stringify(D));else for(let Q=0;Q<D.length;Q++)Ce.persons[Q].box=D[Q].box.map((V,ee)=>((a-1)*Ce.persons[Q].box[ee]+V)/a)}e.gesture&&(Ce.gesture=e.gesture);let s=oe();return n3=he.perfadd?n3+Math.round(s-r):Math.round(s-r),e.performance&&(Ce.performance={...e.performance,interpolate:n3}),Ce}var i3={};bs(i3,{distance:()=>nc,match:()=>s3,similarity:()=>a3});function nc(e,t,r={order:2,multiplier:25}){let n=0;for(let a=0;a<e.length;a++){let s=!r.order||r.order===2?e[a]-t[a]:Math.abs(e[a]-t[a]);n+=!r.order||r.order===2?s*s:s**r.order}return(r.multiplier||20)*n}var V9=(e,t,r,n)=>{if(e===0)return 1;let a=t===2?Math.sqrt(e):e**(1/t),s=(1-a/100-r)/(n-r);return Math.max(Math.min(s,1),0)};function a3(e,t,r={order:2,multiplier:25,min:.2,max:.8}){let n=nc(e,t,r);return V9(n,r.order||2,r.min||0,r.max||1)}function s3(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 n=Number.MAX_SAFE_INTEGER,a=-1;for(let i=0;i<t.length;i++){let o=nc(e,t[i],r);if(o<n&&(n=o,a=i),n<(r.threshold||0))break}let s=V9(n,r.order||2,r.min||0,r.max||1);return{index:a,distance:n,similarity:s}}function U9(e,t,r,n,a){var o,l,u,d,h,p,c,f,m,g,y,A,x,b,v,S;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 n)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===((u=E.body)==null?void 0:u.id)?(d=E.gestures)==null||d.push(O):O.hand!==void 0&&O.hand===((p=(h=E.hands)==null?void 0:h.left)==null?void 0:p.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=[],_=[],M=O=>{O&&O.length===4&&(R.push(O[0],O[0]+O[2]),_.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((S=(v=E.hands)==null?void 0:v.right)==null?void 0:S.box);let I=Math.min(...R),z=Math.min(..._);E.box=[I,z,Math.max(...R)-I,Math.max(..._)-z],a&&a[1]&&a[2]&&(E.boxRaw=[E.box[0]/a[2],E.box[1]/a[1],E.box[2]/a[2],E.box[3]/a[1]]),i.push(E)}return i}var cg=`
|
|
/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==`,fg=`
|
|
/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 jAe(e){let t=(a,s="application/octet-stream")=>fetch(`data:${s};base64,${a}`).then(i=>i.blob()),r,n;switch(e.config.warmup){case"face":r=await t(cg);break;case"body":case"full":r=await t(fg);break;default:r=null}if(r){let a=await createImageBitmap(r);n=await e.detect(a,e.config),a.close()}return n}async function HAe(e){return new Promise(t=>{let r;switch(e.config.warmup){case"face":r="data:image/jpeg;base64,"+cg;break;case"full":case"body":r="data:image/jpeg;base64,"+fg;break;default:r=null}let n;if(typeof Image!="undefined")n=new Image;else if(he.Image)n=new he.Image;else return;n.onload=async()=>{let a=Kr(n.naturalWidth,n.naturalHeight);if(!a)se("Warmup: Canvas not found"),t(void 0);else{let s=a.getContext("2d");s&&s.drawImage(n,0,0);let i=await e.image(a),o=await e.detect(i.tensor,e.config);t(o)}},r?n.src=r:t(void 0)})}async function qAe(e){let t=a=>Buffer.from(a,"base64"),r;e.config.warmup==="face"?r=t(cg):r=t(fg);let n;if("node"in Ue){let a=(void 0).decodeJpeg(r),s=a.expandDims(0);e.tf.dispose(a),n=await e.detect(s,e.config),e.tf.dispose(s)}else e.config.debug&&se("Warmup tfjs-node not loaded");return n}async function KAe(e){let t;return typeof createImageBitmap=="function"?t=await jAe(e):typeof Image!="undefined"||he.Canvas!==void 0?t=await HAe(e):t=await qAe(e),t}async function XAe(e){let t=Ur(),r=zn();if(t!=="webgl"&&t!=="humangl"||!r||!r.checkCompileCompletion)return;Y().set("ENGINE_COMPILE_ONLY",!0);let n=nr().state.numTensors,a=[];for(let[o,l]of Object.entries(e).filter(([u,d])=>u!==null&&d!==null)){let u=l.inputs&&l.inputs[0]&&l.inputs[0].shape?[...l.inputs[0].shape]:[1,64,64,3],d=l.inputs&&l.inputs[0]&&l.inputs[0].dtype?l.inputs[0].dtype:"float32";for(let p=0;p<u.length;p++)u[p]===-1&&(u[p]=p===0?1:64);let h=Pt(u,d);try{let p=l.execute(h);a.push(o),Array.isArray(p)?p.forEach(c=>re(c)):re(p)}catch(p){se("compile fail model:",o)}re(h)}let s=await r.checkCompileCompletionAsync();r.getUniformLocations(),se("compile pass models:",a),se("compile pass kernels:",s.length),Y().set("ENGINE_COMPILE_ONLY",!1);let i=nr().state.numTensors;i-n>0&&se("tensor leak:",i-n)}async function G9(e,t){let r=oe();return e.state="warmup",t&&(e.config=Ut(e.config,t)),!e.config.warmup||e.config.warmup.length===0||e.config.warmup==="none"?{face:[],body:[],hand:[],gesture:[],object:[],performance:e.performance,timestamp:oe(),persons:[],error:null}:new Promise(async n=>{await XAe(e.models);let a=await KAe(e),s=oe();e.config.debug&&se("warmup",e.config.warmup,Math.round(s-r),"ms"),e.emit("warmup"),n(a)})}var Jd,ac,sc,mg,o3=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");hp(this,Jd,void 0);hp(this,ac,void 0);hp(this,sc,void 0);fe(this,"gl");fe(this,"analyze",(...t)=>{if(!pp(this,ac))return;let r=this.tf.engine().state.numTensors,n=pp(this,Jd);cp(this,Jd,r);let a=r-n;a!==0&&se(...t,a)});hp(this,mg,t=>{if(!pp(this,sc))return null;if(!t)return"input is not defined";if(this.env.node&&!(t instanceof nt))return"input must be a tensor";try{this.tf.getBackend()}catch(r){return"backend not loaded"}return null});fe(this,"similarity",a3);fe(this,"distance",nc);fe(this,"match",s3);fe(this,"emit",t=>{var r;this.events&&this.events.dispatchEvent&&((r=this.events)==null||r.dispatchEvent(new Event(t)))});this.env=he,vs.wasmPath=Hh["tfjs-core"].includes("-")?"https://vladmandic.github.io/tfjs/dist/":`https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@${C2}/dist/`,vs.modelBasePath=he.browser?"../models/":"file://models/",vs.backend=he.browser?"humangl":"tensorflow",this.version=$b,Object.defineProperty(this,"version",{value:$b}),this.config=JSON.parse(JSON.stringify(vs)),Object.seal(this.config),this.config.cacheModels=typeof indexedDB!="undefined",t&&(this.config=Ut(this.config,t)),xN(this.config),this.tf=Ue,this.state="idle",cp(this,Jd,0),cp(this,ac,!1),cp(this,sc,!1),this.performance={},this.events=typeof EventTarget!="undefined"?new EventTarget:void 0,this.models=new rc,this.draw={options:br,canvas:(r,n)=>J5(r,n),face:(r,n,a)=>Hd(r,n,a),body:(r,n,a)=>qd(r,n,a),hand:(r,n,a)=>Kd(r,n,a),gesture:(r,n,a)=>Zd(r,n,a),object:(r,n,a)=>Xd(r,n,a),person:(r,n,a)=>Y5(r,n,a),all:(r,n,a)=>Q5(r,n,a)},this.result={face:[],body:[],hand:[],gesture:[],object:[],performance:{},timestamp:0,persons:[],error:null},this.process={tensor:null,canvas:null},this.faceTriangulation=RC,this.faceUVMap=MC,this.gl=Ct,this.emit("create")}reset(){let t=this.config.backend;this.config=JSON.parse(JSON.stringify(vs)),this.config.backend=t}validate(t){return q1(vs,t||this.config)}now(){return oe()}image(t,r=!0){return Fd(t,this.config,r)}async segmentation(t,r){return R9(t,r,this.config)}enhance(t){return y5(t)}compare(t,r){return AN(this.config,t,r)}async init(){await hg(this,!0),await this.tf.ready()}async load(t){this.state="load";let r=oe(),n=Object.values(this.models).filter(i=>i).length;t&&(this.config=Ut(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 hg(this)||se("error: backend check failed"),await ld(),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 H5(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!==n&&(await q5(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 W9(t,this.config)}async warmup(t){let r=oe(),n=await G9(this,t),a=oe();return this.performance.warmup=Math.trunc(a-r),n}async profile(t,r){let n=await this.tf.profile(()=>this.detect(t,r)),a={};for(let o of n.kernels)a[o.name]?a[o.name]+=o.kernelTimeMs:a[o.name]=o.kernelTimeMs;let s=[];Object.entries(a).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 n=>{var g,y,A,x,b,v,S,T,E,R,_,M,I,z,O,j,X,D,Q,V,ee,J;this.state="config";let a;this.config=Ut(this.config,r),this.state="check";let s=pp(this,mg).call(this,t);s&&(se(s,t),this.emit("error"),n({face:[],body:[],hand:[],gesture:[],object:[],performance:this.performance,timestamp:oe(),persons:[],error:s}));let i=oe();await hg(this),await this.load(),a=oe(),this.state="image";let o=await Fd(t,this.config);if(this.process=o,this.performance.inputProcess=this.env.perfadd?(this.performance.inputProcess||0)+Math.trunc(oe()-a):Math.trunc(oe()-a),this.analyze("Get Image:"),!o.tensor){this.config.debug&&se("could not convert input to tensor"),this.emit("error"),n({face:[],body:[],hand:[],gesture:[],object:[],performance:this.performance,timestamp:oe(),persons:[],error:"could not convert input to tensor"});return}this.emit("image"),a=oe(),this.config.skipAllowed=await yN(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()-a):Math.trunc(oe()-a),this.analyze("Check Changed:");let l=[],u=[],d=[],h=[];this.state="detect:face",this.config.async?(l=this.config.face.enabled?r3(this,o.tensor):[],this.performance.face&&delete this.performance.face):(a=oe(),l=this.config.face.enabled?await r3(this,o.tensor):[],this.performance.face=this.env.perfadd?(this.performance.face||0)+Math.trunc(oe()-a):Math.trunc(oe()-a)),this.config.async&&(this.config.body.maxDetected===-1||this.config.hand.maxDetected===-1)&&(l=await l),this.analyze("Start Body:"),this.state="detect:body";let p=this.config.body.maxDetected===-1?Ut(this.config,{body:{maxDetected:this.config.face.enabled?1*l.length:1}}):this.config;this.config.async?((g=this.config.body.modelPath)!=null&&g.includes("posenet")?u=this.config.body.enabled?U5(o.tensor,p):[]:(y=this.config.body.modelPath)!=null&&y.includes("blazepose")?u=this.config.body.enabled?t5(o.tensor,p):[]:(A=this.config.body.modelPath)!=null&&A.includes("efficientpose")?u=this.config.body.enabled?l5(o.tensor,p):[]:(x=this.config.body.modelPath)!=null&&x.includes("movenet")&&(u=this.config.body.enabled?z5(o.tensor,p):[]),this.performance.body&&delete this.performance.body):(a=oe(),(b=this.config.body.modelPath)!=null&&b.includes("posenet")?u=this.config.body.enabled?await U5(o.tensor,p):[]:(v=this.config.body.modelPath)!=null&&v.includes("blazepose")?u=this.config.body.enabled?await t5(o.tensor,p):[]:(S=this.config.body.modelPath)!=null&&S.includes("efficientpose")?u=this.config.body.enabled?await l5(o.tensor,p):[]:(T=this.config.body.modelPath)!=null&&T.includes("movenet")&&(u=this.config.body.enabled?await z5(o.tensor,p):[]),this.performance.body=this.env.perfadd?(this.performance.body||0)+Math.trunc(oe()-a):Math.trunc(oe()-a)),this.analyze("End Body:"),this.analyze("Start Hand:"),this.state="detect:hand";let c=this.config.hand.maxDetected===-1?Ut(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&&R.includes("handdetect")?d=this.config.hand.enabled?I5(o.tensor,c):[]:(M=(_=this.config.hand.detector)==null?void 0:_.modelPath)!=null&&M.includes("handtrack")&&(d=this.config.hand.enabled?C5(o.tensor,c):[]),this.performance.hand&&delete this.performance.hand):(a=oe(),(z=(I=this.config.hand.detector)==null?void 0:I.modelPath)!=null&&z.includes("handdetect")?d=this.config.hand.enabled?await I5(o.tensor,c):[]:(j=(O=this.config.hand.detector)==null?void 0:O.modelPath)!=null&&j.includes("handtrack")&&(d=this.config.hand.enabled?await C5(o.tensor,c):[]),this.performance.hand=this.env.perfadd?(this.performance.hand||0)+Math.trunc(oe()-a):Math.trunc(oe()-a)),this.analyze("End Hand:"),this.analyze("Start Object:"),this.state="detect:object",this.config.async?((X=this.config.object.modelPath)!=null&&X.includes("nanodet")?h=this.config.object.enabled?D5(o.tensor,this.config):[]:(D=this.config.object.modelPath)!=null&&D.includes("centernet")&&(h=this.config.object.enabled?a5(o.tensor,this.config):[]),this.performance.object&&delete this.performance.object):(a=oe(),(Q=this.config.object.modelPath)!=null&&Q.includes("nanodet")?h=this.config.object.enabled?await D5(o.tensor,this.config):[]:(V=this.config.object.modelPath)!=null&&V.includes("centernet")&&(h=this.config.object.enabled?await a5(o.tensor,this.config):[]),this.performance.object=this.env.perfadd?(this.performance.object||0)+Math.trunc(oe()-a):Math.trunc(oe()-a)),this.analyze("End Object:"),this.state="detect:await",this.config.async&&([l,u,d,h]=await Promise.all([l,u,d,h])),this.state="detect:gesture";let f=[];this.config.gesture.enabled&&(a=oe(),f=[...D9(l),...O9(u),...B9(d),...L9(l)],this.config.async?this.performance.gesture&&delete this.performance.gesture:this.performance.gesture=this.env.perfadd?(this.performance.gesture||0)+Math.trunc(oe()-a):Math.trunc(oe()-a)),this.performance.total=this.env.perfadd?(this.performance.total||0)+Math.trunc(oe()-i):Math.trunc(oe()-i);let m=((J=(ee=this.process)==null?void 0:ee.tensor)==null?void 0:J.shape)||[];this.result={face:l,body:u,hand:d,gesture:f,object:h,performance:this.performance,canvas:this.process.canvas,timestamp:Date.now(),error:null,get persons(){return U9(l,u,d,f,m)}},re(o.tensor),this.emit("detect"),this.state="idle",n(this.result)})}};Jd=new WeakMap,ac=new WeakMap,sc=new WeakMap,mg=new WeakMap;return UE(YAe);})();
|
|
/**
|
|
* @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.
|
|
* =============================================================================
|
|
*/
|
|
/**
|
|
* @license
|
|
* Copyright 2022 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 2022 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 2022 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 2022 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. */
|