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 Gh=Object.defineProperty;var BE=Object.getOwnPropertyDescriptor;var WE=Object.getOwnPropertyNames;var VE=Object.prototype.hasOwnProperty;var UE=(e,t,n)=>t in e?Gh(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n;var wa=(e,t)=>{for(var n in t)Gh(e,n,{get:t[n],enumerable:!0})},GE=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of WE(t))!VE.call(e,s)&&s!==n&&Gh(e,s,{get:()=>t[s],enumerable:!(r=BE(t,s))||r.enumerable});return e};var HE=e=>GE(Gh({},"__esModule",{value:!0}),e);var fe=(e,t,n)=>(UE(e,typeof t!="symbol"?t+"":t,n),n),_b=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var fd=(e,t,n)=>(_b(e,t,"read from private field"),n?n.call(e):t.get(e)),md=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},gd=(e,t,n,r)=>(_b(e,t,"write to private field"),r?r.call(e,n):t.set(e,n),n);var fxe={};wa(fxe,{Human:()=>ub,default:()=>ub,defaults:()=>ka,draw:()=>nb,env:()=>pe,match:()=>lb,models:()=>f2});function oe(...e){let t=new Date,n=`${t.getHours().toString().padStart(2,"0")}:${t.getMinutes().toString().padStart(2,"0")}:${t.getSeconds().toString().padStart(2,"0")}.${t.getMilliseconds().toString().padStart(3,"0")}`;e&&console.log(n,"Human:",...e)}function $b(e,t){let n=e.endsWith("/")?"":"/",s=t.startsWith(".")||t.startsWith("/")||t.startsWith("http:")||t.startsWith("https:")||t.startsWith("file:")?`${t}`:`${e}${n}${t}`;if(!s.toLocaleLowerCase().includes(".json"))throw new Error(`modelpath error: expecting json file: ${s}`);return s}var le=()=>typeof performance!="undefined"?performance.now():parseInt((Number(process.hrtime.bigint())/1e3/1e3).toString());function Z1(e,t,n="config",r=[]){for(let s of Object.keys(t))if(typeof t[s]=="object")Z1(e[s],t[s],s,r);else{let a=e&&typeof e[s]!="undefined";a||r.push({reason:"unknown property",where:`${n}.${s} = ${t[s]}`});let o=e&&typeof e[s]==typeof t[s];a&&!o&&r.push({reason:"property type mismatch",where:`${n}.${s} = ${t[s]}`,expected:typeof e[s]})}return t.debug&&n==="config"&&r.length>0&&oe("invalid configuration",r),r}function Gt(...e){let t=n=>n&&typeof n=="object";return e.reduce((n,r)=>(Object.keys(r||{}).forEach(s=>{let a=n[s],o=r[s];Array.isArray(a)&&Array.isArray(o)?n[s]=a.concat(...o):t(a)&&t(o)?n[s]=Gt(a,o):n[s]=o}),n),{})}var ka={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={};wa(Ue,{Abs:()=>Gi,Acos:()=>zu,Acosh:()=>Lu,AdadeltaOptimizer:()=>Gm,AdagradOptimizer:()=>Hm,AdamOptimizer:()=>jm,AdamaxOptimizer:()=>qm,Add:()=>ea,AddN:()=>Za,All:()=>Bu,Any:()=>Wu,ArgMax:()=>Ya,ArgMin:()=>Vu,Asin:()=>Uu,Asinh:()=>Gu,Atan:()=>Hu,Atan2:()=>qu,Atanh:()=>ju,AvgPool:()=>Ja,AvgPool3D:()=>Yd,AvgPool3DGrad:()=>Jf,AvgPoolGrad:()=>Yf,BackendWasm:()=>c9,BatchMatMul:()=>Qa,BatchToSpaceND:()=>Hi,Bincount:()=>Qf,BroadcastArgs:()=>em,BroadcastTo:()=>D4,Callback:()=>ik,CallbackList:()=>i6,Cast:()=>eo,Ceil:()=>to,ClipByValue:()=>ta,Complex:()=>Jd,ComplexAbs:()=>Qd,Concat:()=>ji,Conv2D:()=>no,Conv2DBackpropFilter:()=>tm,Conv2DBackpropInput:()=>ro,Conv3D:()=>ep,Conv3DBackpropFilterV2:()=>nm,Conv3DBackpropInputV2:()=>rm,Cos:()=>so,Cosh:()=>ao,CropAndResize:()=>Xi,Cumprod:()=>qi,Cumsum:()=>oo,CustomCallback:()=>u6,DataStorage:()=>Zd,DenseBincount:()=>sm,DepthToSpace:()=>Ki,DepthwiseConv2dNative:()=>io,DepthwiseConv2dNativeBackpropFilter:()=>am,DepthwiseConv2dNativeBackpropInput:()=>om,Diag:()=>im,Dilation2D:()=>tp,Dilation2DBackpropFilter:()=>xf,Dilation2DBackpropInput:()=>Af,ENV:()=>xs,EarlyStopping:()=>lk,Einsum:()=>np,Elu:()=>uo,EluGrad:()=>lm,Environment:()=>_4,Equal:()=>Zi,Erf:()=>Xu,Exp:()=>co,ExpandDims:()=>Yi,Expm1:()=>Ji,FFT:()=>um,Fill:()=>Ku,FlipLeftRight:()=>Qi,Floor:()=>po,FloorDiv:()=>ho,FromPixels:()=>Md,FusedBatchNorm:()=>fo,FusedConv2D:()=>Fa,FusedDepthwiseConv2D:()=>Oa,GPGPUContext:()=>vu,GatherNd:()=>tl,GatherV2:()=>el,GraphModel:()=>A0,Greater:()=>nl,GreaterEqual:()=>mo,History:()=>l6,IFFT:()=>cm,Identity:()=>go,Imag:()=>rp,InputSpec:()=>Zt,IsFinite:()=>Zu,IsInf:()=>Yu,IsNan:()=>Ju,KernelBackend:()=>Ou,LRN:()=>ap,LRNGrad:()=>pm,LayerVariable:()=>J7,LayersModel:()=>Ys,LeakyRelu:()=>yo,Less:()=>rl,LessEqual:()=>sl,LinSpace:()=>dm,Log:()=>Ao,Log1p:()=>Qu,LogSoftmax:()=>P4,LogicalAnd:()=>al,LogicalNot:()=>ec,LogicalOr:()=>sp,MathBackendCPU:()=>Kx,MathBackendWebGL:()=>Bp,Max:()=>xo,MaxPool:()=>vo,MaxPool3D:()=>op,MaxPool3DGrad:()=>fm,MaxPoolGrad:()=>hm,MaxPoolWithArgmax:()=>mm,Maximum:()=>bo,Mean:()=>wo,Min:()=>ko,Minimum:()=>So,MirrorPad:()=>Io,Mod:()=>tc,MomentumOptimizer:()=>Xm,Multinomial:()=>gm,Multiply:()=>Co,Neg:()=>ol,NonMaxSuppressionV3:()=>ll,NonMaxSuppressionV4:()=>nc,NonMaxSuppressionV5:()=>ul,NotEqual:()=>il,OP_SCOPE_SUFFIX:()=>K4,OneHot:()=>dl,OnesLike:()=>cl,Optimizer:()=>aa,OptimizerConstructors:()=>Ia,Pack:()=>pl,PadV2:()=>To,Pool:()=>OR,Pow:()=>No,Prelu:()=>Eo,Prod:()=>Ro,RMSPropOptimizer:()=>Km,RNN:()=>oa,Range:()=>rc,Rank:()=>L4,Real:()=>ip,RealDiv:()=>lo,Reciprocal:()=>sc,Reduction:()=>O7,Relu:()=>_o,Relu6:()=>Do,Reshape:()=>hl,ResizeBilinear:()=>$o,ResizeBilinearGrad:()=>Am,ResizeNearestNeighbor:()=>ac,ResizeNearestNeighborGrad:()=>ym,Reverse:()=>fl,RotateWithOffset:()=>Nl,Round:()=>ml,Rsqrt:()=>Po,SGDOptimizer:()=>Cp,ScatterNd:()=>gl,Select:()=>yl,Selu:()=>oc,Sequential:()=>u0,Sigmoid:()=>Oo,Sign:()=>ic,Sin:()=>Fo,Sinh:()=>xl,Slice:()=>Al,Softmax:()=>Lo,Softplus:()=>lc,SpaceToBatchND:()=>bl,SparseFillEmptyRows:()=>lp,SparseReshape:()=>uc,SparseSegmentMean:()=>up,SparseSegmentSum:()=>cp,SparseToDense:()=>dp,SplitV:()=>vl,Sqrt:()=>Mo,Square:()=>cc,SquaredDifference:()=>Bo,Step:()=>Go,StridedSlice:()=>wl,StringNGrams:()=>pp,StringSplit:()=>xm,StringToHashBucketFast:()=>bm,Sub:()=>Wo,Sum:()=>zo,SymbolicTensor:()=>cs,Tan:()=>kl,Tanh:()=>Vo,Tensor:()=>rt,TensorBuffer:()=>on,Tile:()=>na,TopK:()=>Sl,Transform:()=>Il,Transpose:()=>Uo,Unique:()=>vm,Unpack:()=>Cl,UnsortedSegmentSum:()=>hp,Variable:()=>Bd,ZerosLike:()=>Tl,_FusedMatMul:()=>Pa,abs:()=>rn,acos:()=>Nw,acosh:()=>Ew,add:()=>ue,addN:()=>km,all:()=>Fy,any:()=>If,argMax:()=>Rr,argMin:()=>Rw,asin:()=>_w,asinh:()=>$w,atan:()=>Dw,atan2:()=>Pw,atanh:()=>Fw,avgPool:()=>Sm,avgPool3d:()=>My,backend:()=>zr,backend_util:()=>C,basicLSTMCell:()=>kD,batchNorm:()=>Iu,batchNorm2d:()=>Lw,batchNorm3d:()=>Bw,batchNorm4d:()=>Ww,batchToSpaceND:()=>Im,bincount:()=>zy,booleanMaskAsync:()=>OO,broadcastArgs:()=>Vw,broadcastTo:()=>$d,broadcast_util:()=>El,browser:()=>Mr,buffer:()=>We,callbacks:()=>fH,cast:()=>ge,ceil:()=>Uw,clipByValue:()=>yr,clone:()=>Gn,complex:()=>Ma,concat:()=>St,concat1d:()=>Gw,concat2d:()=>pc,concat3d:()=>Hw,concat4d:()=>jw,constraints:()=>r6,conv1d:()=>Ly,conv2d:()=>La,conv2dTranspose:()=>Wy,conv3d:()=>Vy,conv3dTranspose:()=>Xw,copyRegisteredKernels:()=>BR,cos:()=>Cm,cosh:()=>Uy,cosineWindow:()=>hA,cumprod:()=>Tf,cumsum:()=>Gy,customGrad:()=>Ds,data:()=>Dk,denseBincount:()=>Kw,deprecationWarn:()=>$y,depthToSpace:()=>Zw,depthwiseConv2d:()=>vp,deregisterOp:()=>yH,device_util:()=>yp,diag:()=>eP,dilation2d:()=>Yw,disableDeprecationWarnings:()=>L$,dispose:()=>ne,disposeVariables:()=>B$,div:()=>de,divNoNan:()=>Jw,dot:()=>iP,dropout:()=>T7,einsum:()=>Qw,elu:()=>wp,enableDebugMode:()=>z$,enableProdMode:()=>_y,enclosingPowerOfTwo:()=>N7,engine:()=>sn,env:()=>Y,equal:()=>_r,erf:()=>e7,exp:()=>$r,expandDims:()=>Kt,expm1:()=>t7,eye:()=>Hy,fft:()=>Mm,fill:()=>hc,findBackend:()=>Py,findBackendFactory:()=>G$,floor:()=>kp,floorDiv:()=>xp,forceHalfFloat:()=>t8,fused:()=>Va,gather:()=>Cu,gatherND:()=>C7,gather_util:()=>Sy,getBackend:()=>qn,getGradient:()=>dg,getKernel:()=>bf,getKernelsForBackend:()=>_s,getThreadsCount:()=>xye,gpgpu_util:()=>$I,grad:()=>$P,grads:()=>DP,greater:()=>Ar,greaterEqual:()=>_l,ifft:()=>Gd,imag:()=>Tm,image:()=>Se,inTopKAsync:()=>qO,initializers:()=>s6,input:()=>k6,io:()=>Cn,irfft:()=>lA,isFinite:()=>wP,isInf:()=>SP,isNaN:()=>n7,keep:()=>fn,kernel_impls:()=>Kr,layers:()=>a6,leakyRelu:()=>Nm,less:()=>jy,lessEqual:()=>$l,linalg:()=>M7,linspace:()=>r7,loadGraphModel:()=>bj,loadLayersModel:()=>IU,localResponseNormalization:()=>s7,log:()=>Dr,log1p:()=>Em,logSigmoid:()=>LP,logSoftmax:()=>qy,logSumExp:()=>u7,logicalAnd:()=>ms,logicalNot:()=>_m,logicalOr:()=>Zy,logicalXor:()=>YP,losses:()=>_z,matMul:()=>Ye,math:()=>uw,max:()=>gn,maxPool:()=>$m,maxPool3d:()=>Yy,maxPoolWithArgmax:()=>c7,maximum:()=>ra,mean:()=>Vt,memory:()=>Sf,meshgrid:()=>rF,metrics:()=>sk,min:()=>Ba,minimum:()=>Sp,mirrorPad:()=>d7,mod:()=>mc,model:()=>kU,models:()=>ak,moments:()=>Dm,movingAverage:()=>LO,mul:()=>L,multiRNNCell:()=>dF,multinomial:()=>p7,neg:()=>zt,nextFrame:()=>gA,norm:()=>dA,notEqual:()=>Tu,oneHot:()=>Vd,ones:()=>gr,onesLike:()=>Pr,op:()=>V,outerProduct:()=>gF,pad:()=>Xr,pad1d:()=>xF,pad2d:()=>vF,pad3d:()=>kF,pad4d:()=>IF,pool:()=>RF,pow:()=>Wa,prelu:()=>Fm,print:()=>aw,prod:()=>Jy,profile:()=>W$,rand:()=>FF,randomGamma:()=>LF,randomNormal:()=>h7,randomUniform:()=>gc,range:()=>Nu,ready:()=>dc,real:()=>Ud,reciprocal:()=>f7,registerBackend:()=>Rl,registerCallbackConstructor:()=>CU,registerGradient:()=>F4,registerKernel:()=>qr,registerOp:()=>gH,regularizers:()=>ok,relu:()=>Os,relu6:()=>tA,removeBackend:()=>U$,reshape:()=>H,reverse:()=>Fr,reverse1d:()=>XF,reverse2d:()=>ZF,reverse3d:()=>JF,reverse4d:()=>eO,rfft:()=>zm,round:()=>nA,rsqrt:()=>rA,scalar:()=>Ie,scatterND:()=>I7,scatter_util:()=>Iy,selu:()=>sA,separableConv2d:()=>m7,sequential:()=>SU,serialization:()=>ce,setBackend:()=>Dy,setPlatform:()=>H$,setThreadsCount:()=>Aye,setWasmPath:()=>yye,setWasmPaths:()=>_3,setWebGLContext:()=>v0,setdiff1dAsync:()=>g7,shared:()=>x0,sigmoid:()=>Tn,sign:()=>y7,signal:()=>Rz,sin:()=>aA,sinh:()=>oA,slice:()=>Pe,slice1d:()=>Om,slice2d:()=>iA,slice3d:()=>Dl,slice4d:()=>Fi,slice_util:()=>Mt,softmax:()=>yc,softplus:()=>fc,spaceToBatchND:()=>Pm,sparse:()=>kd,sparseToDense:()=>pA,spectral:()=>Ez,split:()=>Yt,sqrt:()=>En,square:()=>xt,squaredDifference:()=>uA,squeeze:()=>tt,stack:()=>cn,step:()=>Ip,stridedSlice:()=>A7,string:()=>af,sub:()=>he,sum:()=>ke,sumOutType:()=>gp,tan:()=>x7,tanh:()=>Su,tensor:()=>pt,tensor1d:()=>Ct,tensor2d:()=>ps,tensor3d:()=>dw,tensor4d:()=>CO,tensor5d:()=>TO,tensor6d:()=>NO,tensor_util:()=>ds,test_util:()=>Iw,tidy:()=>K,tile:()=>Gr,time:()=>V$,topk:()=>b7,train:()=>Ai,transpose:()=>et,truncatedNormal:()=>Lm,unique:()=>Sg,unregisterGradient:()=>LR,unregisterKernel:()=>zR,unsortedSegmentSum:()=>v7,unstack:()=>rr,upcastType:()=>Nn,util:()=>w,valueAndGrad:()=>PP,valueAndGrads:()=>FP,variable:()=>w7,variableGrads:()=>a7,version:()=>Kp,version_converter:()=>vj,version_core:()=>Ry,version_cpu:()=>iX,version_layers:()=>LA,version_wasm:()=>bye,version_webgl:()=>_te,webgl:()=>$te,webgl_util:()=>nI,webgpu:()=>aC,where:()=>Hn,whereAsync:()=>cA,zeros:()=>Ft,zerosLike:()=>st});var jE=Object.create,qf=Object.defineProperty,qE=Object.getOwnPropertyDescriptor,x4=Object.getOwnPropertyNames,XE=Object.getPrototypeOf,KE=Object.prototype.hasOwnProperty,ZE=e=>qf(e,"__esModule",{value:!0}),dn=(e,t)=>function(){return t||(0,e[x4(e)[0]])((t={exports:{}}).exports,t),t.exports},Le=(e,t)=>{for(var n in t)qf(e,n,{get:t[n],enumerable:!0})},YE=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of x4(t))!KE.call(e,s)&&(n||s!=="default")&&qf(e,s,{get:()=>t[s],enumerable:!(r=qE(t,s))||r.enumerable});return e},Vi=(e,t)=>YE(ZE(qf(e!=null?jE(XE(e)):{},"default",!t&&e&&e.__esModule?{get:()=>e.default,enumerable:!0}:{value:e,enumerable:!0})),e),JE=dn({"src/node_modules/long/src/long.js"(e,t){t.exports=r;var n=null;try{n=new WebAssembly.Instance(new WebAssembly.Module(new Uint8Array([0,97,115,109,1,0,0,0,1,13,2,96,0,1,127,96,4,127,127,127,127,1,127,3,7,6,0,1,1,1,1,1,6,6,1,127,1,65,0,11,7,50,6,3,109,117,108,0,1,5,100,105,118,95,115,0,2,5,100,105,118,95,117,0,3,5,114,101,109,95,115,0,4,5,114,101,109,95,117,0,5,8,103,101,116,95,104,105,103,104,0,0,10,191,1,6,4,0,35,0,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,126,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,127,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,128,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,129,34,4,66,32,135,167,36,0,32,4,167,11,36,1,1,126,32,0,173,32,1,173,66,32,134,132,32,2,173,32,3,173,66,32,134,132,130,34,4,66,32,135,167,36,0,32,4,167,11])),{}).exports}catch(D){}function r(D,T,F){this.low=D|0,this.high=T|0,this.unsigned=!!F}r.prototype.__isLong__,Object.defineProperty(r.prototype,"__isLong__",{value:!0});function s(D){return(D&&D.__isLong__)===!0}r.isLong=s;var a={},o={};function i(D,T){var F,U,X;return T?(D>>>=0,(X=0<=D&&D<256)&&(U=o[D],U)?U:(F=u(D,(D|0)<0?-1:0,!0),X&&(o[D]=F),F)):(D|=0,(X=-128<=D&&D<128)&&(U=a[D],U)?U:(F=u(D,D<0?-1:0,!1),X&&(a[D]=F),F))}r.fromInt=i;function l(D,T){if(isNaN(D))return T?b:A;if(T){if(D<0)return b;if(D>=g)return R}else{if(D<=-y)return P;if(D+1>=y)return E}return D<0?l(-D,T).neg():u(D%m|0,D/m|0,T)}r.fromNumber=l;function u(D,T,F){return new r(D,T,F)}r.fromBits=u;var c=Math.pow;function p(D,T,F){if(D.length===0)throw Error("empty string");if(D==="NaN"||D==="Infinity"||D==="+Infinity"||D==="-Infinity")return A;if(typeof T=="number"?(F=T,T=!1):T=!!T,F=F||10,F<2||36<F)throw RangeError("radix");var U;if((U=D.indexOf("-"))>0)throw Error("interior hyphen");if(U===0)return p(D.substring(1),T,F).neg();for(var X=l(c(F,8)),z=A,Z=0;Z<D.length;Z+=8){var W=Math.min(8,D.length-Z),ee=parseInt(D.substring(Z,Z+W),F);if(W<8){var Q=l(c(F,W));z=z.mul(Q).add(l(ee))}else z=z.mul(X),z=z.add(l(ee))}return z.unsigned=T,z}r.fromString=p;function d(D,T){return typeof D=="number"?l(D,T):typeof D=="string"?p(D,T):u(D.low,D.high,typeof T=="boolean"?T:D.unsigned)}r.fromValue=d;var h=1<<16,f=1<<24,m=h*h,g=m*m,y=g/2,x=i(f),A=i(0);r.ZERO=A;var b=i(0,!0);r.UZERO=b;var v=i(1);r.ONE=v;var S=i(1,!0);r.UONE=S;var I=i(-1);r.NEG_ONE=I;var E=u(-1,2147483647,!1);r.MAX_VALUE=E;var R=u(-1,-1,!0);r.MAX_UNSIGNED_VALUE=R;var P=u(0,-2147483648,!1);r.MIN_VALUE=P;var _=r.prototype;_.toInt=function(){return this.unsigned?this.low>>>0:this.low},_.toNumber=function(){return this.unsigned?(this.high>>>0)*m+(this.low>>>0):this.high*m+(this.low>>>0)},_.toString=function(T){if(T=T||10,T<2||36<T)throw RangeError("radix");if(this.isZero())return"0";if(this.isNegative())if(this.eq(P)){var F=l(T),U=this.div(F),X=U.mul(F).sub(this);return U.toString(T)+X.toInt().toString(T)}else return"-"+this.neg().toString(T);for(var z=l(c(T,6),this.unsigned),Z=this,W="";;){var ee=Z.div(z),Q=Z.sub(ee.mul(z)).toInt()>>>0,ae=Q.toString(T);if(Z=ee,Z.isZero())return ae+W;for(;ae.length<6;)ae="0"+ae;W=""+ae+W}},_.getHighBits=function(){return this.high},_.getHighBitsUnsigned=function(){return this.high>>>0},_.getLowBits=function(){return this.low},_.getLowBitsUnsigned=function(){return this.low>>>0},_.getNumBitsAbs=function(){if(this.isNegative())return this.eq(P)?64:this.neg().getNumBitsAbs();for(var T=this.high!=0?this.high:this.low,F=31;F>0&&(T&1<<F)==0;F--);return this.high!=0?F+33:F+1},_.isZero=function(){return this.high===0&&this.low===0},_.eqz=_.isZero,_.isNegative=function(){return!this.unsigned&&this.high<0},_.isPositive=function(){return this.unsigned||this.high>=0},_.isOdd=function(){return(this.low&1)===1},_.isEven=function(){return(this.low&1)===0},_.equals=function(T){return s(T)||(T=d(T)),this.unsigned!==T.unsigned&&this.high>>>31===1&&T.high>>>31===1?!1:this.high===T.high&&this.low===T.low},_.eq=_.equals,_.notEquals=function(T){return!this.eq(T)},_.neq=_.notEquals,_.ne=_.notEquals,_.lessThan=function(T){return this.comp(T)<0},_.lt=_.lessThan,_.lessThanOrEqual=function(T){return this.comp(T)<=0},_.lte=_.lessThanOrEqual,_.le=_.lessThanOrEqual,_.greaterThan=function(T){return this.comp(T)>0},_.gt=_.greaterThan,_.greaterThanOrEqual=function(T){return this.comp(T)>=0},_.gte=_.greaterThanOrEqual,_.ge=_.greaterThanOrEqual,_.compare=function(T){if(s(T)||(T=d(T)),this.eq(T))return 0;var F=this.isNegative(),U=T.isNegative();return F&&!U?-1:!F&&U?1:this.unsigned?T.high>>>0>this.high>>>0||T.high===this.high&&T.low>>>0>this.low>>>0?-1:1:this.sub(T).isNegative()?-1:1},_.comp=_.compare,_.negate=function(){return!this.unsigned&&this.eq(P)?P:this.not().add(v)},_.neg=_.negate,_.add=function(T){s(T)||(T=d(T));var F=this.high>>>16,U=this.high&65535,X=this.low>>>16,z=this.low&65535,Z=T.high>>>16,W=T.high&65535,ee=T.low>>>16,Q=T.low&65535,ae=0,J=0,se=0,ie=0;return ie+=z+Q,se+=ie>>>16,ie&=65535,se+=X+ee,J+=se>>>16,se&=65535,J+=U+W,ae+=J>>>16,J&=65535,ae+=F+Z,ae&=65535,u(se<<16|ie,ae<<16|J,this.unsigned)},_.subtract=function(T){return s(T)||(T=d(T)),this.add(T.neg())},_.sub=_.subtract,_.multiply=function(T){if(this.isZero())return A;if(s(T)||(T=d(T)),n){var F=n.mul(this.low,this.high,T.low,T.high);return u(F,n.get_high(),this.unsigned)}if(T.isZero())return A;if(this.eq(P))return T.isOdd()?P:A;if(T.eq(P))return this.isOdd()?P:A;if(this.isNegative())return T.isNegative()?this.neg().mul(T.neg()):this.neg().mul(T).neg();if(T.isNegative())return this.mul(T.neg()).neg();if(this.lt(x)&&T.lt(x))return l(this.toNumber()*T.toNumber(),this.unsigned);var U=this.high>>>16,X=this.high&65535,z=this.low>>>16,Z=this.low&65535,W=T.high>>>16,ee=T.high&65535,Q=T.low>>>16,ae=T.low&65535,J=0,se=0,ie=0,me=0;return me+=Z*ae,ie+=me>>>16,me&=65535,ie+=z*ae,se+=ie>>>16,ie&=65535,ie+=Z*Q,se+=ie>>>16,ie&=65535,se+=X*ae,J+=se>>>16,se&=65535,se+=z*Q,J+=se>>>16,se&=65535,se+=Z*ee,J+=se>>>16,se&=65535,J+=U*ae+X*Q+z*ee+Z*W,J&=65535,u(ie<<16|me,J<<16|se,this.unsigned)},_.mul=_.multiply,_.divide=function(T){if(s(T)||(T=d(T)),T.isZero())throw Error("division by zero");if(n){if(!this.unsigned&&this.high===-2147483648&&T.low===-1&&T.high===-1)return this;var F=(this.unsigned?n.div_u:n.div_s)(this.low,this.high,T.low,T.high);return u(F,n.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?b:A;var U,X,z;if(this.unsigned){if(T.unsigned||(T=T.toUnsigned()),T.gt(this))return b;if(T.gt(this.shru(1)))return S;z=b}else{if(this.eq(P)){if(T.eq(v)||T.eq(I))return P;if(T.eq(P))return v;var Z=this.shr(1);return U=Z.div(T).shl(1),U.eq(A)?T.isNegative()?v:I:(X=this.sub(T.mul(U)),z=U.add(X.div(T)),z)}else if(T.eq(P))return this.unsigned?b:A;if(this.isNegative())return T.isNegative()?this.neg().div(T.neg()):this.neg().div(T).neg();if(T.isNegative())return this.div(T.neg()).neg();z=A}for(X=this;X.gte(T);){U=Math.max(1,Math.floor(X.toNumber()/T.toNumber()));for(var W=Math.ceil(Math.log(U)/Math.LN2),ee=W<=48?1:c(2,W-48),Q=l(U),ae=Q.mul(T);ae.isNegative()||ae.gt(X);)U-=ee,Q=l(U,this.unsigned),ae=Q.mul(T);Q.isZero()&&(Q=v),z=z.add(Q),X=X.sub(ae)}return z},_.div=_.divide,_.modulo=function(T){if(s(T)||(T=d(T)),n){var F=(this.unsigned?n.rem_u:n.rem_s)(this.low,this.high,T.low,T.high);return u(F,n.get_high(),this.unsigned)}return this.sub(this.div(T).mul(T))},_.mod=_.modulo,_.rem=_.modulo,_.not=function(){return u(~this.low,~this.high,this.unsigned)},_.and=function(T){return s(T)||(T=d(T)),u(this.low&T.low,this.high&T.high,this.unsigned)},_.or=function(T){return s(T)||(T=d(T)),u(this.low|T.low,this.high|T.high,this.unsigned)},_.xor=function(T){return s(T)||(T=d(T)),u(this.low^T.low,this.high^T.high,this.unsigned)},_.shiftLeft=function(T){return s(T)&&(T=T.toInt()),(T&=63)===0?this:T<32?u(this.low<<T,this.high<<T|this.low>>>32-T,this.unsigned):u(0,this.low<<T-32,this.unsigned)},_.shl=_.shiftLeft,_.shiftRight=function(T){return s(T)&&(T=T.toInt()),(T&=63)===0?this:T<32?u(this.low>>>T|this.high<<32-T,this.high>>T,this.unsigned):u(this.high>>T-32,this.high>=0?0:-1,this.unsigned)},_.shr=_.shiftRight,_.shiftRightUnsigned=function(T){if(s(T)&&(T=T.toInt()),T&=63,T===0)return this;var F=this.high;if(T<32){var U=this.low;return u(U>>>T|F<<32-T,F>>>T,this.unsigned)}else return T===32?u(F,0,this.unsigned):u(F>>>T-32,0,this.unsigned)},_.shru=_.shiftRightUnsigned,_.shr_u=_.shiftRightUnsigned,_.toSigned=function(){return this.unsigned?u(this.low,this.high,!1):this},_.toUnsigned=function(){return this.unsigned?this:u(this.low,this.high,!0)},_.toBytes=function(T){return T?this.toBytesLE():this.toBytesBE()},_.toBytesLE=function(){var T=this.high,F=this.low;return[F&255,F>>>8&255,F>>>16&255,F>>>24,T&255,T>>>8&255,T>>>16&255,T>>>24]},_.toBytesBE=function(){var T=this.high,F=this.low;return[T>>>24,T>>>16&255,T>>>8&255,T&255,F>>>24,F>>>16&255,F>>>8&255,F&255]},r.fromBytes=function(T,F,U){return U?r.fromBytesLE(T,F):r.fromBytesBE(T,F)},r.fromBytesLE=function(T,F){return new r(T[0]|T[1]<<8|T[2]<<16|T[3]<<24,T[4]|T[5]<<8|T[6]<<16|T[7]<<24,F)},r.fromBytesBE=function(T,F){return new r(T[4]<<24|T[5]<<16|T[6]<<8|T[7],T[0]<<24|T[1]<<16|T[2]<<8|T[3],F)}}}),QE=dn({"(disabled):src/node_modules/node-fetch/browser.js"(){}}),eR=dn({"(disabled):util"(){}}),tR=dn({"src/node_modules/seedrandom/lib/alea.js"(e,t){(function(n,r,s){function a(u){var c=this,p=l();c.next=function(){var d=2091639*c.s0+c.c*23283064365386963e-26;return c.s0=c.s1,c.s1=c.s2,c.s2=d-(c.c=d|0)},c.c=1,c.s0=p(" "),c.s1=p(" "),c.s2=p(" "),c.s0-=p(u),c.s0<0&&(c.s0+=1),c.s1-=p(u),c.s1<0&&(c.s1+=1),c.s2-=p(u),c.s2<0&&(c.s2+=1),p=null}function o(u,c){return c.c=u.c,c.s0=u.s0,c.s1=u.s1,c.s2=u.s2,c}function i(u,c){var p=new a(u),d=c&&c.state,h=p.next;return h.int32=function(){return p.next()*4294967296|0},h.double=function(){return h()+(h()*2097152|0)*11102230246251565e-32},h.quick=h,d&&(typeof d=="object"&&o(d,p),h.state=function(){return o(p,{})}),h}function l(){var u=4022871197,c=function(p){p=String(p);for(var d=0;d<p.length;d++){u+=p.charCodeAt(d);var h=.02519603282416938*u;u=h>>>0,h-=u,h*=u,u=h>>>0,h-=u,u+=h*4294967296}return(u>>>0)*23283064365386963e-26};return c}r&&r.exports?r.exports=i:s&&s.amd?s(function(){return i}):this.alea=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),nR=dn({"src/node_modules/seedrandom/lib/xor128.js"(e,t){(function(n,r,s){function a(l){var u=this,c="";u.x=0,u.y=0,u.z=0,u.w=0,u.next=function(){var d=u.x^u.x<<11;return u.x=u.y,u.y=u.z,u.z=u.w,u.w^=u.w>>>19^d^d>>>8},l===(l|0)?u.x=l:c+=l;for(var p=0;p<c.length+64;p++)u.x^=c.charCodeAt(p)|0,u.next()}function o(l,u){return u.x=l.x,u.y=l.y,u.z=l.z,u.w=l.w,u}function i(l,u){var c=new a(l),p=u&&u.state,d=function(){return(c.next()>>>0)/4294967296};return d.double=function(){do var h=c.next()>>>11,f=(c.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},d.int32=c.next,d.quick=d,p&&(typeof p=="object"&&o(p,c),d.state=function(){return o(c,{})}),d}r&&r.exports?r.exports=i:s&&s.amd?s(function(){return i}):this.xor128=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),rR=dn({"src/node_modules/seedrandom/lib/xorwow.js"(e,t){(function(n,r,s){function a(l){var u=this,c="";u.next=function(){var d=u.x^u.x>>>2;return u.x=u.y,u.y=u.z,u.z=u.w,u.w=u.v,(u.d=u.d+362437|0)+(u.v=u.v^u.v<<4^(d^d<<1))|0},u.x=0,u.y=0,u.z=0,u.w=0,u.v=0,l===(l|0)?u.x=l:c+=l;for(var p=0;p<c.length+64;p++)u.x^=c.charCodeAt(p)|0,p==c.length&&(u.d=u.x<<10^u.x>>>4),u.next()}function o(l,u){return u.x=l.x,u.y=l.y,u.z=l.z,u.w=l.w,u.v=l.v,u.d=l.d,u}function i(l,u){var c=new a(l),p=u&&u.state,d=function(){return(c.next()>>>0)/4294967296};return d.double=function(){do var h=c.next()>>>11,f=(c.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},d.int32=c.next,d.quick=d,p&&(typeof p=="object"&&o(p,c),d.state=function(){return o(c,{})}),d}r&&r.exports?r.exports=i:s&&s.amd?s(function(){return i}):this.xorwow=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),sR=dn({"src/node_modules/seedrandom/lib/xorshift7.js"(e,t){(function(n,r,s){function a(l){var u=this;u.next=function(){var p=u.x,d=u.i,h,f,m;return h=p[d],h^=h>>>7,f=h^h<<24,h=p[d+1&7],f^=h^h>>>10,h=p[d+3&7],f^=h^h>>>3,h=p[d+4&7],f^=h^h<<7,h=p[d+7&7],h=h^h<<13,f^=h^h<<9,p[d]=f,u.i=d+1&7,f};function c(p,d){var h,f,m=[];if(d===(d|0))f=m[0]=d;else for(d=""+d,h=0;h<d.length;++h)m[h&7]=m[h&7]<<15^d.charCodeAt(h)+m[h+1&7]<<13;for(;m.length<8;)m.push(0);for(h=0;h<8&&m[h]===0;++h);for(h==8?f=m[7]=-1:f=m[h],p.x=m,p.i=0,h=256;h>0;--h)p.next()}c(u,l)}function o(l,u){return u.x=l.x.slice(),u.i=l.i,u}function i(l,u){l==null&&(l=+new Date);var c=new a(l),p=u&&u.state,d=function(){return(c.next()>>>0)/4294967296};return d.double=function(){do var h=c.next()>>>11,f=(c.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},d.int32=c.next,d.quick=d,p&&(p.x&&o(p,c),d.state=function(){return o(c,{})}),d}r&&r.exports?r.exports=i:s&&s.amd?s(function(){return i}):this.xorshift7=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),aR=dn({"src/node_modules/seedrandom/lib/xor4096.js"(e,t){(function(n,r,s){function a(l){var u=this;u.next=function(){var p=u.w,d=u.X,h=u.i,f,m;return u.w=p=p+1640531527|0,m=d[h+34&127],f=d[h=h+1&127],m^=m<<13,f^=f<<17,m^=m>>>15,f^=f>>>12,m=d[h]=m^f,u.i=h,m+(p^p>>>16)|0};function c(p,d){var h,f,m,g,y,x=[],A=128;for(d===(d|0)?(f=d,d=null):(d=d+"\0",f=0,A=Math.max(A,d.length)),m=0,g=-32;g<A;++g)d&&(f^=d.charCodeAt((g+32)%d.length)),g===0&&(y=f),f^=f<<10,f^=f>>>15,f^=f<<4,f^=f>>>13,g>=0&&(y=y+1640531527|0,h=x[g&127]^=f+y,m=h==0?m+1:0);for(m>=128&&(x[(d&&d.length||0)&127]=-1),m=127,g=4*128;g>0;--g)f=x[m+34&127],h=x[m=m+1&127],f^=f<<13,h^=h<<17,f^=f>>>15,h^=h>>>12,x[m]=f^h;p.w=y,p.X=x,p.i=m}c(u,l)}function o(l,u){return u.i=l.i,u.w=l.w,u.X=l.X.slice(),u}function i(l,u){l==null&&(l=+new Date);var c=new a(l),p=u&&u.state,d=function(){return(c.next()>>>0)/4294967296};return d.double=function(){do var h=c.next()>>>11,f=(c.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},d.int32=c.next,d.quick=d,p&&(p.X&&o(p,c),d.state=function(){return o(c,{})}),d}r&&r.exports?r.exports=i:s&&s.amd?s(function(){return i}):this.xor4096=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),oR=dn({"src/node_modules/seedrandom/lib/tychei.js"(e,t){(function(n,r,s){function a(l){var u=this,c="";u.next=function(){var d=u.b,h=u.c,f=u.d,m=u.a;return d=d<<25^d>>>7^h,h=h-f|0,f=f<<24^f>>>8^m,m=m-d|0,u.b=d=d<<20^d>>>12^h,u.c=h=h-f|0,u.d=f<<16^h>>>16^m,u.a=m-d|0},u.a=0,u.b=0,u.c=-1640531527,u.d=1367130551,l===Math.floor(l)?(u.a=l/4294967296|0,u.b=l|0):c+=l;for(var p=0;p<c.length+20;p++)u.b^=c.charCodeAt(p)|0,u.next()}function o(l,u){return u.a=l.a,u.b=l.b,u.c=l.c,u.d=l.d,u}function i(l,u){var c=new a(l),p=u&&u.state,d=function(){return(c.next()>>>0)/4294967296};return d.double=function(){do var h=c.next()>>>11,f=(c.next()>>>0)/4294967296,m=(h+f)/(1<<21);while(m===0);return m},d.int32=c.next,d.quick=d,p&&(typeof p=="object"&&o(p,c),d.state=function(){return o(c,{})}),d}r&&r.exports?r.exports=i:s&&s.amd?s(function(){return i}):this.tychei=i})(e,typeof t=="object"&&t,typeof define=="function"&&define)}}),iR=dn({"(disabled):crypto"(){}}),lR=dn({"src/node_modules/seedrandom/seedrandom.js"(e,t){(function(n,r,s){var a=256,o=6,i=52,l="random",u=s.pow(a,o),c=s.pow(2,i),p=c*2,d=a-1,h;function f(v,S,I){var E=[];S=S==!0?{entropy:!0}:S||{};var R=x(y(S.entropy?[v,b(r)]:v==null?A():v,3),E),P=new m(E),_=function(){for(var D=P.g(o),T=u,F=0;D<c;)D=(D+F)*a,T*=a,F=P.g(1);for(;D>=p;)D/=2,T/=2,F>>>=1;return(D+F)/T};return _.int32=function(){return P.g(4)|0},_.quick=function(){return P.g(4)/4294967296},_.double=_,x(b(P.S),r),(S.pass||I||function(D,T,F,U){return U&&(U.S&&g(U,P),D.state=function(){return g(P,{})}),F?(s[l]=D,T):D})(_,R,"global"in S?S.global:this==s,S.state)}function m(v){var S,I=v.length,E=this,R=0,P=E.i=E.j=0,_=E.S=[];for(I||(v=[I++]);R<a;)_[R]=R++;for(R=0;R<a;R++)_[R]=_[P=d&P+v[R%I]+(S=_[R])],_[P]=S;(E.g=function(D){for(var T,F=0,U=E.i,X=E.j,z=E.S;D--;)T=z[U=d&U+1],F=F*a+z[d&(z[U]=z[X=d&X+T])+(z[X]=T)];return E.i=U,E.j=X,F})(a)}function g(v,S){return S.i=v.i,S.j=v.j,S.S=v.S.slice(),S}function y(v,S){var I=[],E=typeof v,R;if(S&&E=="object")for(R in v)try{I.push(y(v[R],S-1))}catch(P){}return I.length?I:E=="string"?v:v+"\0"}function x(v,S){for(var I=v+"",E,R=0;R<I.length;)S[d&R]=d&(E^=S[d&R]*19)+I.charCodeAt(R++);return b(S)}function A(){try{var v;return h&&(v=h.randomBytes)?v=v(a):(v=new Uint8Array(a),(n.crypto||n.msCrypto).getRandomValues(v)),b(v)}catch(E){var S=n.navigator,I=S&&S.plugins;return[+new Date,n,I,n.screen,b(r)]}}function b(v){return String.fromCharCode.apply(0,v)}if(x(s.random(),r),typeof t=="object"&&t.exports){t.exports=f;try{h=iR()}catch(v){}}else typeof define=="function"&&define.amd?define(function(){return f}):s["seed"+l]=f})(typeof self!="undefined"?self:e,[],Math)}}),Xf=dn({"src/node_modules/seedrandom/index.js"(e,t){var n=tR(),r=nR(),s=rR(),a=sR(),o=aR(),i=oR(),l=lR();l.alea=n,l.xor128=r,l.xorwow=s,l.xorshift7=a,l.xor4096=o,l.tychei=i,t.exports=l}}),b4=dn({"(disabled):src/node_modules/string_decoder/index.js"(){}}),dy=dn({"(disabled):fs"(){}}),mf=dn({"(disabled):path"(){}}),uR=dn({"(disabled):worker_threads"(){}}),cR=dn({"(disabled):perf_hooks"(){}}),dR=dn({"(disabled):os"(){}}),pR=dn({"src/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm-threaded-simd.js"(e,t){var n=(()=>{var r=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(r=r||__filename),function(s){s=s||{};function a(){return $e.buffer!=Mn&&ts($e.buffer),uh}function o(){return $e.buffer!=Mn&&ts($e.buffer),ch}function i(){return $e.buffer!=Mn&&ts($e.buffer),rd}function l(){return $e.buffer!=Mn&&ts($e.buffer),dh}function u(){return $e.buffer!=Mn&&ts($e.buffer),ph}function c(){return $e.buffer!=Mn&&ts($e.buffer),hh}function p(){return $e.buffer!=Mn&&ts($e.buffer),fh}var d=typeof s!="undefined"?s:{},h,f;d.ready=new Promise(function(N,O){h=N,f=O});var m;typeof process!="undefined"&&process.listeners&&(m={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var g=Object.assign({},d),y=[],x="./this.program",A=(N,O)=>{throw O},b=typeof window=="object",v=typeof importScripts=="function",S=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",I=d.ENVIRONMENT_IS_PTHREAD||!1,E="";function R(N){return d.locateFile?d.locateFile(N,E):E+N}var P,_,D,T;function F(N){if(N instanceof pd)return;Q("exiting due to exception: "+N)}var U,X,z;if(S){v?E=mf().dirname(E)+"/":E=__dirname+"/",z=()=>{X||(U=dy(),X=mf())},P=function(G,te){return z(),G=X.normalize(G),U.readFileSync(G,te?void 0:"utf8")},D=O=>{var G=P(O,!0);return G.buffer||(G=new Uint8Array(G)),G},_=(O,G,te)=>{z(),O=X.normalize(O),U.readFile(O,function(ye,xe){ye?te(ye):G(xe.buffer)})},process.argv.length>1&&(x=process.argv[1].replace(/\\/g,"/")),y=process.argv.slice(2),process.on("uncaughtException",function(O){if(!(O instanceof pd))throw O}),process.on("unhandledRejection",function(O){throw O}),A=(O,G)=>{if(ci())throw process.exitCode=O,G;F(G),process.exit(O)},d.inspect=function(){return"[Emscripten Module object]"};let N;try{N=uR()}catch(O){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),O}global.Worker=N.Worker}else(b||v)&&(v?E=self.location.href:typeof document!="undefined"&&document.currentScript&&(E=document.currentScript.src),typeof r!="undefined"&&r&&(E=r),E.indexOf("blob:")!==0?E=E.substr(0,E.replace(/[?#].*/,"").lastIndexOf("/")+1):E="",S||(P=N=>{var O=new XMLHttpRequest;return O.open("GET",N,!1),O.send(null),O.responseText},v&&(D=N=>{var O=new XMLHttpRequest;return O.open("GET",N,!1),O.responseType="arraybuffer",O.send(null),new Uint8Array(O.response)}),_=(N,O,G)=>{var te=new XMLHttpRequest;te.open("GET",N,!0),te.responseType="arraybuffer",te.onload=()=>{if(te.status==200||te.status==0&&te.response){O(te.response);return}G()},te.onerror=G,te.send(null)}),T=N=>document.title=N);S&&typeof performance=="undefined"&&(global.performance=cR().performance);var Z=console.log.bind(console),W=console.warn.bind(console);S&&(z(),Z=N=>U.writeSync(1,N+`
|
|
`),W=N=>U.writeSync(2,N+`
|
|
`));var ee=d.print||Z,Q=d.printErr||W;Object.assign(d,g),g=null,d.arguments&&(y=d.arguments),d.thisProgram&&(x=d.thisProgram),d.quit&&(A=d.quit);var ae=4;function J(N){J.shown||(J.shown={}),J.shown[N]||(J.shown[N]=1,Q(N))}function se(N,O){if(typeof WebAssembly.Function=="function"){for(var G={i:"i32",j:"i64",f:"f32",d:"f64"},te={parameters:[],results:O[0]=="v"?[]:[G[O[0]]]},ye=1;ye<O.length;++ye)te.parameters.push(G[O[ye]]);return new WebAssembly.Function(te,N)}var xe=[1,0,1,96],Te=O.slice(0,1),Fe=O.slice(1),Pt={i:127,j:126,f:125,d:124};xe.push(Fe.length);for(var ye=0;ye<Fe.length;++ye)xe.push(Pt[Fe[ye]]);Te=="v"?xe.push(0):xe=xe.concat([1,Pt[Te]]),xe[1]=xe.length-2;var as=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])),os=new WebAssembly.Module(as),Uh=new WebAssembly.Instance(os,{e:{f:N}}),hd=Uh.exports.f;return hd}var ie=[],me;function be(){if(ie.length)return ie.pop();try{Cr.grow(1)}catch(N){throw N instanceof RangeError?"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.":N}return Cr.length-1}function Ee(N,O){for(var G=N;G<N+O;G++){var te=tu(G);te&&me.set(te,G)}}var Re=0,ze=N=>{Re=N},Be=Atomics.load,nt=Atomics.store,it=Atomics.compareExchange,lt;d.wasmBinary&&(lt=d.wasmBinary);var ft=d.noExitRuntime||!0;typeof WebAssembly!="object"&&Jl("no native wasm support detected");var $e,wt,At=!1,Pn;function qt(N,O){N||Jl(O)}function ur(N){var O=d["_"+N];return O}function nn(N,O,G,te,ye){var xe={string:function(pr){var lu=0;if(pr!=null&&pr!==0){var Rb=(pr.length<<2)+1;lu=iu(Rb),Gs(pr,lu,Rb)}return lu},array:function(pr){var lu=iu(pr.length);return Hs(pr,lu),lu}};function Te(pr){return O==="string"?On(pr):O==="boolean"?Boolean(pr):pr}var Fe=ur(N),Pt=[],as=0;if(te)for(var os=0;os<te.length;os++){var Uh=xe[G[os]];Uh?(as===0&&(as=X1()),Pt[os]=Uh(te[os])):Pt[os]=te[os]}var hd=Fe.apply(null,Pt);function LE(pr){return as!==0&&Lh(as),Te(pr)}return hd=LE(hd),hd}function Fn(N,O,G,te){G=G||[];var ye=G.every(function(Te){return Te==="number"}),xe=O!=="string";return xe&&ye&&!te?ur(N):function(){return nn(N,O,G,arguments,te)}}var cr=1;function dr(N){var O=new TextDecoder(N);this.decode=G=>(G.buffer instanceof SharedArrayBuffer&&(G=new Uint8Array(G)),O.decode.call(O,G))}var Sn=typeof TextDecoder!="undefined"?new dr("utf8"):void 0;function Ir(N,O,G){for(var te=O+G,ye=O;N[ye]&&!(ye>=te);)++ye;if(ye-O>16&&N.subarray&&Sn)return Sn.decode(N.subarray(O,ye));for(var xe="";O<ye;){var Te=N[O++];if(!(Te&128)){xe+=String.fromCharCode(Te);continue}var Fe=N[O++]&63;if((Te&224)==192){xe+=String.fromCharCode((Te&31)<<6|Fe);continue}var Pt=N[O++]&63;if((Te&240)==224?Te=(Te&15)<<12|Fe<<6|Pt:Te=(Te&7)<<18|Fe<<12|Pt<<6|N[O++]&63,Te<65536)xe+=String.fromCharCode(Te);else{var as=Te-65536;xe+=String.fromCharCode(55296|as>>10,56320|as&1023)}}return xe}function On(N,O){return N?Ir(o(),N,O):""}function Us(N,O,G,te){if(!(te>0))return 0;for(var ye=G,xe=G+te-1,Te=0;Te<N.length;++Te){var Fe=N.charCodeAt(Te);if(Fe>=55296&&Fe<=57343){var Pt=N.charCodeAt(++Te);Fe=65536+((Fe&1023)<<10)|Pt&1023}if(Fe<=127){if(G>=xe)break;O[G++]=Fe}else if(Fe<=2047){if(G+1>=xe)break;O[G++]=192|Fe>>6,O[G++]=128|Fe&63}else if(Fe<=65535){if(G+2>=xe)break;O[G++]=224|Fe>>12,O[G++]=128|Fe>>6&63,O[G++]=128|Fe&63}else{if(G+3>=xe)break;O[G++]=240|Fe>>18,O[G++]=128|Fe>>12&63,O[G++]=128|Fe>>6&63,O[G++]=128|Fe&63}}return O[G]=0,G-ye}function Gs(N,O,G){return Us(N,o(),O,G)}function Kl(N){for(var O=0,G=0;G<N.length;++G){var te=N.charCodeAt(G);te>=55296&&te<=57343&&(te=65536+((te&1023)<<10)|N.charCodeAt(++G)&1023),te<=127?++O:te<=2047?O+=2:te<=65535?O+=3:O+=4}return O}var Aa=typeof TextDecoder!="undefined"?new dr("utf-16le"):void 0;function Hs(N,O){a().set(N,O)}function nd(N,O,G){for(var te=0;te<N.length;++te)a()[O++>>0]=N.charCodeAt(te);G||(a()[O>>0]=0)}function Zl(N,O){return N%O>0&&(N+=O-N%O),N}var Mn,uh,ch,rd,dh,ph,cb,hh,fh;I&&(Mn=d.buffer);function ts(N){Mn=N,d.HEAP8=uh=new Int8Array(N),d.HEAP16=rd=new Int16Array(N),d.HEAP32=ph=new Int32Array(N),d.HEAPU8=ch=new Uint8Array(N),d.HEAPU16=dh=new Uint16Array(N),d.HEAPU32=cb=new Uint32Array(N),d.HEAPF32=hh=new Float32Array(N),d.HEAPF64=fh=new Float64Array(N)}var mh=d.INITIAL_MEMORY||16777216;if(I)$e=d.wasmMemory,Mn=d.buffer;else if(d.wasmMemory)$e=d.wasmMemory;else if($e=new WebAssembly.Memory({initial:mh/65536,maximum:32768,shared:!0}),!($e.buffer instanceof SharedArrayBuffer))throw Q("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&&(Mn=$e.buffer),mh=Mn.byteLength,ts(Mn);var Cr,Yl=[],xa=[],x2=[],gh=[],ui=!1,b2=!1,yh=0;function ci(){return ft||yh>0}function zn(){if(d.preRun)for(typeof d.preRun=="function"&&(d.preRun=[d.preRun]);d.preRun.length;)db(d.preRun.shift());wh(Yl)}function sd(){ui=!0,!I&&wh(xa)}function v2(){I||(Me.terminateAllThreads(),b2=!0)}function w2(){if(!I){if(d.postRun)for(typeof d.postRun=="function"&&(d.postRun=[d.postRun]);d.postRun.length;)ad(d.postRun.shift());wh(gh)}}function db(N){Yl.unshift(N)}function pb(N){xa.unshift(N)}function ad(N){gh.unshift(N)}var ba=0,Ah=null,ns=null;function od(N){ba++,d.monitorRunDependencies&&d.monitorRunDependencies(ba)}function hb(N){if(ba--,d.monitorRunDependencies&&d.monitorRunDependencies(ba),ba==0&&(Ah!==null&&(clearInterval(Ah),Ah=null),ns)){var O=ns;ns=null,O()}}d.preloadedImages={},d.preloadedAudios={};function Jl(N){I?postMessage({cmd:"onAbort",arg:N}):d.onAbort&&d.onAbort(N),N="Aborted("+N+")",Q(N),At=!0,Pn=1,N+=". Build with -s ASSERTIONS=1 for more info.";var O=new WebAssembly.RuntimeError(N);throw f(O),O}var k2="data:application/octet-stream;base64,";function xh(N){return N.startsWith(k2)}function bh(N){return N.startsWith("file://")}var Ln;Ln="tfjs-backend-wasm-threaded-simd.wasm",xh(Ln)||(Ln=R(Ln));function vh(N){try{if(N==Ln&<)return new Uint8Array(lt);if(D)return D(N);throw"both async and sync fetching of the wasm failed"}catch(O){Jl(O)}}function Ql(){if(!lt&&(b||v)){if(typeof fetch=="function"&&!bh(Ln))return fetch(Ln,{credentials:"same-origin"}).then(function(N){if(!N.ok)throw"failed to load wasm binary file at '"+Ln+"'";return N.arrayBuffer()}).catch(function(){return vh(Ln)});if(_)return new Promise(function(N,O){_(Ln,function(G){N(new Uint8Array(G))},O)})}return Promise.resolve().then(function(){return vh(Ln)})}function S2(){var N={env:Ph,wasi_snapshot_preview1:Ph};function O(Te,Fe){var Pt=Te.exports;if(d.asm=Pt,_2(d.asm.emscripten_tls_init),Cr=d.asm.__indirect_function_table,pb(d.asm.__wasm_call_ctors),wt=Fe,!I){var as=Me.unusedWorkers.length;Me.unusedWorkers.forEach(function(os){Me.loadWasmModuleToWorker(os,function(){--as||hb("wasm-instantiate")})})}}I||od("wasm-instantiate");function G(Te){O(Te.instance,Te.module)}function te(Te){return Ql().then(function(Fe){return WebAssembly.instantiate(Fe,N)}).then(function(Fe){return Fe}).then(Te,function(Fe){Q("failed to asynchronously prepare wasm: "+Fe),Jl(Fe)})}function ye(){return!lt&&typeof WebAssembly.instantiateStreaming=="function"&&!xh(Ln)&&!bh(Ln)&&typeof fetch=="function"?fetch(Ln,{credentials:"same-origin"}).then(function(Te){var Fe=WebAssembly.instantiateStreaming(Te,N);return Fe.then(G,function(Pt){return Q("wasm streaming compile failed: "+Pt),Q("falling back to ArrayBuffer instantiation"),te(G)})}):te(G)}if(d.instantiateWasm)try{var xe=d.instantiateWasm(N,O);return xe}catch(Te){return Q("Module.instantiateWasm callback failed with error: "+Te),!1}return ye().catch(f),{}}var fb,mb,I2={};function wh(N){for(;N.length>0;){var O=N.shift();if(typeof O=="function"){O(d);continue}var G=O.func;typeof G=="number"?O.arg===void 0?tu(G)():tu(G)(O.arg):G(O.arg===void 0?null:O.arg)}}function eu(N){var O=X1(),G=N();return Lh(O),G}function qN(N){return N}function gb(N){var O=/\b_Z[\w\d_]+/g;return N.replace(O,function(G){var te=G;return G===te?G:te+" ["+G+"]"})}function C2(N){u()[N>>2]=0;var O=Me.pthreads[N];delete Me.pthreads[N],O.worker.terminate(),q1(N),Me.runningWorkers.splice(Me.runningWorkers.indexOf(O.worker),1),O.worker.pthread=void 0}function T2(N){var O=Me.pthreads[N];O.worker.postMessage({cmd:"cancel"})}function kh(N){var O=Me.pthreads[N];if(O){u()[N>>2]=0;var G=O.worker;Me.returnWorkerToPool(G)}}function Sh(N){OE(N)}function N2(N){if(N instanceof pd||N=="unwind")return Pn;A(1,N)}var Me={unusedWorkers:[],runningWorkers:[],tlsInitFunctions:[],init:function(){I?Me.initWorker():Me.initMainThread()},initMainThread:function(){for(var N=8,O=0;O<N;++O)Me.allocateUnusedWorker()},initWorker:function(){ft=!1},pthreads:{},setExitStatus:function(N){Pn=N},terminateAllThreads:function(){for(var N in Me.pthreads){var O=Me.pthreads[N];O&&O.worker&&Me.returnWorkerToPool(O.worker)}for(var G=0;G<Me.unusedWorkers.length;++G){var te=Me.unusedWorkers[G];te.terminate()}Me.unusedWorkers=[]},returnWorkerToPool:function(N){Me.runWithoutMainThreadQueuedCalls(function(){delete Me.pthreads[N.pthread.threadInfoStruct],Me.unusedWorkers.push(N),Me.runningWorkers.splice(Me.runningWorkers.indexOf(N),1),q1(N.pthread.threadInfoStruct),N.pthread=void 0})},runWithoutMainThreadQueuedCalls:function(N){u()[Eb>>2]=0;try{N()}finally{u()[Eb>>2]=1}},receiveObjectTransfer:function(N){},threadInit:function(){for(var N in Me.tlsInitFunctions)Me.tlsInitFunctions[N]()},loadWasmModuleToWorker:function(N,O){N.onmessage=G=>{var te=G.data,ye=te.cmd;if(N.pthread&&(Me.currentProxiedOperationCallerThread=N.pthread.threadInfoStruct),te.targetThread&&te.targetThread!=zh()){var xe=Me.pthreads[te.targetThread];xe?xe.worker.postMessage(te,te.transferList):Q('Internal error! Worker sent a message "'+ye+'" to target pthread '+te.targetThread+", but that thread no longer exists!"),Me.currentProxiedOperationCallerThread=void 0;return}ye==="processQueuedMainThreadWork"?Sb():ye==="spawnThread"?Ch(te):ye==="cleanupThread"?kh(te.thread):ye==="killThread"?C2(te.thread):ye==="cancelThread"?T2(te.thread):ye==="loaded"?(N.loaded=!0,O&&O(N),N.runPthread&&(N.runPthread(),delete N.runPthread)):ye==="print"?ee("Thread "+te.threadId+": "+te.text):ye==="printErr"?Q("Thread "+te.threadId+": "+te.text):ye==="alert"?alert("Thread "+te.threadId+": "+te.text):te.target==="setimmediate"?N.postMessage(te):ye==="onAbort"?d.onAbort&&d.onAbort(te.arg):Q("worker sent an unknown command "+ye),Me.currentProxiedOperationCallerThread=void 0},N.onerror=G=>{var te="worker sent an error!";throw Q(te+" "+G.filename+":"+G.lineno+": "+G.message),G},S&&(N.on("message",function(G){N.onmessage({data:G})}),N.on("error",function(G){N.onerror(G)}),N.on("detachedExit",function(){})),N.postMessage({cmd:"load",urlOrBlob:d.mainScriptUrlOrBlob||r,wasmMemory:$e,wasmModule:wt})},allocateUnusedWorker:function(){var N=R("tfjs-backend-wasm-threaded-simd.worker.js");Me.unusedWorkers.push(new Worker(N))},getNewWorker:function(){return Me.unusedWorkers.length==0&&(Me.allocateUnusedWorker(),Me.loadWasmModuleToWorker(Me.unusedWorkers[0])),Me.unusedWorkers.pop()}};function E2(){var N=zh(),O=u()[N+44>>2],G=u()[N+48>>2],te=O-G;Nb(O,te),Lh(O)}d.establishStackSpace=E2;function Ih(N){if(I)return hi(1,0,N);try{Sh(N)}catch(O){N2(O)}}var di=[];function tu(N){var O=di[N];return O||(N>=di.length&&(di.length=N+1),di[N]=O=Cr.get(N)),O}function R2(N,O){return tu(N)(O)}d.invokeEntryPoint=R2;function yb(){var N=new Error;if(!N.stack){try{throw new Error}catch(O){N=O}if(!N.stack)return"(no stack trace available)"}return N.stack.toString()}function _2(N,O,G){Me.tlsInitFunctions.push(N)}function Ab(N,O){Cr.set(N,O),di[N]=O}var pi;S?pi=()=>{var N=process.hrtime();return N[0]*1e3+N[1]/1e6}:I?pi=()=>performance.now()-d.__performance_now_clock_drift:pi=()=>performance.now();var $2=!0;function D2(N){return u()[kb()>>2]=N,N}function P2(N,O){var G;if(N===0)G=Date.now();else if((N===1||N===4)&&$2)G=pi();else return D2(28),-1;return u()[O>>2]=G/1e3|0,u()[O+4>>2]=G%1e3*1e3*1e3|0,0}function F2(N,O){return P2(N,O)}function O2(N){Ib(N,!v,1,!b),Me.threadInit()}function M2(N){I?postMessage({cmd:"cleanupThread",thread:N}):kh(N)}function Ch(N){var O=Me.getNewWorker();if(!O)return 6;Me.runningWorkers.push(O);var G=Me.pthreads[N.pthread_ptr]={worker:O,threadInfoStruct:N.pthread_ptr};O.pthread=G;var te={cmd:"run",start_routine:N.startRoutine,arg:N.arg,threadInfoStruct:N.pthread_ptr};return O.runPthread=()=>{te.time=performance.now(),O.postMessage(te,N.transferList)},O.loaded&&(O.runPthread(),delete O.runPthread),0}function z2(N,O,G,te){if(typeof SharedArrayBuffer=="undefined")return Q("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;var ye=[],xe=0;if(I&&(ye.length===0||xe))return Cb(687865856,N,O,G,te);if(xe)return xe;var Te={startRoutine:G,pthread_ptr:N,arg:te,transferList:ye};return I?(Te.cmd="spawnThread",postMessage(Te,ye),0):Ch(Te)}function L2(){return 2097152}function B2(N,O){if(N==O)postMessage({cmd:"processQueuedMainThreadWork"});else if(I)postMessage({targetThread:N,cmd:"processThreadQueue"});else{var G=Me.pthreads[N],te=G&&G.worker;if(!te)return;te.postMessage({cmd:"processThreadQueue"})}return 1}function W2(){Jl("")}function V2(){S||v||J("Blocking on the main thread is very dangerous, see https://emscripten.org/docs/porting/pthreads.html#blocking-on-the-main-browser-thread")}function Th(){return 2147483648}function U2(N,O,G){o().copyWithin(N,O,O+G)}function G2(){return S?dR().cpus().length:navigator.hardwareConcurrency}function hi(N,O){var G=arguments.length-2,te=arguments;return eu(function(){for(var ye=G,xe=iu(ye*8),Te=xe>>3,Fe=0;Fe<G;Fe++){var Pt=te[2+Fe];p()[Te+Fe]=Pt}return Tb(N,ye,xe,O)})}var id=[];function H2(N,O,G){id.length=O;for(var te=G>>3,ye=0;ye<O;ye++)id[ye]=p()[te+ye];var xe=N<0,Te=xe?I2[-N-1]:c1[N];return Te.apply(null,id)}function j2(N){try{return $e.grow(N-Mn.byteLength+65535>>>16),ts($e.buffer),1}catch(O){}}function q2(N){var O=o().length;if(N=N>>>0,N<=O)return!1;var G=Th();if(N>G)return!1;for(var te=1;te<=4;te*=2){var ye=O*(1+.2/te);ye=Math.min(ye,N+100663296);var xe=Math.min(G,Zl(Math.max(N,ye),65536)),Te=j2(xe);if(Te)return!0}return!1}var Ke={inEventHandler:0,removeAllEventListeners:function(){for(var N=Ke.eventHandlers.length-1;N>=0;--N)Ke._removeHandler(N);Ke.eventHandlers=[],Ke.deferredCalls=[]},registerRemoveEventListeners:function(){Ke.removeEventListenersRegistered||(x2.push(Ke.removeAllEventListeners),Ke.removeEventListenersRegistered=!0)},deferredCalls:[],deferCall:function(N,O,G){function te(Te,Fe){if(Te.length!=Fe.length)return!1;for(var Pt in Te)if(Te[Pt]!=Fe[Pt])return!1;return!0}for(var ye in Ke.deferredCalls){var xe=Ke.deferredCalls[ye];if(xe.targetFunction==N&&te(xe.argsList,G))return}Ke.deferredCalls.push({targetFunction:N,precedence:O,argsList:G}),Ke.deferredCalls.sort(function(Te,Fe){return Te.precedence<Fe.precedence})},removeDeferredCalls:function(N){for(var O=0;O<Ke.deferredCalls.length;++O)Ke.deferredCalls[O].targetFunction==N&&(Ke.deferredCalls.splice(O,1),--O)},canPerformEventHandlerRequests:function(){return Ke.inEventHandler&&Ke.currentEventHandler.allowsDeferredCalls},runDeferredCalls:function(){if(!!Ke.canPerformEventHandlerRequests())for(var N=0;N<Ke.deferredCalls.length;++N){var O=Ke.deferredCalls[N];Ke.deferredCalls.splice(N,1),--N,O.targetFunction.apply(null,O.argsList)}},eventHandlers:[],removeAllHandlersOnTarget:function(N,O){for(var G=0;G<Ke.eventHandlers.length;++G)Ke.eventHandlers[G].target==N&&(!O||O==Ke.eventHandlers[G].eventTypeString)&&Ke._removeHandler(G--)},_removeHandler:function(N){var O=Ke.eventHandlers[N];O.target.removeEventListener(O.eventTypeString,O.eventListenerFunc,O.useCapture),Ke.eventHandlers.splice(N,1)},registerOrRemoveHandler:function(N){var O=function(ye){++Ke.inEventHandler,Ke.currentEventHandler=N,Ke.runDeferredCalls(),N.handlerFunc(ye),Ke.runDeferredCalls(),--Ke.inEventHandler};if(N.callbackfunc)N.eventListenerFunc=O,N.target.addEventListener(N.eventTypeString,O,N.useCapture),Ke.eventHandlers.push(N),Ke.registerRemoveEventListeners();else for(var G=0;G<Ke.eventHandlers.length;++G)Ke.eventHandlers[G].target==N.target&&Ke.eventHandlers[G].eventTypeString==N.eventTypeString&&Ke._removeHandler(G--)},queueEventHandlerOnThread_iiii:function(N,O,G,te,ye){eu(function(){var xe=iu(12);u()[xe>>2]=G,u()[xe+4>>2]=te,u()[xe+8>>2]=ye,j1(N,637534208,O,te,xe)})},getTargetThreadForEventCallback:function(N){switch(N){case 1:return 0;case 2:return Me.currentProxiedOperationCallerThread;default:return N}},getNodeNameForTarget:function(N){return N?N==window?"#window":N==screen?"#screen":N&&N.nodeName?N.nodeName:"":""},fullscreenEnabled:function(){return document.fullscreenEnabled||document.webkitFullscreenEnabled}};function X2(N){var O=Kl(N)+1,G=H1(O);return Gs(N,G,O),G}function K2(N,O,G,te){eu(function(){var ye=iu(12),xe=0;O&&(xe=X2(O)),u()[ye>>2]=xe,u()[ye+4>>2]=G,u()[ye+8>>2]=te,j1(N,657457152,0,xe,ye)})}function Z2(N,O,G,te){O=O?On(O):"",K2(N,O,G,te)}function Y2(N){return N>2?On(N):N}var J2=[0,typeof document!="undefined"?document:0,typeof window!="undefined"?window:0];function Q2(N){N=Y2(N);var O=J2[N]||(typeof document!="undefined"?document.querySelector(N):void 0);return O}function ld(N){return Q2(N)}function Nh(N,O,G){var te=ld(N);if(!te)return-4;if(te.canvasSharedPtr&&(u()[te.canvasSharedPtr>>2]=O,u()[te.canvasSharedPtr+4>>2]=G),te.offscreenCanvas||!te.controlTransferredOffscreen){te.offscreenCanvas&&(te=te.offscreenCanvas);var ye=!1;if(te.GLctxObject&&te.GLctxObject.GLctx){var xe=te.GLctxObject.GLctx.getParameter(2978);ye=xe[0]===0&&xe[1]===0&&xe[2]===te.width&&xe[3]===te.height}te.width=O,te.height=G,ye&&te.GLctxObject.GLctx.viewport(0,0,O,G)}else if(te.canvasSharedPtr){var Te=u()[te.canvasSharedPtr+8>>2];return Z2(Te,N,O,G),1}else return-4;return 0}function Eh(N,O,G){return I?hi(2,1,N,O,G):Nh(N,O,G)}function e1(N,O,G){var te=ld(N);return te?Nh(N,O,G):Eh(N,O,G)}function t1(){throw"unwind"}function n1(N){var O=N.getExtension("ANGLE_instanced_arrays");if(O)return N.vertexAttribDivisor=function(G,te){O.vertexAttribDivisorANGLE(G,te)},N.drawArraysInstanced=function(G,te,ye,xe){O.drawArraysInstancedANGLE(G,te,ye,xe)},N.drawElementsInstanced=function(G,te,ye,xe,Te){O.drawElementsInstancedANGLE(G,te,ye,xe,Te)},1}function r1(N){var O=N.getExtension("OES_vertex_array_object");if(O)return N.createVertexArray=function(){return O.createVertexArrayOES()},N.deleteVertexArray=function(G){O.deleteVertexArrayOES(G)},N.bindVertexArray=function(G){O.bindVertexArrayOES(G)},N.isVertexArray=function(G){return O.isVertexArrayOES(G)},1}function s1(N){var O=N.getExtension("WEBGL_draw_buffers");if(O)return N.drawBuffers=function(G,te){O.drawBuffersWEBGL(G,te)},1}function a1(N){return!!(N.multiDrawWebgl=N.getExtension("WEBGL_multi_draw"))}var Dt={counter:1,buffers:[],programs:[],framebuffers:[],renderbuffers:[],textures:[],shaders:[],vaos:[],contexts:{},offscreenCanvases:{},queries:[],stringCache:{},unpackAlignment:4,recordError:function(O){Dt.lastError||(Dt.lastError=O)},getNewId:function(N){for(var O=Dt.counter++,G=N.length;G<O;G++)N[G]=null;return O},getSource:function(N,O,G,te){for(var ye="",xe=0;xe<O;++xe){var Te=te?u()[te+xe*4>>2]:-1;ye+=On(u()[G+xe*4>>2],Te<0?void 0:Te)}return ye},createContext:function(N,O){N.getContextSafariWebGL2Fixed||(N.getContextSafariWebGL2Fixed=N.getContext,N.getContext=function(ye,xe){var Te=N.getContextSafariWebGL2Fixed(ye,xe);return ye=="webgl"==Te instanceof WebGLRenderingContext?Te:null});var G=N.getContext("webgl",O);if(!G)return 0;var te=Dt.registerContext(G,O);return te},registerContext:function(N,O){var G=H1(8);u()[G+4>>2]=zh();var te={handle:G,attributes:O,version:O.majorVersion,GLctx:N};return N.canvas&&(N.canvas.GLctxObject=te),Dt.contexts[G]=te,(typeof O.enableExtensionsByDefault=="undefined"||O.enableExtensionsByDefault)&&Dt.initExtensions(te),G},makeContextCurrent:function(N){return Dt.currentContext=Dt.contexts[N],d.ctx=Dh=Dt.currentContext&&Dt.currentContext.GLctx,!(N&&!Dh)},getContext:function(N){return Dt.contexts[N]},deleteContext:function(N){Dt.currentContext===Dt.contexts[N]&&(Dt.currentContext=null),typeof Ke=="object"&&Ke.removeAllHandlersOnTarget(Dt.contexts[N].GLctx.canvas),Dt.contexts[N]&&Dt.contexts[N].GLctx.canvas&&(Dt.contexts[N].GLctx.canvas.GLctxObject=void 0),wb(Dt.contexts[N].handle),Dt.contexts[N]=null},initExtensions:function(N){if(N||(N=Dt.currentContext),!N.initExtensionsDone){N.initExtensionsDone=!0;var O=N.GLctx;n1(O),r1(O),s1(O),O.disjointTimerQueryExt=O.getExtension("EXT_disjoint_timer_query"),a1(O);var G=O.getSupportedExtensions()||[];G.forEach(function(te){!te.includes("lose_context")&&!te.includes("debug")&&O.getExtension(te)})}}},o1=["default","low-power","high-performance"];function i1(N,O){var G=O>>2,te=u()[G+6],ye={alpha:!!u()[G+0],depth:!!u()[G+1],stencil:!!u()[G+2],antialias:!!u()[G+3],premultipliedAlpha:!!u()[G+4],preserveDrawingBuffer:!!u()[G+5],powerPreference:o1[te],failIfMajorPerformanceCaveat:!!u()[G+7],majorVersion:u()[G+8],minorVersion:u()[G+9],enableExtensionsByDefault:u()[G+10],explicitSwapControl:u()[G+11],proxyContextToMainThread:u()[G+12],renderViaOffscreenBackBuffer:u()[G+13]},xe=ld(N);if(!xe||ye.explicitSwapControl)return 0;var Te=Dt.createContext(xe,ye);return Te}function l1(N,O){return i1(N,O)}var nu={mappings:{},buffers:[null,[],[]],printChar:function(N,O){var G=nu.buffers[N];O===0||O===10?((N===1?ee:Q)(Ir(G,0)),G.length=0):G.push(O)},varargs:void 0,get:function(){nu.varargs+=4;var N=u()[nu.varargs-4>>2];return N},getStr:function(N){var O=On(N);return O},get64:function(N,O){return N}};function Rh(N){return I?hi(3,1,N):0}function _h(N,O,G,te,ye){if(I)return hi(4,1,N,O,G,te,ye)}function $h(N,O,G,te){if(I)return hi(5,1,N,O,G,te);for(var ye=0,xe=0;xe<G;xe++){var Te=u()[O>>2],Fe=u()[O+4>>2];O+=8;for(var Pt=0;Pt<Fe;Pt++)nu.printChar(N,o()[Te+Pt]);ye+=Fe}return u()[te>>2]=ye,0}function u1(N){ze(N)}Me.init();var Dh,c1=[null,Ih,Eh,Rh,_h,$h],xb=!1,Ph={__clock_gettime:F2,__emscripten_init_main_thread_js:O2,__emscripten_thread_cleanup:M2,__pthread_create_js:z2,_emscripten_default_pthread_stack_size:L2,_emscripten_notify_thread_queue:B2,abort:W2,emscripten_check_blocking_allowed:V2,emscripten_get_heap_max:Th,emscripten_get_now:pi,emscripten_memcpy_big:U2,emscripten_num_logical_cores:G2,emscripten_receive_on_main_thread_js:H2,emscripten_resize_heap:q2,emscripten_set_canvas_element_size:e1,emscripten_unwind_to_js_event_loop:t1,emscripten_webgl_create_context:l1,exit:Sh,fd_close:Rh,fd_seek:_h,fd_write:$h,memory:$e||d.wasmMemory,setTempRet0:u1},bb=S2(),d1=d.___wasm_call_ctors=function(){return(d1=d.___wasm_call_ctors=d.asm.__wasm_call_ctors).apply(null,arguments)},p1=d._init=function(){return(p1=d._init=d.asm.init).apply(null,arguments)},h1=d._init_with_threads_count=function(){return(h1=d._init_with_threads_count=d.asm.init_with_threads_count).apply(null,arguments)},f1=d._get_threads_count=function(){return(f1=d._get_threads_count=d.asm.get_threads_count).apply(null,arguments)},m1=d._register_tensor=function(){return(m1=d._register_tensor=d.asm.register_tensor).apply(null,arguments)},g1=d._dispose_data=function(){return(g1=d._dispose_data=d.asm.dispose_data).apply(null,arguments)},y1=d._dispose=function(){return(y1=d._dispose=d.asm.dispose).apply(null,arguments)},A1=d._Abs=function(){return(A1=d._Abs=d.asm.Abs).apply(null,arguments)},x1=d._Add=function(){return(x1=d._Add=d.asm.Add).apply(null,arguments)},b1=d._AddN=function(){return(b1=d._AddN=d.asm.AddN).apply(null,arguments)},v1=d._All=function(){return(v1=d._All=d.asm.All).apply(null,arguments)},w1=d._Any=function(){return(w1=d._Any=d.asm.Any).apply(null,arguments)},k1=d._ArgMax=function(){return(k1=d._ArgMax=d.asm.ArgMax).apply(null,arguments)},S1=d._AvgPool=function(){return(S1=d._AvgPool=d.asm.AvgPool).apply(null,arguments)},I1=d._BatchMatMul=function(){return(I1=d._BatchMatMul=d.asm.BatchMatMul).apply(null,arguments)},C1=d._Ceil=function(){return(C1=d._Ceil=d.asm.Ceil).apply(null,arguments)},T1=d._ClipByValue=function(){return(T1=d._ClipByValue=d.asm.ClipByValue).apply(null,arguments)},N1=d._Conv2D=function(){return(N1=d._Conv2D=d.asm.Conv2D).apply(null,arguments)},E1=d._Conv2DBackpropInput=function(){return(E1=d._Conv2DBackpropInput=d.asm.Conv2DBackpropInput).apply(null,arguments)},R1=d._Cos=function(){return(R1=d._Cos=d.asm.Cos).apply(null,arguments)},_1=d._Cosh=function(){return(_1=d._Cosh=d.asm.Cosh).apply(null,arguments)},$1=d._CropAndResize=function(){return($1=d._CropAndResize=d.asm.CropAndResize).apply(null,arguments)},D1=d._Cumprod=function(){return(D1=d._Cumprod=d.asm.Cumprod).apply(null,arguments)},P1=d._Cumsum=function(){return(P1=d._Cumsum=d.asm.Cumsum).apply(null,arguments)},F1=d._DepthToSpace=function(){return(F1=d._DepthToSpace=d.asm.DepthToSpace).apply(null,arguments)},O1=d._DepthwiseConv2dNative=function(){return(O1=d._DepthwiseConv2dNative=d.asm.DepthwiseConv2dNative).apply(null,arguments)},M1=d._Elu=function(){return(M1=d._Elu=d.asm.Elu).apply(null,arguments)},z1=d._Equal=function(){return(z1=d._Equal=d.asm.Equal).apply(null,arguments)},L1=d._Exp=function(){return(L1=d._Exp=d.asm.Exp).apply(null,arguments)},B1=d._FlipLeftRight=function(){return(B1=d._FlipLeftRight=d.asm.FlipLeftRight).apply(null,arguments)},Fh=d._Floor=function(){return(Fh=d._Floor=d.asm.Floor).apply(null,arguments)},Oh=d._FloorDiv=function(){return(Oh=d._FloorDiv=d.asm.FloorDiv).apply(null,arguments)},ud=d._FusedBatchNorm=function(){return(ud=d._FusedBatchNorm=d.asm.FusedBatchNorm).apply(null,arguments)},W1=d._FusedConv2D=function(){return(W1=d._FusedConv2D=d.asm.FusedConv2D).apply(null,arguments)},V1=d._FusedDepthwiseConv2D=function(){return(V1=d._FusedDepthwiseConv2D=d.asm.FusedDepthwiseConv2D).apply(null,arguments)},ru=d._Gather=function(){return(ru=d._Gather=d.asm.Gather).apply(null,arguments)},cd=d._GatherNd=function(){return(cd=d._GatherNd=d.asm.GatherNd).apply(null,arguments)},dd=d._Greater=function(){return(dd=d._Greater=d.asm.Greater).apply(null,arguments)},vb=d._GreaterEqual=function(){return(vb=d._GreaterEqual=d.asm.GreaterEqual).apply(null,arguments)},su=d._LeakyRelu=function(){return(su=d._LeakyRelu=d.asm.LeakyRelu).apply(null,arguments)},au=d._Less=function(){return(au=d._Less=d.asm.Less).apply(null,arguments)},U1=d._LessEqual=function(){return(U1=d._LessEqual=d.asm.LessEqual).apply(null,arguments)},q=d._Log=function(){return(q=d._Log=d.asm.Log).apply(null,arguments)},re=d._LogicalAnd=function(){return(re=d._LogicalAnd=d.asm.LogicalAnd).apply(null,arguments)},Ae=d._Max=function(){return(Ae=d._Max=d.asm.Max).apply(null,arguments)},_e=d._MaxPool=function(){return(_e=d._MaxPool=d.asm.MaxPool).apply(null,arguments)},ut=d._Maximum=function(){return(ut=d._Maximum=d.asm.Maximum).apply(null,arguments)},dt=d._Mean=function(){return(dt=d._Mean=d.asm.Mean).apply(null,arguments)},Ze=d._Min=function(){return(Ze=d._Min=d.asm.Min).apply(null,arguments)},je=d._Minimum=function(){return(je=d._Minimum=d.asm.Minimum).apply(null,arguments)},Xt=d._MirrorPad=function(){return(Xt=d._MirrorPad=d.asm.MirrorPad).apply(null,arguments)},rs=d._Multiply=function(){return(rs=d._Multiply=d.asm.Multiply).apply(null,arguments)},ss=d._Neg=function(){return(ss=d._Neg=d.asm.Neg).apply(null,arguments)},ou=d._NonMaxSuppressionV3=function(){return(ou=d._NonMaxSuppressionV3=d.asm.NonMaxSuppressionV3).apply(null,arguments)},fi=d._NonMaxSuppressionV4=function(){return(fi=d._NonMaxSuppressionV4=d.asm.NonMaxSuppressionV4).apply(null,arguments)},G1=d._NonMaxSuppressionV5=function(){return(G1=d._NonMaxSuppressionV5=d.asm.NonMaxSuppressionV5).apply(null,arguments)},Bn=d._NotEqual=function(){return(Bn=d._NotEqual=d.asm.NotEqual).apply(null,arguments)},va=d._OneHot=function(){return(va=d._OneHot=d.asm.OneHot).apply(null,arguments)},Mh=d._PadV2=function(){return(Mh=d._PadV2=d.asm.PadV2).apply(null,arguments)},XN=d._Pow=function(){return(XN=d._Pow=d.asm.Pow).apply(null,arguments)},KN=d._Prelu=function(){return(KN=d._Prelu=d.asm.Prelu).apply(null,arguments)},ZN=d._Prod=function(){return(ZN=d._Prod=d.asm.Prod).apply(null,arguments)},YN=d._RealDiv=function(){return(YN=d._RealDiv=d.asm.RealDiv).apply(null,arguments)},JN=d._Relu=function(){return(JN=d._Relu=d.asm.Relu).apply(null,arguments)},QN=d._Relu6=function(){return(QN=d._Relu6=d.asm.Relu6).apply(null,arguments)},eE=d._ResizeBilinear=function(){return(eE=d._ResizeBilinear=d.asm.ResizeBilinear).apply(null,arguments)},tE=d._Reverse=function(){return(tE=d._Reverse=d.asm.Reverse).apply(null,arguments)},nE=d._RotateWithOffset=function(){return(nE=d._RotateWithOffset=d.asm.RotateWithOffset).apply(null,arguments)},rE=d._Round=function(){return(rE=d._Round=d.asm.Round).apply(null,arguments)},sE=d._Rsqrt=function(){return(sE=d._Rsqrt=d.asm.Rsqrt).apply(null,arguments)},aE=d._ScatterNd=function(){return(aE=d._ScatterNd=d.asm.ScatterNd).apply(null,arguments)},oE=d._SelectV2=function(){return(oE=d._SelectV2=d.asm.SelectV2).apply(null,arguments)},iE=d._Sigmoid=function(){return(iE=d._Sigmoid=d.asm.Sigmoid).apply(null,arguments)},lE=d._Sin=function(){return(lE=d._Sin=d.asm.Sin).apply(null,arguments)},uE=d._Softmax=function(){return(uE=d._Softmax=d.asm.Softmax).apply(null,arguments)},cE=d._SparseFillEmptyRows=function(){return(cE=d._SparseFillEmptyRows=d.asm.SparseFillEmptyRows).apply(null,arguments)},dE=d._SparseReshape=function(){return(dE=d._SparseReshape=d.asm.SparseReshape).apply(null,arguments)},pE=d._SparseSegmentReduction=function(){return(pE=d._SparseSegmentReduction=d.asm.SparseSegmentReduction).apply(null,arguments)},hE=d._Sqrt=function(){return(hE=d._Sqrt=d.asm.Sqrt).apply(null,arguments)},fE=d._Square=function(){return(fE=d._Square=d.asm.Square).apply(null,arguments)},mE=d._SquaredDifference=function(){return(mE=d._SquaredDifference=d.asm.SquaredDifference).apply(null,arguments)},gE=d._Step=function(){return(gE=d._Step=d.asm.Step).apply(null,arguments)},yE=d._StridedSlice=function(){return(yE=d._StridedSlice=d.asm.StridedSlice).apply(null,arguments)},AE=d._Sub=function(){return(AE=d._Sub=d.asm.Sub).apply(null,arguments)},xE=d._Sum=function(){return(xE=d._Sum=d.asm.Sum).apply(null,arguments)},bE=d._Tan=function(){return(bE=d._Tan=d.asm.Tan).apply(null,arguments)},vE=d._Tanh=function(){return(vE=d._Tanh=d.asm.Tanh).apply(null,arguments)},wE=d._Tile=function(){return(wE=d._Tile=d.asm.Tile).apply(null,arguments)},kE=d._TopK=function(){return(kE=d._TopK=d.asm.TopK).apply(null,arguments)},SE=d._Transform=function(){return(SE=d._Transform=d.asm.Transform).apply(null,arguments)},IE=d._Transpose=function(){return(IE=d._Transpose=d.asm.Transpose).apply(null,arguments)},CE=d.__FusedMatMul=function(){return(CE=d.__FusedMatMul=d.asm._FusedMatMul).apply(null,arguments)},H1=d._malloc=function(){return(H1=d._malloc=d.asm.malloc).apply(null,arguments)},wb=d._free=function(){return(wb=d._free=d.asm.free).apply(null,arguments)},TE=d._emscripten_tls_init=function(){return(TE=d._emscripten_tls_init=d.asm.emscripten_tls_init).apply(null,arguments)},kb=d.___errno_location=function(){return(kb=d.___errno_location=d.asm.__errno_location).apply(null,arguments)},zh=d._pthread_self=function(){return(zh=d._pthread_self=d.asm.pthread_self).apply(null,arguments)},Sb=d._emscripten_main_thread_process_queued_calls=function(){return(Sb=d._emscripten_main_thread_process_queued_calls=d.asm.emscripten_main_thread_process_queued_calls).apply(null,arguments)},NE=d.__emscripten_thread_crashed=function(){return(NE=d.__emscripten_thread_crashed=d.asm._emscripten_thread_crashed).apply(null,arguments)},Ib=d.__emscripten_thread_init=function(){return(Ib=d.__emscripten_thread_init=d.asm._emscripten_thread_init).apply(null,arguments)},EE=d._emscripten_current_thread_process_queued_calls=function(){return(EE=d._emscripten_current_thread_process_queued_calls=d.asm.emscripten_current_thread_process_queued_calls).apply(null,arguments)},RE=d._emscripten_main_browser_thread_id=function(){return(RE=d._emscripten_main_browser_thread_id=d.asm.emscripten_main_browser_thread_id).apply(null,arguments)},_E=d._emscripten_sync_run_in_main_thread_2=function(){return(_E=d._emscripten_sync_run_in_main_thread_2=d.asm.emscripten_sync_run_in_main_thread_2).apply(null,arguments)},Cb=d._emscripten_sync_run_in_main_thread_4=function(){return(Cb=d._emscripten_sync_run_in_main_thread_4=d.asm.emscripten_sync_run_in_main_thread_4).apply(null,arguments)},Tb=d._emscripten_run_in_main_runtime_thread_js=function(){return(Tb=d._emscripten_run_in_main_runtime_thread_js=d.asm.emscripten_run_in_main_runtime_thread_js).apply(null,arguments)},j1=d._emscripten_dispatch_to_thread_=function(){return(j1=d._emscripten_dispatch_to_thread_=d.asm.emscripten_dispatch_to_thread_).apply(null,arguments)},q1=d.__emscripten_thread_free_data=function(){return(q1=d.__emscripten_thread_free_data=d.asm._emscripten_thread_free_data).apply(null,arguments)},$E=d.__emscripten_thread_exit=function(){return($E=d.__emscripten_thread_exit=d.asm._emscripten_thread_exit).apply(null,arguments)},DE=d._memalign=function(){return(DE=d._memalign=d.asm.memalign).apply(null,arguments)},Nb=d._emscripten_stack_set_limits=function(){return(Nb=d._emscripten_stack_set_limits=d.asm.emscripten_stack_set_limits).apply(null,arguments)},X1=d.stackSave=function(){return(X1=d.stackSave=d.asm.stackSave).apply(null,arguments)},Lh=d.stackRestore=function(){return(Lh=d.stackRestore=d.asm.stackRestore).apply(null,arguments)},iu=d.stackAlloc=function(){return(iu=d.stackAlloc=d.asm.stackAlloc).apply(null,arguments)},PE=d.dynCall_iijjiiii=function(){return(PE=d.dynCall_iijjiiii=d.asm.dynCall_iijjiiii).apply(null,arguments)},FE=d.dynCall_jiji=function(){return(FE=d.dynCall_jiji=d.asm.dynCall_jiji).apply(null,arguments)},Eb=d.__emscripten_allow_main_runtime_queued_calls=21456;d.cwrap=Fn,d.keepRuntimeAlive=ci,d.PThread=Me,d.PThread=Me,d.wasmMemory=$e,d.ExitStatus=pd;var Bh;function pd(N){this.name="ExitStatus",this.message="Program terminated with exit("+N+")",this.status=N}ns=function N(){Bh||K1(),Bh||(ns=N)};function K1(N){if(N=N||y,ba>0)return;if(I){h(d),sd(),postMessage({cmd:"loaded"});return}if(zn(),ba>0)return;function O(){Bh||(Bh=!0,d.calledRun=!0,!At&&(sd(),h(d),d.onRuntimeInitialized&&d.onRuntimeInitialized(),w2()))}d.setStatus?(d.setStatus("Running..."),setTimeout(function(){setTimeout(function(){d.setStatus("")},1),O()},1)):O()}d.run=K1;function OE(N,O){if(Pn=N,!O&&I)throw Ih(N),"unwind";ci()||v2(),ME(N)}function ME(N){Pn=N,ci()||(Me.terminateAllThreads(),d.onExit&&d.onExit(N),At=!0),A(N,new pd(N))}if(d.preInit)for(typeof d.preInit=="function"&&(d.preInit=[d.preInit]);d.preInit.length>0;)d.preInit.pop()();K1();var Wh;m&&(Wh={uncaughtException:process.listeners("uncaughtException").filter(function(N){return!m.uncaughtException.indexOf(N)>-1}),unhandledRejection:process.listeners("unhandledRejection").filter(function(N){return!m.unhandledRejection.indexOf(N)>-1})});var Vh;if(typeof WasmBackendModule!="undefined")Vh=WasmBackendModule;else if(typeof s!="undefined")Vh=s;else throw new Error("Could not find wasm module in post.js");if(Wh){var zE=Vh._dispose;Vh._dispose=function(){zE(),Wh.uncaughtException.forEach(function(N){process.removeListener("uncaughtException",N)}),Wh.unhandledRejection.forEach(function(N){process.removeListener("unhandledRejection",N)})}}return s.ready}})();typeof e=="object"&&typeof t=="object"?t.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):typeof e=="object"&&(e.WasmBackendModuleThreadedSimd=n)}}),hR=dn({"src/tfjs-backend-wasm/wasm-out/tfjs-backend-wasm.js"(e,t){var n=(()=>{var r=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(r=r||__filename),function(s){s=s||{};var a=typeof s!="undefined"?s:{},o,i;a.ready=new Promise(function(q,re){o=q,i=re});var l;typeof process!="undefined"&&process.listeners&&(l={uncaughtException:process.listeners("uncaughtException"),unhandledRejection:process.listeners("unhandledRejection")});var u=Object.assign({},a),c=[],p="./this.program",d=(q,re)=>{throw re},h=typeof window=="object",f=typeof importScripts=="function",m=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g="";function y(q){return a.locateFile?a.locateFile(q,g):g+q}var x,A,b,v;function S(q){if(q instanceof cd)return;_("exiting due to exception: "+q)}var I,E,R;m?(f?g=mf().dirname(g)+"/":g=__dirname+"/",R=()=>{E||(I=dy(),E=mf())},x=function(re,Ae){return R(),re=E.normalize(re),I.readFileSync(re,Ae?void 0:"utf8")},b=q=>{var re=x(q,!0);return re.buffer||(re=new Uint8Array(re)),re},A=(q,re,Ae)=>{R(),q=E.normalize(q),I.readFile(q,function(_e,ut){_e?Ae(_e):re(ut.buffer)})},process.argv.length>1&&(p=process.argv[1].replace(/\\/g,"/")),c=process.argv.slice(2),process.on("uncaughtException",function(q){if(!(q instanceof cd))throw q}),process.on("unhandledRejection",function(q){throw q}),d=(q,re)=>{if(rd())throw process.exitCode=q,re;S(re),process.exit(q)},a.inspect=function(){return"[Emscripten Module object]"}):(h||f)&&(f?g=self.location.href:typeof document!="undefined"&&document.currentScript&&(g=document.currentScript.src),r&&(g=r),g.indexOf("blob:")!==0?g=g.substr(0,g.replace(/[?#].*/,"").lastIndexOf("/")+1):g="",x=q=>{var re=new XMLHttpRequest;return re.open("GET",q,!1),re.send(null),re.responseText},f&&(b=q=>{var re=new XMLHttpRequest;return re.open("GET",q,!1),re.responseType="arraybuffer",re.send(null),new Uint8Array(re.response)}),A=(q,re,Ae)=>{var _e=new XMLHttpRequest;_e.open("GET",q,!0),_e.responseType="arraybuffer",_e.onload=()=>{if(_e.status==200||_e.status==0&&_e.response){re(_e.response);return}Ae()},_e.onerror=Ae,_e.send(null)},v=q=>document.title=q);var P=a.print||console.log.bind(console),_=a.printErr||console.warn.bind(console);Object.assign(a,u),u=null,a.arguments&&(c=a.arguments),a.thisProgram&&(p=a.thisProgram),a.quit&&(d=a.quit);var D=4;function T(q){T.shown||(T.shown={}),T.shown[q]||(T.shown[q]=1,_(q))}function F(q,re){if(typeof WebAssembly.Function=="function"){for(var Ae={i:"i32",j:"i64",f:"f32",d:"f64"},_e={parameters:[],results:re[0]=="v"?[]:[Ae[re[0]]]},ut=1;ut<re.length;++ut)_e.parameters.push(Ae[re[ut]]);return new WebAssembly.Function(_e,q)}var dt=[1,0,1,96],Ze=re.slice(0,1),je=re.slice(1),Xt={i:127,j:126,f:125,d:124};dt.push(je.length);for(var ut=0;ut<je.length;++ut)dt.push(Xt[je[ut]]);Ze=="v"?dt.push(0):dt=dt.concat([1,Xt[Ze]]),dt[1]=dt.length-2;var rs=new Uint8Array([0,97,115,109,1,0,0,0].concat(dt,[2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0])),ss=new WebAssembly.Module(rs),ou=new WebAssembly.Instance(ss,{e:{f:q}}),fi=ou.exports.f;return fi}var U=[],X;function z(){if(U.length)return U.pop();try{Aa.grow(1)}catch(q){throw q instanceof RangeError?"Unable to grow wasm table. Set ALLOW_TABLE_GROWTH.":q}return Aa.length-1}function Z(q,re){for(var Ae=q;Ae<q+re;Ae++){var _e=od(Ae);_e&&X.set(_e,Ae)}}var W=0,ee=q=>{W=q},Q;a.wasmBinary&&(Q=a.wasmBinary);var ae=a.noExitRuntime||!0;typeof WebAssembly!="object"&&ui("no native wasm support detected");var J,se=!1,ie;function me(q,re){q||ui(re)}function be(q){var re=a["_"+q];return re}function Ee(q,re,Ae,_e,ut){var dt={string:function(Bn){var va=0;if(Bn!=null&&Bn!==0){var Mh=(Bn.length<<2)+1;va=ud(Mh),ft(Bn,va,Mh)}return va},array:function(Bn){var va=ud(Bn.length);return At(Bn,va),va}};function Ze(Bn){return re==="string"?it(Bn):re==="boolean"?Boolean(Bn):Bn}var je=be(q),Xt=[],rs=0;if(_e)for(var ss=0;ss<_e.length;ss++){var ou=dt[Ae[ss]];ou?(rs===0&&(rs=Fh()),Xt[ss]=ou(_e[ss])):Xt[ss]=_e[ss]}var fi=je.apply(null,Xt);function G1(Bn){return rs!==0&&Oh(rs),Ze(Bn)}return fi=G1(fi),fi}function Re(q,re,Ae,_e){Ae=Ae||[];var ut=Ae.every(function(Ze){return Ze==="number"}),dt=re!=="string";return dt&&ut&&!_e?be(q):function(){return Ee(q,re,Ae,arguments,_e)}}var ze=1,Be=typeof TextDecoder!="undefined"?new TextDecoder("utf8"):void 0;function nt(q,re,Ae){for(var _e=re+Ae,ut=re;q[ut]&&!(ut>=_e);)++ut;if(ut-re>16&&q.subarray&&Be)return Be.decode(q.subarray(re,ut));for(var dt="";re<ut;){var Ze=q[re++];if(!(Ze&128)){dt+=String.fromCharCode(Ze);continue}var je=q[re++]&63;if((Ze&224)==192){dt+=String.fromCharCode((Ze&31)<<6|je);continue}var Xt=q[re++]&63;if((Ze&240)==224?Ze=(Ze&15)<<12|je<<6|Xt:Ze=(Ze&7)<<18|je<<12|Xt<<6|q[re++]&63,Ze<65536)dt+=String.fromCharCode(Ze);else{var rs=Ze-65536;dt+=String.fromCharCode(55296|rs>>10,56320|rs&1023)}}return dt}function it(q,re){return q?nt(Fn,q,re):""}function lt(q,re,Ae,_e){if(!(_e>0))return 0;for(var ut=Ae,dt=Ae+_e-1,Ze=0;Ze<q.length;++Ze){var je=q.charCodeAt(Ze);if(je>=55296&&je<=57343){var Xt=q.charCodeAt(++Ze);je=65536+((je&1023)<<10)|Xt&1023}if(je<=127){if(Ae>=dt)break;re[Ae++]=je}else if(je<=2047){if(Ae+1>=dt)break;re[Ae++]=192|je>>6,re[Ae++]=128|je&63}else if(je<=65535){if(Ae+2>=dt)break;re[Ae++]=224|je>>12,re[Ae++]=128|je>>6&63,re[Ae++]=128|je&63}else{if(Ae+3>=dt)break;re[Ae++]=240|je>>18,re[Ae++]=128|je>>12&63,re[Ae++]=128|je>>6&63,re[Ae++]=128|je&63}}return re[Ae]=0,Ae-ut}function ft(q,re,Ae){return lt(q,Fn,re,Ae)}function $e(q){for(var re=0,Ae=0;Ae<q.length;++Ae){var _e=q.charCodeAt(Ae);_e>=55296&&_e<=57343&&(_e=65536+((_e&1023)<<10)|q.charCodeAt(++Ae)&1023),_e<=127?++re:_e<=2047?re+=2:_e<=65535?re+=3:re+=4}return re}var wt=typeof TextDecoder!="undefined"?new TextDecoder("utf-16le"):void 0;function At(q,re){nn.set(q,re)}function Pn(q,re,Ae){for(var _e=0;_e<q.length;++_e)nn[re++>>0]=q.charCodeAt(_e);Ae||(nn[re>>0]=0)}function qt(q,re){return q%re>0&&(q+=re-q%re),q}var ur,nn,Fn,cr,dr,Sn,Ir,On,Us;function Gs(q){ur=q,a.HEAP8=nn=new Int8Array(q),a.HEAP16=cr=new Int16Array(q),a.HEAP32=Sn=new Int32Array(q),a.HEAPU8=Fn=new Uint8Array(q),a.HEAPU16=dr=new Uint16Array(q),a.HEAPU32=Ir=new Uint32Array(q),a.HEAPF32=On=new Float32Array(q),a.HEAPF64=Us=new Float64Array(q)}var Kl=a.INITIAL_MEMORY||16777216,Aa,Hs=[],nd=[],Zl=[],Mn=!1,uh=!1,ch=0;function rd(){return ae||ch>0}function dh(){if(a.preRun)for(typeof a.preRun=="function"&&(a.preRun=[a.preRun]);a.preRun.length;)fh(a.preRun.shift());ad(Hs)}function ph(){Mn=!0,ad(nd)}function cb(){uh=!0}function hh(){if(a.postRun)for(typeof a.postRun=="function"&&(a.postRun=[a.postRun]);a.postRun.length;)mh(a.postRun.shift());ad(Zl)}function fh(q){Hs.unshift(q)}function ts(q){nd.unshift(q)}function mh(q){Zl.unshift(q)}var Cr=0,Yl=null,xa=null;function x2(q){Cr++,a.monitorRunDependencies&&a.monitorRunDependencies(Cr)}function gh(q){if(Cr--,a.monitorRunDependencies&&a.monitorRunDependencies(Cr),Cr==0&&(Yl!==null&&(clearInterval(Yl),Yl=null),xa)){var re=xa;xa=null,re()}}a.preloadedImages={},a.preloadedAudios={};function ui(q){a.onAbort&&a.onAbort(q),q="Aborted("+q+")",_(q),se=!0,ie=1,q+=". Build with -s ASSERTIONS=1 for more info.";var re=new WebAssembly.RuntimeError(q);throw i(re),re}var b2="data:application/octet-stream;base64,";function yh(q){return q.startsWith(b2)}function ci(q){return q.startsWith("file://")}var zn;zn="tfjs-backend-wasm.wasm",yh(zn)||(zn=y(zn));function sd(q){try{if(q==zn&&Q)return new Uint8Array(Q);if(b)return b(q);throw"both async and sync fetching of the wasm failed"}catch(re){ui(re)}}function v2(){if(!Q&&(h||f)){if(typeof fetch=="function"&&!ci(zn))return fetch(zn,{credentials:"same-origin"}).then(function(q){if(!q.ok)throw"failed to load wasm binary file at '"+zn+"'";return q.arrayBuffer()}).catch(function(){return sd(zn)});if(A)return new Promise(function(q,re){A(zn,function(Ae){q(new Uint8Array(Ae))},re)})}return Promise.resolve().then(function(){return sd(zn)})}function w2(){var q={env:eu,wasi_snapshot_preview1:eu};function re(Ze,je){var Xt=Ze.exports;a.asm=Xt,J=a.asm.memory,Gs(J.buffer),Aa=a.asm.__indirect_function_table,ts(a.asm.__wasm_call_ctors),gh("wasm-instantiate")}x2("wasm-instantiate");function Ae(Ze){re(Ze.instance)}function _e(Ze){return v2().then(function(je){return WebAssembly.instantiate(je,q)}).then(function(je){return je}).then(Ze,function(je){_("failed to asynchronously prepare wasm: "+je),ui(je)})}function ut(){return!Q&&typeof WebAssembly.instantiateStreaming=="function"&&!yh(zn)&&!ci(zn)&&typeof fetch=="function"?fetch(zn,{credentials:"same-origin"}).then(function(Ze){var je=WebAssembly.instantiateStreaming(Ze,q);return je.then(Ae,function(Xt){return _("wasm streaming compile failed: "+Xt),_("falling back to ArrayBuffer instantiation"),_e(Ae)})}):_e(Ae)}if(a.instantiateWasm)try{var dt=a.instantiateWasm(q,re);return dt}catch(Ze){return _("Module.instantiateWasm callback failed with error: "+Ze),!1}return ut().catch(i),{}}var db,pb;function ad(q){for(;q.length>0;){var re=q.shift();if(typeof re=="function"){re(a);continue}var Ae=re.func;typeof Ae=="number"?re.arg===void 0?od(Ae)():od(Ae)(re.arg):Ae(re.arg===void 0?null:re.arg)}}function ba(q){return q}function Ah(q){var re=/\b_Z[\w\d_]+/g;return q.replace(re,function(Ae){var _e=Ae;return Ae===_e?Ae:_e+" ["+Ae+"]"})}var ns=[];function od(q){var re=ns[q];return re||(q>=ns.length&&(ns.length=q+1),ns[q]=re=Aa.get(q)),re}function hb(){var q=new Error;if(!q.stack){try{throw new Error}catch(re){q=re}if(!q.stack)return"(no stack trace available)"}return q.stack.toString()}function Jl(q,re){Aa.set(q,re),ns[q]=re}function k2(){ui("")}function xh(q,re,Ae){Fn.copyWithin(q,re,re+Ae)}function bh(){return 2147483648}function Ln(q){try{return J.grow(q-ur.byteLength+65535>>>16),Gs(J.buffer),1}catch(re){}}function vh(q){var re=Fn.length;q=q>>>0;var Ae=bh();if(q>Ae)return!1;for(var _e=1;_e<=4;_e*=2){var ut=re*(1+.2/_e);ut=Math.min(ut,q+100663296);var dt=Math.min(Ae,qt(Math.max(q,ut),65536)),Ze=Ln(dt);if(Ze)return!0}return!1}var Ql={mappings:{},buffers:[null,[],[]],printChar:function(q,re){var Ae=Ql.buffers[q];re===0||re===10?((q===1?P:_)(nt(Ae,0)),Ae.length=0):Ae.push(re)},varargs:void 0,get:function(){Ql.varargs+=4;var q=Sn[Ql.varargs-4>>2];return q},getStr:function(q){var re=it(q);return re},get64:function(q,re){return q}};function S2(q){return 0}function fb(q,re,Ae,_e,ut){}function mb(q,re,Ae,_e){for(var ut=0,dt=0;dt<Ae;dt++){var Ze=Sn[re>>2],je=Sn[re+4>>2];re+=8;for(var Xt=0;Xt<je;Xt++)Ql.printChar(q,Fn[Ze+Xt]);ut+=je}return Sn[_e>>2]=ut,0}function I2(q){ee(q)}var wh=!1,eu={abort:k2,emscripten_memcpy_big:xh,emscripten_resize_heap:vh,fd_close:S2,fd_seek:fb,fd_write:mb,setTempRet0:I2},qN=w2(),gb=a.___wasm_call_ctors=function(){return(gb=a.___wasm_call_ctors=a.asm.__wasm_call_ctors).apply(null,arguments)},C2=a._init=function(){return(C2=a._init=a.asm.init).apply(null,arguments)},T2=a._init_with_threads_count=function(){return(T2=a._init_with_threads_count=a.asm.init_with_threads_count).apply(null,arguments)},kh=a._get_threads_count=function(){return(kh=a._get_threads_count=a.asm.get_threads_count).apply(null,arguments)},Sh=a._register_tensor=function(){return(Sh=a._register_tensor=a.asm.register_tensor).apply(null,arguments)},N2=a._dispose_data=function(){return(N2=a._dispose_data=a.asm.dispose_data).apply(null,arguments)},Me=a._dispose=function(){return(Me=a._dispose=a.asm.dispose).apply(null,arguments)},E2=a._Abs=function(){return(E2=a._Abs=a.asm.Abs).apply(null,arguments)},Ih=a._Add=function(){return(Ih=a._Add=a.asm.Add).apply(null,arguments)},di=a._AddN=function(){return(di=a._AddN=a.asm.AddN).apply(null,arguments)},tu=a._All=function(){return(tu=a._All=a.asm.All).apply(null,arguments)},R2=a._Any=function(){return(R2=a._Any=a.asm.Any).apply(null,arguments)},yb=a._ArgMax=function(){return(yb=a._ArgMax=a.asm.ArgMax).apply(null,arguments)},_2=a._AvgPool=function(){return(_2=a._AvgPool=a.asm.AvgPool).apply(null,arguments)},Ab=a._BatchMatMul=function(){return(Ab=a._BatchMatMul=a.asm.BatchMatMul).apply(null,arguments)},pi=a._Ceil=function(){return(pi=a._Ceil=a.asm.Ceil).apply(null,arguments)},$2=a._ClipByValue=function(){return($2=a._ClipByValue=a.asm.ClipByValue).apply(null,arguments)},D2=a._Conv2D=function(){return(D2=a._Conv2D=a.asm.Conv2D).apply(null,arguments)},P2=a._Conv2DBackpropInput=function(){return(P2=a._Conv2DBackpropInput=a.asm.Conv2DBackpropInput).apply(null,arguments)},F2=a._Cos=function(){return(F2=a._Cos=a.asm.Cos).apply(null,arguments)},O2=a._Cosh=function(){return(O2=a._Cosh=a.asm.Cosh).apply(null,arguments)},M2=a._CropAndResize=function(){return(M2=a._CropAndResize=a.asm.CropAndResize).apply(null,arguments)},Ch=a._Cumprod=function(){return(Ch=a._Cumprod=a.asm.Cumprod).apply(null,arguments)},z2=a._Cumsum=function(){return(z2=a._Cumsum=a.asm.Cumsum).apply(null,arguments)},L2=a._DepthToSpace=function(){return(L2=a._DepthToSpace=a.asm.DepthToSpace).apply(null,arguments)},B2=a._DepthwiseConv2dNative=function(){return(B2=a._DepthwiseConv2dNative=a.asm.DepthwiseConv2dNative).apply(null,arguments)},W2=a._Elu=function(){return(W2=a._Elu=a.asm.Elu).apply(null,arguments)},V2=a._Equal=function(){return(V2=a._Equal=a.asm.Equal).apply(null,arguments)},Th=a._Exp=function(){return(Th=a._Exp=a.asm.Exp).apply(null,arguments)},U2=a._FlipLeftRight=function(){return(U2=a._FlipLeftRight=a.asm.FlipLeftRight).apply(null,arguments)},G2=a._Floor=function(){return(G2=a._Floor=a.asm.Floor).apply(null,arguments)},hi=a._FloorDiv=function(){return(hi=a._FloorDiv=a.asm.FloorDiv).apply(null,arguments)},id=a._FusedBatchNorm=function(){return(id=a._FusedBatchNorm=a.asm.FusedBatchNorm).apply(null,arguments)},H2=a._FusedConv2D=function(){return(H2=a._FusedConv2D=a.asm.FusedConv2D).apply(null,arguments)},j2=a._FusedDepthwiseConv2D=function(){return(j2=a._FusedDepthwiseConv2D=a.asm.FusedDepthwiseConv2D).apply(null,arguments)},q2=a._Gather=function(){return(q2=a._Gather=a.asm.Gather).apply(null,arguments)},Ke=a._GatherNd=function(){return(Ke=a._GatherNd=a.asm.GatherNd).apply(null,arguments)},X2=a._Greater=function(){return(X2=a._Greater=a.asm.Greater).apply(null,arguments)},K2=a._GreaterEqual=function(){return(K2=a._GreaterEqual=a.asm.GreaterEqual).apply(null,arguments)},Z2=a._LeakyRelu=function(){return(Z2=a._LeakyRelu=a.asm.LeakyRelu).apply(null,arguments)},Y2=a._Less=function(){return(Y2=a._Less=a.asm.Less).apply(null,arguments)},J2=a._LessEqual=function(){return(J2=a._LessEqual=a.asm.LessEqual).apply(null,arguments)},Q2=a._Log=function(){return(Q2=a._Log=a.asm.Log).apply(null,arguments)},ld=a._LogicalAnd=function(){return(ld=a._LogicalAnd=a.asm.LogicalAnd).apply(null,arguments)},Nh=a._Max=function(){return(Nh=a._Max=a.asm.Max).apply(null,arguments)},Eh=a._MaxPool=function(){return(Eh=a._MaxPool=a.asm.MaxPool).apply(null,arguments)},e1=a._Maximum=function(){return(e1=a._Maximum=a.asm.Maximum).apply(null,arguments)},t1=a._Mean=function(){return(t1=a._Mean=a.asm.Mean).apply(null,arguments)},n1=a._Min=function(){return(n1=a._Min=a.asm.Min).apply(null,arguments)},r1=a._Minimum=function(){return(r1=a._Minimum=a.asm.Minimum).apply(null,arguments)},s1=a._MirrorPad=function(){return(s1=a._MirrorPad=a.asm.MirrorPad).apply(null,arguments)},a1=a._Multiply=function(){return(a1=a._Multiply=a.asm.Multiply).apply(null,arguments)},Dt=a._Neg=function(){return(Dt=a._Neg=a.asm.Neg).apply(null,arguments)},o1=a._NonMaxSuppressionV3=function(){return(o1=a._NonMaxSuppressionV3=a.asm.NonMaxSuppressionV3).apply(null,arguments)},i1=a._NonMaxSuppressionV4=function(){return(i1=a._NonMaxSuppressionV4=a.asm.NonMaxSuppressionV4).apply(null,arguments)},l1=a._NonMaxSuppressionV5=function(){return(l1=a._NonMaxSuppressionV5=a.asm.NonMaxSuppressionV5).apply(null,arguments)},nu=a._NotEqual=function(){return(nu=a._NotEqual=a.asm.NotEqual).apply(null,arguments)},Rh=a._OneHot=function(){return(Rh=a._OneHot=a.asm.OneHot).apply(null,arguments)},_h=a._PadV2=function(){return(_h=a._PadV2=a.asm.PadV2).apply(null,arguments)},$h=a._Pow=function(){return($h=a._Pow=a.asm.Pow).apply(null,arguments)},u1=a._Prelu=function(){return(u1=a._Prelu=a.asm.Prelu).apply(null,arguments)},Dh=a._Prod=function(){return(Dh=a._Prod=a.asm.Prod).apply(null,arguments)},c1=a._RealDiv=function(){return(c1=a._RealDiv=a.asm.RealDiv).apply(null,arguments)},xb=a._Relu=function(){return(xb=a._Relu=a.asm.Relu).apply(null,arguments)},Ph=a._Relu6=function(){return(Ph=a._Relu6=a.asm.Relu6).apply(null,arguments)},bb=a._ResizeBilinear=function(){return(bb=a._ResizeBilinear=a.asm.ResizeBilinear).apply(null,arguments)},d1=a._Reverse=function(){return(d1=a._Reverse=a.asm.Reverse).apply(null,arguments)},p1=a._RotateWithOffset=function(){return(p1=a._RotateWithOffset=a.asm.RotateWithOffset).apply(null,arguments)},h1=a._Round=function(){return(h1=a._Round=a.asm.Round).apply(null,arguments)},f1=a._Rsqrt=function(){return(f1=a._Rsqrt=a.asm.Rsqrt).apply(null,arguments)},m1=a._ScatterNd=function(){return(m1=a._ScatterNd=a.asm.ScatterNd).apply(null,arguments)},g1=a._SelectV2=function(){return(g1=a._SelectV2=a.asm.SelectV2).apply(null,arguments)},y1=a._Sigmoid=function(){return(y1=a._Sigmoid=a.asm.Sigmoid).apply(null,arguments)},A1=a._Sin=function(){return(A1=a._Sin=a.asm.Sin).apply(null,arguments)},x1=a._Softmax=function(){return(x1=a._Softmax=a.asm.Softmax).apply(null,arguments)},b1=a._SparseFillEmptyRows=function(){return(b1=a._SparseFillEmptyRows=a.asm.SparseFillEmptyRows).apply(null,arguments)},v1=a._SparseReshape=function(){return(v1=a._SparseReshape=a.asm.SparseReshape).apply(null,arguments)},w1=a._SparseSegmentReduction=function(){return(w1=a._SparseSegmentReduction=a.asm.SparseSegmentReduction).apply(null,arguments)},k1=a._Sqrt=function(){return(k1=a._Sqrt=a.asm.Sqrt).apply(null,arguments)},S1=a._Square=function(){return(S1=a._Square=a.asm.Square).apply(null,arguments)},I1=a._SquaredDifference=function(){return(I1=a._SquaredDifference=a.asm.SquaredDifference).apply(null,arguments)},C1=a._Step=function(){return(C1=a._Step=a.asm.Step).apply(null,arguments)},T1=a._StridedSlice=function(){return(T1=a._StridedSlice=a.asm.StridedSlice).apply(null,arguments)},N1=a._Sub=function(){return(N1=a._Sub=a.asm.Sub).apply(null,arguments)},E1=a._Sum=function(){return(E1=a._Sum=a.asm.Sum).apply(null,arguments)},R1=a._Tan=function(){return(R1=a._Tan=a.asm.Tan).apply(null,arguments)},_1=a._Tanh=function(){return(_1=a._Tanh=a.asm.Tanh).apply(null,arguments)},$1=a._Tile=function(){return($1=a._Tile=a.asm.Tile).apply(null,arguments)},D1=a._TopK=function(){return(D1=a._TopK=a.asm.TopK).apply(null,arguments)},P1=a._Transform=function(){return(P1=a._Transform=a.asm.Transform).apply(null,arguments)},F1=a._Transpose=function(){return(F1=a._Transpose=a.asm.Transpose).apply(null,arguments)},O1=a.__FusedMatMul=function(){return(O1=a.__FusedMatMul=a.asm._FusedMatMul).apply(null,arguments)},M1=a._malloc=function(){return(M1=a._malloc=a.asm.malloc).apply(null,arguments)},z1=a._free=function(){return(z1=a._free=a.asm.free).apply(null,arguments)},L1=a.___errno_location=function(){return(L1=a.___errno_location=a.asm.__errno_location).apply(null,arguments)},B1=a._emscripten_main_thread_process_queued_calls=function(){return(B1=a._emscripten_main_thread_process_queued_calls=a.asm.emscripten_main_thread_process_queued_calls).apply(null,arguments)},Fh=a.stackSave=function(){return(Fh=a.stackSave=a.asm.stackSave).apply(null,arguments)},Oh=a.stackRestore=function(){return(Oh=a.stackRestore=a.asm.stackRestore).apply(null,arguments)},ud=a.stackAlloc=function(){return(ud=a.stackAlloc=a.asm.stackAlloc).apply(null,arguments)},W1=a.dynCall_iijjiiii=function(){return(W1=a.dynCall_iijjiiii=a.asm.dynCall_iijjiiii).apply(null,arguments)},V1=a.dynCall_jiji=function(){return(V1=a.dynCall_jiji=a.asm.dynCall_jiji).apply(null,arguments)};a.cwrap=Re;var ru;function cd(q){this.name="ExitStatus",this.message="Program terminated with exit("+q+")",this.status=q}xa=function q(){ru||dd(),ru||(xa=q)};function dd(q){if(q=q||c,Cr>0||(dh(),Cr>0))return;function re(){ru||(ru=!0,a.calledRun=!0,!se&&(ph(),o(a),a.onRuntimeInitialized&&a.onRuntimeInitialized(),hh()))}a.setStatus?(a.setStatus("Running..."),setTimeout(function(){setTimeout(function(){a.setStatus("")},1),re()},1)):re()}a.run=dd;function vb(q){ie=q,rd()||(a.onExit&&a.onExit(q),se=!0),d(q,new cd(q))}if(a.preInit)for(typeof a.preInit=="function"&&(a.preInit=[a.preInit]);a.preInit.length>0;)a.preInit.pop()();dd();var su;l&&(su={uncaughtException:process.listeners("uncaughtException").filter(function(q){return!l.uncaughtException.indexOf(q)>-1}),unhandledRejection:process.listeners("unhandledRejection").filter(function(q){return!l.unhandledRejection.indexOf(q)>-1})});var au;if(typeof s!="undefined")au=s;else if(typeof WasmBackendModuleThreadedSimd!="undefined")au=WasmBackendModuleThreadedSimd;else throw new Error("Could not find wasm module in post.js");if(su){var U1=au._dispose;au._dispose=function(){U1(),su.uncaughtException.forEach(function(q){process.removeListener("uncaughtException",q)}),su.unhandledRejection.forEach(function(q){process.removeListener("unhandledRejection",q)})}}return s.ready}})();typeof e=="object"&&typeof t=="object"?t.exports=n:typeof define=="function"&&define.amd?define([],function(){return n}):typeof e=="object"&&(e.WasmBackendModule=n)}}),fR=1e-7,mR=1e-4,Zd=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}},Ou=class{refCount(e){return Tr("refCount")}incRef(e){return Tr("incRef")}timerAvailable(){return!0}time(e){return Tr("time")}read(e){return Tr("read")}readSync(e){return Tr("readSync")}readToGPU(e,t){return Tr("readToGPU")}numDataIds(){return Tr("numDataIds")}disposeData(e,t){return Tr("disposeData")}write(e,t,n){return Tr("write")}move(e,t,n,r,s){return Tr("move")}memory(){return Tr("memory")}floatPrecision(){return Tr("floatPrecision")}epsilon(){return this.floatPrecision()===32?fR:mR}dispose(){return Tr("dispose")}};function Tr(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 v4(e){let t=e.length,n=0;for(;t>0;)n=Math.random()*t|0,t--,gf(e,t,n)}function gR(e,t){if(e.length!==t.length)throw new Error(`Array sizes must match to be shuffled together First array length was ${e.length}Second array length was ${t.length}`);let n=e.length,r=0;for(;n>0;)r=Math.random()*n|0,n--,gf(e,n,r),gf(t,n,r)}function Od(e,t,n){return Math.max(e,Math.min(t,n))}function yR(e){return e%2===0?e:e+1}function gf(e,t,n){let r=e[t];e[t]=e[n],e[n]=r}function AR(e){let t=0;for(let n=0;n<e.length;n++)t+=e[n];return t}function xR(e,t){let n=Math.random();return t*n+(1-n)*e}function bR(e,t){let n=0;for(let r=0;r<e.length;r++){let s=Number(e[r])-Number(t[r]);n+=s*s}return n}function M(e,t){if(!e)throw new Error(typeof t=="string"?t:t())}function jn(e,t,n=""){M(Ka(e,t),()=>n+` Shapes ${e} and ${t} must match`)}function Ui(e){M(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function _i(e,t=[],n=!1){if(t==null&&(t=[]),Array.isArray(e)||In(e)&&!n)for(let r=0;r<e.length;++r)_i(e[r],t,n);else t.push(e);return t}function Tt(e){if(e.length===0)return 1;let t=e[0];for(let n=1;n<e.length;n++)t*=e[n];return t}function vR(e){return e.length===0}function Ka(e,t){if(e===t)return!0;if(e==null||t==null||e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;return!0}function wu(e){return e%1===0}function wR(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 kR(e){let t=Math.ceil(Math.sqrt(e));return[t,Math.ceil(e/t)]}function SR(e){let t=new Uint32Array(e);for(let n=0;n<e;++n)t[n]=n;return v4(t),t}function _d(e,t){return t<=e.length?e:e+" ".repeat(t-e.length)}function IR(e,t=r=>0,n){return new Promise((r,s)=>{let a=0,o=()=>{if(e()){r();return}a++;let i=t(a);if(n!=null&&a>=n){s();return}setTimeout(o,i)};o()})}function CR(e,t){let n=1,r=-1;for(let a=0;a<e.length;++a)if(e[a]>=0)n*=e[a];else if(e[a]===-1){if(r!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${r} and dim ${a}`);r=a}else if(e[a]<0)throw Error(`Shapes can not be < 0. Found ${e[a]} at dim ${a}`);if(r===-1){if(t>0&&t!==n)throw Error(`Size(${t}) must match the product of shape ${e}`);return e}if(n===0)throw Error(`Cannot infer the missing size in [${e}] when there are 0 elements`);if(t%n!==0)throw Error(`The implicit shape can't be a fractional number. Got ${t} / ${n}`);let s=e.slice();return s[r]=t/n,s}function jr(e,t){let n=t.length;return e=e==null?t.map((r,s)=>s):[].concat(e),M(e.every(r=>r>=-n&&r<n),()=>`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),M(e.every(r=>wu(r)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(r=>r<0?n+r:r)}function w4(e,t){let n=[],r=[],s=t!=null&&Array.isArray(t)&&t.length===0,a=t==null||s?null:jr(t,e).sort(),o=0;for(let i=0;i<e.length;++i){if(a!=null){if(a[o]===i&&e[i]!==1)throw new Error(`Can't squeeze axis ${i} since its dim '${e[i]}' is not 1`);(a[o]==null||a[o]>i)&&e[i]===1&&(n.push(e[i]),r.push(i)),a[o]<=i&&o++}e[i]!==1&&(n.push(e[i]),r.push(i))}return{newShape:n,keptDims:r}}function k4(e,t){let n=null;if(e==null||e==="float32")n=new Float32Array(t);else if(e==="int32")n=new Int32Array(t);else if(e==="bool")n=new Uint8Array(t);else throw new Error(`Unknown data type ${e}`);return n}function S4(e,t){let n=null;if(e==null||e==="float32")n=new Float32Array(t);else if(e==="int32")n=new Int32Array(t);else if(e==="bool")n=new Uint8Array(t);else if(e==="string")n=new Array(t);else throw new Error(`Unknown data type ${e}`);return n}function I4(e,t){for(let n=0;n<e.length;n++){let r=e[n];if(isNaN(r)||!isFinite(r))throw Error(`A tensor of type ${t} being uploaded contains ${r}.`)}}function C4(e){return e==="bool"||e==="complex64"||e==="float32"||e==="int32"||e==="string"}function TR(e,t){return!(t==="complex64"||t==="float32"&&e!=="complex64"||t==="int32"&&e!=="float32"&&e!=="complex64"||t==="bool"&&e==="bool")}function In(e){return e instanceof Float32Array||e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray}function cg(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 T4(e){if(e==null)return 0;let t=0;return e.forEach(n=>t+=n.length),t}function Na(e){return typeof e=="string"||e instanceof String}function N4(e){return typeof e=="boolean"}function E4(e){return typeof e=="number"}function Kf(e){return Array.isArray(e)?Kf(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray?"int32":E4(e)?"float32":Na(e)?"string":N4(e)?"bool":"float32"}function Da(e){return!!(e&&e.constructor&&e.call&&e.apply)}function yf(e,t){for(let n=t;n<e;++n)if(e%n===0)return n;return e}function Mu(e){let t=e.length;if(t<2)return[];let n=new Array(t-1);n[t-2]=e[t-1];for(let r=t-3;r>=0;--r)n[r]=n[r+1]*e[r+1];return n}function R4(e,t,n,r=!1){let s=new Array;if(t.length===1){let a=t[0]*(r?2:1);for(let o=0;o<a;o++)s[o]=n[e+o]}else{let a=t[0],o=t.slice(1),i=o.reduce((l,u)=>l*u)*(r?2:1);for(let l=0;l<a;l++)s[l]=R4(e+l*i,o,n,r)}return s}function yu(e,t,n=!1){if(e.length===0)return t[0];let r=e.reduce((s,a)=>s*a)*(n?2:1);if(r===0)return[];if(r!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return R4(0,e,t,n)}function py(e,t){let n=Zf(e,t);for(let r=0;r<n.length;r++)n[r]=1;return n}function Zf(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 NR(e,t){let n=e.reduce((r,s)=>r*s,1);if(t==null||t==="float32")return yu(e,new Float32Array(n));if(t==="int32")return yu(e,new Int32Array(n));if(t==="bool")return yu(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function hy(e){e.forEach(t=>{M(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function ER(e,t,n){if(t===0)return 0;if(t===1)return e[0];let r=e[e.length-1];for(let s=0;s<e.length-1;++s)r+=n[s]*e[s];return r}function RR(e,t,n){if(t===0)return[];if(t===1)return[e];let r=new Array(t);for(let s=0;s<r.length-1;++s)r[s]=Math.floor(e/n[s]),e-=r[s]*n[s];return r[r.length-1]=e,r}function fy(e){return e&&e.then&&typeof e.then=="function"}var Db="tfjsflags",_4=class{constructor(e){this.global=e,this.flags={},this.flagRegistry={},this.urlFlags={},this.getQueryParams=_R,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,n){if(this.flagRegistry[e]={evaluationFn:t,setHook:n},this.urlFlags[e]!=null){let r=this.urlFlags[e];Y().getBool("IS_TEST")||Y().getBool("PROD")||console.warn(`Setting feature override from URL ${e}: ${r}.`),this.set(e,r)}}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(fy(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);Db in e&&e[Db].split(",").forEach(n=>{let[r,s]=n.split(":");this.urlFlags[r]=DR(r,s)})}};function _R(e){let t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...r)=>($R(t,r[0],r[1]),r.join("="))),t}function $R(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function DR(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 xs}var xs=null;function PR(e){xs=e}var Y1;function $4(){if(Y1==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");Y1=e}return Y1}function FR(){let e=$4();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function my(e,t){let n=FR();if(n.has(e))return n.get(e);{let r=t();return n.set(e,r),n.get(e)}}var Gi="Abs",zu="Acos",Lu="Acosh",ea="Add",Za="AddN",Bu="All",Wu="Any",Ya="ArgMax",Vu="ArgMin",Uu="Asin",Gu="Asinh",Hu="Atan",ju="Atanh",qu="Atan2",Ja="AvgPool",Yf="AvgPoolGrad",Yd="AvgPool3D",Jf="AvgPool3DGrad",Qa="BatchMatMul",Hi="BatchToSpaceND",Qf="Bincount",D4="BroadcastTo",em="BroadcastArgs",eo="Cast",to="Ceil",ta="ClipByValue",Jd="Complex",Qd="ComplexAbs",ji="Concat",no="Conv2D",tm="Conv2DBackpropFilter",ro="Conv2DBackpropInput",ep="Conv3D",nm="Conv3DBackpropFilterV2",rm="Conv3DBackpropInputV2",so="Cos",ao="Cosh",qi="Cumprod",oo="Cumsum",Xi="CropAndResize",sm="DenseBincount",Ki="DepthToSpace",io="DepthwiseConv2dNative",am="DepthwiseConv2dNativeBackpropFilter",om="DepthwiseConv2dNativeBackpropInput",im="Diag",tp="Dilation2D",Af="Dilation2DBackpropInput",xf="Dilation2DBackpropFilter",lo="RealDiv",np="Einsum",uo="Elu",lm="EluGrad",Xu="Erf",Zi="Equal",co="Exp",Yi="ExpandDims",Ji="Expm1",um="FFT",Ku="Fill",Qi="FlipLeftRight",po="Floor",ho="FloorDiv",fo="FusedBatchNorm",el="GatherV2",tl="GatherNd",nl="Greater",mo="GreaterEqual",go="Identity",cm="IFFT",rp="Imag",Zu="IsFinite",Yu="IsInf",Ju="IsNan",yo="LeakyRelu",rl="Less",sl="LessEqual",dm="LinSpace",Ao="Log",Qu="Log1p",al="LogicalAnd",ec="LogicalNot",sp="LogicalOr",P4="LogSoftmax",ap="LRN",pm="LRNGrad",xo="Max",bo="Maximum",vo="MaxPool",hm="MaxPoolGrad",op="MaxPool3D",fm="MaxPool3DGrad",mm="MaxPoolWithArgmax",wo="Mean",ko="Min",So="Minimum",Io="MirrorPad",tc="Mod",gm="Multinomial",Co="Multiply",ol="Neg",il="NotEqual",ll="NonMaxSuppressionV3",nc="NonMaxSuppressionV4",ul="NonMaxSuppressionV5",cl="OnesLike",dl="OneHot",pl="Pack",To="PadV2",OR="Pool",No="Pow",Eo="Prelu",Ro="Prod",rc="Range",ip="Real",sc="Reciprocal",_o="Relu",hl="Reshape",ac="ResizeNearestNeighbor",ym="ResizeNearestNeighborGrad",$o="ResizeBilinear",Am="ResizeBilinearGrad",Do="Relu6",fl="Reverse",ml="Round",Po="Rsqrt",gl="ScatterNd",yl="Select",oc="Selu",Al="Slice",Fo="Sin",xl="Sinh",ic="Sign",Oo="Sigmoid",lc="Softplus",Mo="Sqrt",zo="Sum",bl="SpaceToBatchND",vl="SplitV",Lo="Softmax",lp="SparseFillEmptyRows",uc="SparseReshape",up="SparseSegmentMean",cp="SparseSegmentSum",dp="SparseToDense",Bo="SquaredDifference",cc="Square",wl="StridedSlice",pp="StringNGrams",xm="StringSplit",bm="StringToHashBucketFast",Wo="Sub",kl="Tan",Vo="Tanh",na="Tile",Sl="TopK",Il="Transform",Uo="Transpose",vm="Unique",Cl="Unpack",hp="UnsortedSegmentSum",Tl="ZerosLike",Go="Step",Md="FromPixels",Nl="RotateWithOffset",Pa="_FusedMatMul",Fa="FusedConv2D",Oa="FusedDepthwiseConv2D";function Ta(...e){Y().getBool("IS_TEST")||Y().getBool("PROD")||console.warn(...e)}function MR(...e){Y().getBool("IS_TEST")||Y().getBool("PROD")||console.log(...e)}var ku=my("kernelRegistry",()=>new Map),zd=my("gradRegistry",()=>new Map);function bf(e,t){let n=gy(e,t);return ku.get(n)}function dg(e){return zd.get(e)}function _s(e){let t=ku.entries(),n=[];for(;;){let{done:r,value:s}=t.next();if(r)break;let[a,o]=s,[i]=a.split("_");i===e&&n.push(o)}return n}function qr(e){let{kernelName:t,backendName:n}=e,r=gy(t,n);ku.has(r)&&Ta(`The kernel '${t}' for backend '${n}' is already registered`),ku.set(r,e)}function F4(e){let{kernelName:t}=e;zd.has(t)&&Y().getBool("DEBUG")&&Ta(`Overriding the gradient for '${t}'`),zd.set(t,e)}function zR(e,t){let n=gy(e,t);if(!ku.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);ku.delete(n)}function LR(e){if(!zd.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);zd.delete(e)}function BR(e,t){_s(e).forEach(r=>{let s=Object.assign({},r,{backendName:t});qr(s)})}function gy(e,t){return`${t}_${e}`}var w={};Le(w,{arraysEqual:()=>Ka,assert:()=>M,assertNonNegativeIntegerDimensions:()=>hy,assertNonNull:()=>Ui,assertShapesMatch:()=>jn,bytesFromStringArray:()=>T4,bytesPerElement:()=>cg,checkConversionForErrors:()=>I4,clamp:()=>Od,computeStrides:()=>Mu,createScalarValue:()=>jR,createShuffledIndices:()=>SR,decodeString:()=>vf,distSquared:()=>bR,encodeString:()=>mp,fetch:()=>XR,fingerPrint64:()=>HR,flatten:()=>_i,getArrayFromDType:()=>S4,getTypedArrayFromDType:()=>k4,hasEncodingLoss:()=>TR,hexToLong:()=>fp,indexToLoc:()=>RR,inferDtype:()=>Kf,inferFromImplicitShape:()=>CR,isBoolean:()=>N4,isFunction:()=>Da,isInt:()=>wu,isNumber:()=>E4,isPromise:()=>fy,isScalarShape:()=>vR,isString:()=>Na,isTypedArray:()=>In,isValidDtype:()=>C4,locToIndex:()=>ER,makeOnesTypedArray:()=>py,makeZerosNestedTypedArray:()=>NR,makeZerosTypedArray:()=>Zf,nearestDivisor:()=>yf,nearestLargerEven:()=>yR,now:()=>Ld,parseAxisParam:()=>jr,randUniform:()=>xR,repeatedTry:()=>IR,rightPad:()=>_d,shuffle:()=>v4,shuffleCombo:()=>gR,sizeFromShape:()=>Tt,sizeToSquarishShape:()=>kR,squeezeShape:()=>w4,sum:()=>AR,swap:()=>gf,tanh:()=>wR,toNestedArray:()=>yu,toTypedArray:()=>wm});var Pb=Vi(JE()),bi=Pb.default||Pb;function fp(e){return bi.fromString(e,!0,16)}var O4=fp("c3a5c85c97cb3127"),yi=fp("b492b66fbe98f273"),Wn=fp("9ae16a3b2f90404f");function pg(e){return e.xor(e.shru(47))}function M4(e,t,n){let r=e.slice(t,t+n);return bi.fromBytes(Array.from(r),!0,!0)}function kt(e,t){return M4(e,t,8)}function Fb(e,t){return M4(e,t,4)}function hn(e,t){return t===0?e:e.shru(t).or(e.shl(64-t))}function Ra(e,t,n=fp("9ddfea08eb382d69")){let r=e.xor(t).mul(n);r=r.xor(r.shru(47));let s=t.xor(r).mul(n);return s=s.xor(s.shru(47)),s=s.mul(n),s}function WR(e,t,n,r,s,a){s=s.add(e),a=hn(a.add(s).add(r),21);let o=s;return s=s.add(t),s=s.add(n),a=a.add(hn(s,44)),[s.add(r),a.add(o)]}function Hh(e,t,n,r){return WR(kt(e,t),kt(e,t+8),kt(e,t+16),kt(e,t+24),n,r)}function VR(e,t=e.length){if(t>=8){let n=Wn.add(t*2),r=kt(e,0).add(Wn),s=kt(e,t-8),a=hn(s,37).mul(n).add(r),o=hn(r,25).add(s).mul(n);return Ra(a,o,n)}if(t>=4){let n=Wn.add(t*2),r=Fb(e,0);return Ra(r.shl(3).add(t),Fb(e,t-4),n)}if(t>0){let n=e[0],r=e[t>>1],s=e[t-1],a=n+(r<<8),o=t+(s<<2);return pg(Wn.mul(a).xor(O4.mul(o))).mul(Wn)}return Wn}function UR(e,t=e.length){let n=Wn.add(t*2),r=kt(e,0).mul(yi),s=kt(e,8),a=kt(e,t-8).mul(n),o=kt(e,t-16).mul(Wn);return Ra(hn(r.add(s),43).add(hn(a,30)).add(o),r.add(hn(s.add(Wn),18)).add(a),n)}function GR(e,t=e.length){let n=Wn.add(t*2),r=kt(e,0).mul(Wn),s=kt(e,8),a=kt(e,t-8).mul(n),o=kt(e,t-16).mul(Wn),i=hn(r.add(s),43).add(hn(a,30)).add(o),l=Ra(i,r.add(hn(s.add(Wn),18)).add(a),n),u=kt(e,16).mul(n),c=kt(e,24),p=i.add(kt(e,t-32)).mul(n),d=l.add(kt(e,t-24)).mul(n);return Ra(hn(u.add(c),43).add(hn(p,30)).add(d),u.add(hn(c.add(r),18)).add(p),n)}function HR(e,t=e.length){let n=bi.fromNumber(81,!0);if(t<=32)return t<=16?VR(e,t):UR(e,t);if(t<=64)return GR(e,t);let r=n,s=n.mul(yi).add(113),a=pg(s.mul(Wn).add(113)).mul(Wn),o=[bi.UZERO,bi.UZERO],i=[bi.UZERO,bi.UZERO];r=r.mul(Wn).add(kt(e,0));let l=0,u=(t-1>>6)*64,c=u+(t-1&63)-63;do r=hn(r.add(s).add(o[0]).add(kt(e,l+8)),37).mul(yi),s=hn(s.add(o[1]).add(kt(e,l+48)),42).mul(yi),r=r.xor(i[1]),s=s.add(o[0]).add(kt(e,l+40)),a=hn(a.add(i[0]),33).mul(yi),o=Hh(e,l,o[1].mul(yi),r.add(i[0])),i=Hh(e,l+32,a.add(i[1]),s.add(kt(e,l+16))),[a,r]=[r,a],l+=64;while(l!==u);let p=yi.add(a.and(255).shl(1));return l=c,i[0]=i[0].add(t-1&63),o[0]=o[0].add(i[0]),i[0]=i[0].add(o[0]),r=hn(r.add(s).add(o[0]).add(kt(e,l+8)),37).mul(p),s=hn(s.add(o[1]).add(kt(e,l+48)),42).mul(p),r=r.xor(i[1].mul(9)),s=s.add(o[0].mul(9).add(kt(e,l+40))),a=hn(a.add(i[0]),33).mul(p),o=Hh(e,l,o[1].mul(p),r.add(i[0])),i=Hh(e,l+32,a.add(i[1]),s.add(kt(e,l+16))),[a,r]=[r,a],Ra(Ra(o[0],i[0],p).add(pg(s).mul(O4)).add(a),Ra(o[1],i[1],p).add(r),p)}function jR(e,t){return t==="string"?mp(e):wm([e],t)}function qR(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function wm(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=_i(e)),Y().getBool("DEBUG")&&I4(e,t),qR(e,t))return e;if(t==null||t==="float32"||t==="complex64")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool"){let n=new Uint8Array(e.length);for(let r=0;r<n.length;++r)Math.round(e[r])!==0&&(n[r]=1);return n}else throw new Error(`Unknown data type ${t}`)}function Ld(){return Y().platform.now()}function XR(e,t){return Y().platform.fetch(e,t)}function mp(e,t="utf-8"){return t=t||"utf-8",Y().platform.encode(e,t)}function vf(e,t="utf-8"){return t=t||"utf-8",Y().platform.decode(e,t)}var KR=class{constructor(e,t){this.backendTimer=e,this.logger=t,t==null&&(this.logger=new YR)}profileKernel(e,t,n){let r,s=()=>{r=n()},a,o=Ld();if(this.backendTimer.timerAvailable())a=this.backendTimer.time(s);else{s();for(let l of r)l.dataSync();a=Promise.resolve({kernelMs:Ld()-o})}if(Y().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let l=0;l<r.length;l++){let u=r[l];u.data().then(c=>{ZR(c,u.dtype,e)})}return{kernelName:e,outputs:r,inputs:t,timeMs:a.then(l=>l.kernelMs),extraInfo:a.then(l=>l.getExtraProfileInfo!=null?l.getExtraProfileInfo():"")}}logKernelProfile(e){let{kernelName:t,outputs:n,timeMs:r,inputs:s,extraInfo:a}=e;n.forEach(o=>{Promise.all([o.data(),r,a]).then(i=>{this.logger.logKernelProfile(t,o,i[0],i[1],s,i[2])})})}};function ZR(e,t,n){if(t!=="float32")return!1;for(let r=0;r<e.length;r++){let s=e[r];if(isNaN(s)||!isFinite(s))return console.warn(`Found ${s} in the result of '${n}'`),!0}return!1}var YR=class{logKernelProfile(e,t,n,r,s,a){let o=typeof r=="number"?_d(`${r}ms`,9):r.error,i=_d(e,25),l=t.rank,u=t.size,c=_d(t.shape.toString(),14),p="";for(let d in s){let h=s[d];if(h!=null){let f=h.shape||t.shape,m=f.length;p+=`${d}: ${m}D ${m>0?f:""} `}}console.log(`%c${i} %c${o} %c${l}D ${c} %c${u} %c${p} %c${a}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function JR(e,t,n){let r={},s={};for(let l=0;l<t.length;l++)r[t[l].id]=!0;for(let l=0;l<e.length;l++){let u=e[l],c=u.inputs;for(let p in c){let d=c[p],h=!1;for(let f=0;f<t.length;f++)if(r[d.id]){u.outputs.forEach(m=>r[m.id]=!0),h=!0,s[u.id]=!0;break}if(h)break}}let a={};a[n.id]=!0;let o={};for(let l=e.length-1;l>=0;l--){let u=e[l],c=u.inputs;for(let p=0;p<u.outputs.length;p++)if(a[u.outputs[p].id]){for(let d in c)a[c[d].id]=!0,o[u.id]=!0;break}}let i=[];for(let l=0;l<e.length;l++){let u=e[l];if(s[u.id]&&o[u.id]){let c={};for(let d in u.inputs){let h=u.inputs[d];r[h.id]&&(c[d]=h)}let p=Object.assign({},u);p.inputs=c,p.outputs=u.outputs,i.push(p)}}return i}function QR(e,t,n,r){for(let s=t.length-1;s>=0;s--){let a=t[s],o=[];if(a.outputs.forEach(l=>{let u=e[l.id];u!=null?o.push(u):o.push(null)}),a.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${a.kernelName}.`);let i=a.gradient(o);for(let l in a.inputs){if(!(l in i))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(i)}.`);let u=n(()=>i[l]());if(u.dtype!=="float32")throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${u.dtype}'`);let c=a.inputs[l];if(!Ka(u.shape,c.shape))throw new Error(`Error in gradient for op ${a.kernelName}. The gradient of input '${l}' has shape '${u.shape}', which does not match the shape of the input '${c.shape}'`);if(e[c.id]==null)e[c.id]=u;else{let p=e[c.id];e[c.id]=r(p,u),p.dispose()}}}}var Ob=20,yd=3,J1=7;function e_(e,t,n,r){let s=Mu(t),a=t_(e,t,n,s),o=t.length,i=rf(e,t,n,s,a),l=["Tensor"];return r&&(l.push(` dtype: ${n}`),l.push(` rank: ${o}`),l.push(` shape: [${t}]`),l.push(" values:")),l.push(i.map(u=>" "+u).join(`
|
|
`)),l.join(`
|
|
`)}function t_(e,t,n,r){let s=Tt(t),a=r[r.length-1],o=new Array(a).fill(0),i=t.length,l=n==="complex64"?wd(e):e;if(i>1)for(let u=0;u<s/a;u++){let c=u*a;for(let p=0;p<a;p++)o[p]=Math.max(o[p],vd(l[c+p],0,n).length)}return o}function vd(e,t,n){let r;return Array.isArray(e)?r=`${parseFloat(e[0].toFixed(J1))} + ${parseFloat(e[1].toFixed(J1))}j`:Na(e)?r=`'${e}'`:n==="bool"?r=z4(e):r=parseFloat(e.toFixed(J1)).toString(),_d(r,t)}function z4(e){return e===0?"false":"true"}function rf(e,t,n,r,s,a=!0){let o=n==="complex64"?2:1,i=t[0],l=t.length;if(l===0){if(n==="complex64"){let m=wd(e);return[vd(m[0],0,n)]}return n==="bool"?[z4(e[0])]:[e[0].toString()]}if(l===1){if(i>Ob){let g=yd*o,y=Array.from(e.slice(0,g)),x=Array.from(e.slice((i-yd)*o,i*o));return n==="complex64"&&(y=wd(y),x=wd(x)),["["+y.map((A,b)=>vd(A,s[b],n)).join(", ")+", ..., "+x.map((A,b)=>vd(A,s[i-yd+b],n)).join(", ")+"]"]}let m=n==="complex64"?wd(e):Array.from(e);return["["+m.map((g,y)=>vd(g,s[y],n)).join(", ")+"]"]}let u=t.slice(1),c=r.slice(1),p=r[0]*o,d=[];if(i>Ob){for(let m=0;m<yd;m++){let g=m*p,y=g+p;d.push(...rf(e.slice(g,y),u,n,c,s,!1))}d.push("...");for(let m=i-yd;m<i;m++){let g=m*p,y=g+p;d.push(...rf(e.slice(g,y),u,n,c,s,m===i-1))}}else for(let m=0;m<i;m++){let g=m*p,y=g+p;d.push(...rf(e.slice(g,y),u,n,c,s,m===i-1))}let h=l===2?",":"";d[0]="["+d[0]+h;for(let m=1;m<d.length-1;m++)d[m]=" "+d[m]+h;let f=`,
|
|
`;for(let m=2;m<l;m++)f+=`
|
|
`;return d[d.length-1]=" "+d[d.length-1]+"]"+(a?"":f),d}function wd(e){let t=[];for(let n=0;n<e.length;n+=2)t.push([e[n],e[n+1]]);return t}var on=class{constructor(e,t,n){if(this.dtype=t,this.shape=e.slice(),this.size=Tt(e),n!=null){let r=n.length;M(r===this.size,()=>`Length of values '${r}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||S4(t,this.size),this.strides=Mu(e)}set(e,...t){t.length===0&&(t=[0]),M(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);let n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let r of e){if(r<0||r>=this.shape[t]){let s=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(s)}t++}let n=e[e.length-1];for(let r=0;r<e.length-1;++r)n+=this.strides[r]*e[r];return this.values[n]}locToIndex(e){if(this.rank===0)return 0;if(this.rank===1)return e[0];let t=e[e.length-1];for(let n=0;n<e.length-1;++n)t+=this.strides[n]*e[n];return t}indexToLoc(e){if(this.rank===0)return[];if(this.rank===1)return[e];let t=new Array(this.shape.length);for(let n=0;n<t.length-1;++n)t[n]=Math.floor(e/this.strides[n]),e-=t[n]*this.strides[n];return t[t.length-1]=e,t}get rank(){return this.shape.length}toTensor(){return is().makeTensor(this.values,this.shape,this.dtype)}},is=null,fu=null,n_=null;function r_(e){is=e}function s_(e){fu=e}function a_(e){n_=e}var rt=class{constructor(e,t,n,r){this.kept=!1,this.isDisposedInternal=!1,this.shape=e.slice(),this.dtype=t||"float32",this.size=Tt(e),this.strides=Mu(e),this.dataId=n,this.id=r,this.rankType=this.rank<5?this.rank.toString():"higher"}get rank(){return this.shape.length}async buffer(){let e=await this.data();return fu.buffer(this.shape,this.dtype,e)}bufferSync(){return fu.buffer(this.shape,this.dtype,this.dataSync())}async array(){let e=await this.data();return yu(this.shape,e,this.dtype==="complex64")}arraySync(){return yu(this.shape,this.dataSync(),this.dtype==="complex64")}async data(){this.throwIfDisposed();let e=is().read(this.dataId);if(this.dtype==="string"){let t=await e;try{return t.map(n=>vf(n))}catch(n){throw new Error("Failed to decode the string bytes into utf-8. To get the original bytes, call tensor.bytes().")}}return e}dataToGPU(e){return this.throwIfDisposed(),is().readToGPU(this.dataId,e)}dataSync(){this.throwIfDisposed();let e=is().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>vf(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 is().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(is().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return fu.print(this,e)}clone(){return this.throwIfDisposed(),fu.clone(this)}toString(e=!1){let t=this.dataSync();return e_(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),fu.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),is().makeVariable(this,e,t,n)}};Object.defineProperty(rt,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function o_(){return my("Tensor",()=>rt)}o_();var Bd=class extends rt{constructor(e,t,n,r){super(e.shape,e.dtype,e.dataId,r),this.trainable=t,this.name=n}assign(e){if(e.dtype!==this.dtype)throw new Error(`dtype of the new value (${e.dtype}) and previous value (${this.dtype}) must match`);if(!Ka(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);is().disposeTensor(this),this.dataId=e.dataId,is().incRef(this,null)}dispose(){is().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(Bd,Symbol.hasInstance,{value:e=>e instanceof rt&&e.assign!=null&&e.assign instanceof Function});var ds={};Le(ds,{assertTypesMatch:()=>G4,getTensorsInContainer:()=>yy,isTensorInList:()=>l_,makeTypesMatch:()=>Lt});var L4=(e=>(e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6",e))(L4||{}),B4=(e=>(e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64",e))(B4||{}),W4=(e=>(e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64",e))(W4||{}),V4=(e=>(e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64",e))(V4||{}),U4=(e=>(e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64",e))(U4||{}),i_={float32:V4,int32:B4,bool:W4,complex64:U4};function Nn(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return i_[e][t]}function gp(e){return Nn(e,"int32")}function Lt(e,t){if(e.dtype===t.dtype)return[e,t];let n=Nn(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function G4(e,t){M(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function l_(e,t){return t.some(n=>n.id===e.id)}function yy(e){let t=[];return H4(e,t,new Set),t}function H4(e,t,n){if(e==null)return;if(e instanceof rt){t.push(e);return}if(!u_(e))return;let r=e;for(let s in r){let a=r[s];n.has(a)||(n.add(a),H4(a,t,n))}}function u_(e){return Array.isArray(e)||typeof e=="object"}function Q1(e){return e.kernelName!=null}var Mb=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()}},hg=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new Mb}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 n=e[t];if(await this.initializeBackend(n).success){await this.setBackend(n);return}}throw new Error("Could not initialize any backends, all backend initializations failed.")}get backend(){if(this.pendingBackendInit!=null)throw new Error(`Backend '${this.backendName}' has not yet been initialized. Make sure to await tf.ready() or await tf.setBackend() before calling other methods`);if(this.backendInstance==null){let{name: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,n=1){return e in this.registryFactory?(Ta(`${e} backend was already registered. Reusing existing backend factory.`),!1):(this.registryFactory[e]={factory:t,priority:n},!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:n}=this.initializeBackend(e);if(!(n?await t:t))return!1}return this.backendInstance=this.registry[e],this.setupRegisteredKernels(),this.profiler=new KR(this.backendInstance),!0}setupRegisteredKernels(){_s(this.backendName).forEach(t=>{t.setupFunc!=null&&t.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){_s(e).forEach(n=>{n.disposeFunc!=null&&n.disposeFunc(this.registry[e])})}initializeBackend(e){let t=this.registryFactory[e];if(t==null)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{let n=t.factory();if(n&&!(n instanceof Ou)&&typeof n.then=="function"){let r=++this.pendingBackendInitId,s=n.then(a=>r<this.pendingBackendInitId?!1:(this.registry[e]=a,this.pendingBackendInit=null,!0)).catch(a=>(r<this.pendingBackendInitId||(this.pendingBackendInit=null,Ta(`Initialization of backend ${e} failed`),Ta(a.stack||a.message)),!1));return this.pendingBackendInit=s,{success:s,asyncInit:!0}}else return this.registry[e]=n,{success:!0,asyncInit:!1}}catch(n){return Ta(`Initialization of backend ${e} failed`),Ta(n.stack||n.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 n=e[t],{success:r,asyncInit:s}=this.initializeBackend(n);if(s||r)return{name:n,asyncInit:s}}throw new Error("Could not initialize any backends, all backend initializations failed.")}moveData(e,t){let n=this.state.tensorInfo.get(t),r=n.backend,s=this.readSync(t),a=r.refCount(t);r.disposeData(t,!0),n.backend=e,e.move(t,s,n.shape,n.dtype,a),this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack[this.state.numDataMovesStack.length-1]++}tidy(e,t){let n=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");n=e}let r;return this.scopedRun(()=>this.startScope(n),()=>this.endScope(r),()=>(r=t(),r instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),r))}scopedRun(e,t,n){e();try{let r=n();return t(),r}catch(r){throw t(),r}}nextTensorId(){return hg.nextTensorId++}nextVariableId(){return hg.nextVariableId++}clone(e){let t=B.runKernel(go,{x:e}),n={x:e},r=a=>({x:()=>{let o="float32",i={x:a},l={dtype:o};return B.runKernel(eo,i,l)}}),s=[];return this.addTapeNode(this.state.activeScope.name,n,[t],r,s,{}),t}runKernel(e,t,n){if(this.backendName==null&&this.backend,!(bf(e,this.backendName)!=null))throw new Error(`Kernel '${e}' not registered for backend '${this.backendName}'`);return this.runKernelFunc({kernelName:e,inputs:t,attrs:n})}shouldCheckForMemLeaks(){return this.ENV.getBool("IS_TEST")}checkKernelForMemLeak(e,t,n){let r=this.backend.numDataIds(),s=0;n.forEach(i=>{s+=i.dtype==="complex64"?3:1});let a=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],o=r-t-s-a;if(o>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${o} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[],r=this.isTapeOn(),s=this.state.numBytes,a=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let o;this.backendName==null&&this.backend;let i,l=Q1(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(Q1(e)){let{kernelName:h,inputs:f,attrs:m}=e;this.backendName==null&&this.backend;let g=bf(h,this.backendName);M(g!=null,()=>`Cannot find registered kernel '${h}' for backend '${this.backendName}'`),o=()=>{let y=this.backend.numDataIds();i=g.kernelFunc({inputs:f,attrs:m,backend:this.backend});let x=Array.isArray(i)?i:[i];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(h,y,x);let A=x.map(b=>{if(b.rank!=null)return b;let{dataId:v,shape:S,dtype:I}=b;return this.makeTensorFromDataId(v,S,I)});if(r){let b=this.getTensorsForGradient(h,f,A);n=this.saveTensorsForBackwardMode(b)}return A}}else{let{forwardFunc:h}=e,f=m=>{!r||(n=m.map(g=>this.keep(this.clone(g))))};o=()=>{let m=this.backend.numDataIds();i=this.tidy(()=>h(this.backend,f));let g=Array.isArray(i)?i:[i];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,m,g),g}}let{inputs:u,attrs:c}=e,p=Q1(e)?null:e.backwardsFunc,d;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=o():(d=this.profiler.profileKernel(l,u,()=>o()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(d),t=d.outputs)}),r&&this.addTapeNode(l,u,t,p,n,c),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-s,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-a,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(u).map(h=>u[h]!=null?u[h].shape:null),outputShapes:t.map(h=>h.shape),kernelTimeMs:d.timeMs,extraInfo:d.extraInfo}),Array.isArray(i)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(n=>this.keep(this.clone(n)))}getTensorsForGradient(e,t,n){let r=dg(e);if(r!=null){let s=r.inputsToSave||[],a=r.outputsToSave||[],o;r.saveAllInputs?(M(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),o=Object.keys(t).map(l=>t[l])):o=s.map(l=>t[l]);let i=n.filter((l,u)=>a[u]);return o.concat(i)}return[]}makeTensor(e,t,n,r){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",r=r||this.backend;let s=e;n==="string"&&Na(e[0])&&(s=e.map(i=>mp(i)));let a=r.write(s,t,n),o=new rt(t,n,a,this.nextTensorId());if(this.trackTensor(o,r),n==="string"){let i=this.state.tensorInfo.get(a),l=T4(s);this.state.numBytes+=l-i.bytes,i.bytes=l}return o}makeTensorFromDataId(e,t,n,r){n=n||"float32";let s=new rt(t,n,e,this.nextTensorId());return this.trackTensor(s,r),s}makeVariable(e,t=!0,n,r){n=n||this.nextVariableId().toString(),r!=null&&r!==e.dtype&&(e=e.cast(r));let s=new Bd(e,t,n,this.nextTensorId());if(this.state.registeredVariables[s.name]!=null)throw new Error(`Variable with name ${s.name} was already registered`);return this.state.registeredVariables[s.name]=s,this.incRef(s,this.backend),s}trackTensor(e,t){this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++;let n=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(n=e.size*cg(e.dtype)),this.state.numBytes+=n,this.state.tensorInfo.has(e.dataId)||(this.state.numDataBuffers++,this.state.tensorInfo.set(e.dataId,{backend:t||this.backend,dtype:e.dtype,shape:e.shape,bytes:n})),e instanceof Bd||this.track(e)}incRef(e,t){this.trackTensor(e,t),this.backend.incRef(e.dataId)}removeDataId(e,t){this.state.tensorInfo.has(e)&&this.state.tensorInfo.get(e).backend===t&&(this.state.tensorInfo.delete(e),this.state.numDataBuffers--)}disposeTensor(e){if(!this.state.tensorInfo.has(e.dataId))return;let t=this.state.tensorInfo.get(e.dataId);if(this.state.numTensors--,e.dtype==="string"&&(this.state.numStringTensors--,this.state.numBytes-=t.bytes),e.dtype!=="complex64"&&e.dtype!=="string"){let n=e.size*cg(e.dtype);this.state.numBytes-=n}t.backend.disposeData(e.dataId)&&this.removeDataId(e.dataId,t.backend)}disposeVariables(){for(let e in this.state.registeredVariables){let t=this.state.registeredVariables[e];this.disposeVariable(t)}}disposeVariable(e){this.disposeTensor(e),this.state.registeredVariables[e.name]!=null&&delete this.state.registeredVariables[e.name]}memory(){let e=this.backend.memory();return e.numTensors=this.state.numTensors,e.numDataBuffers=this.state.numDataBuffers,e.numBytes=this.state.numBytes,this.state.numStringTensors>0&&(e.unreliable=!0,e.reasons==null&&(e.reasons=[]),e.reasons.push("Memory usage by string tensors is approximate (2 bytes per character)")),e}async profile(e){this.state.profiling=!0;let t=this.state.numBytes,n=this.state.numTensors;this.state.activeProfile.kernels=[],this.state.activeProfile.result=await e(),this.state.profiling=!1,this.state.activeProfile.peakBytes=Math.max(...this.state.activeProfile.kernels.map(r=>r.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(let r of this.state.activeProfile.kernels)r.kernelTimeMs=await r.kernelTimeMs,r.extraInfo=await r.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,n,r,s,a){let o={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:s},i=dg(e);i!=null&&(r=i.gradFunc),r!=null&&(o.gradient=l=>(l=l.map((u,c)=>{if(u==null){let p=n[c],d=Zf(p.size,p.dtype);return this.makeTensor(d,p.shape,p.dtype)}return u}),r(l.length>1?l:l[0],s,a))),this.state.activeTape.push(o)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){let t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){let t=yy(e),n=new Set(t.map(s=>s.id));for(let s=0;s<this.state.activeScope.track.length;s++){let a=this.state.activeScope.track[s];!a.kept&&!n.has(a.id)&&a.dispose()}let r=this.state.scopeStack.pop();this.state.activeScope=this.state.scopeStack.length===0?null:this.state.scopeStack[this.state.scopeStack.length-1],t.forEach(s=>{!s.kept&&s.scopeId===r.id&&this.track(s)})}gradients(e,t,n,r=!1){if(M(t.length>0,()=>"gradients() received an empty list of xs."),n!=null&&n.dtype!=="float32")throw new Error(`dy must have 'float32' dtype, but has '${n.dtype}'`);let s=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));M(s instanceof rt,()=>"The result y returned by f() must be a tensor.");let a=JR(this.state.activeTape,t,s);if(!r&&a.length===0&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",()=>{let o={};o[s.id]=n==null?c_(s.shape):n,QR(o,a,l=>this.tidy(l),d_);let i=t.map(l=>o[l.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(l=>{for(let u of l.saved)u.dispose()}),this.state.activeTape=null),{value:s,grads:i}})}customGrad(e){return M(Da(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{M(t.every(o=>o instanceof rt),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n,r={};t.forEach((o,i)=>{r[i]=o});let s=(o,i)=>(n=e(...t,i),M(n.value instanceof rt,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),M(Da(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),a=(o,i)=>{let l=n.gradFunc(o,i),u=Array.isArray(l)?l:[l];M(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(...)."),M(u.every(p=>p instanceof rt),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");let c={};return u.forEach((p,d)=>{c[d]=()=>p}),c};return this.runKernelFunc({forwardFunc:s,backwardsFunc:a,inputs:r})}}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=Ld(),n=await this.backend.time(e);return n.wallMs=Ld()-t,n}track(e){return this.state.activeScope!=null&&(e.scopeId=this.state.activeScope.id,this.state.activeScope.track.push(e)),e}get registeredVariables(){return this.state.registeredVariables}reset(){this.pendingBackendInitId++,this.state.dispose(),this.ENV.reset(),this.state=new Mb;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}},Ay=hg;Ay.nextTensorId=0;Ay.nextVariableId=0;function c_(e){let t=py(Tt(e),"float32");return B.makeTensor(t,e,"float32")}function j4(){let e=$4();if(e._tfengine==null){let t=new _4(e);e._tfengine=new Ay(t)}return PR(e._tfengine.ENV),r_(()=>e._tfengine),e._tfengine}var B=j4();function d_(e,t){let n={a:e,b:t};return B.runKernel(ea,n)}var yp={};Le(yp,{isBrowser:()=>q4,isMobile:()=>f_,mockIsMobile:()=>h_});function p_(){return typeof navigator!="undefined"&&navigator!=null}var fg;function h_(e){fg=e}function f_(e){if(fg!==void 0)return fg;if(e||p_()){if(e||(e=navigator),e.product==="ReactNative")return!0;let t=e.userAgent||e.vendor||(typeof window!="undefined"?window.opera:"");if(!t){let n=e;return n.userAgentData&&n.userAgentData.mobile}return/(android|bb\d+|meego).+mobile|avantgo|bada\/|blackberry|blazer|compal|elaine|fennec|hiptop|iemobile|ip(hone|od)|iris|kindle|lge |maemo|midp|mmp|mobile.+firefox|netfront|opera m(ob|in)i|palm( os)?|phone|p(ixi|re)\/|plucker|pocket|psp|series(4|6)0|symbian|treo|up\.(browser|link)|vodafone|wap|windows ce|xda|xiino/i.test(t)||/1207|6310|6590|3gso|4thp|50[1-6]i|770s|802s|a wa|abac|ac(er|oo|s\-)|ai(ko|rn)|al(av|ca|co)|amoi|an(ex|ny|yw)|aptu|ar(ch|go)|as(te|us)|attw|au(di|\-m|r |s )|avan|be(ck|ll|nq)|bi(lb|rd)|bl(ac|az)|br(e|v)w|bumb|bw\-(n|u)|c55\/|capi|ccwa|cdm\-|cell|chtm|cldc|cmd\-|co(mp|nd)|craw|da(it|ll|ng)|dbte|dc\-s|devi|dica|dmob|do(c|p)o|ds(12|\-d)|el(49|ai)|em(l2|ul)|er(ic|k0)|esl8|ez([4-7]0|os|wa|ze)|fetc|fly(\-|_)|g1 u|g560|gene|gf\-5|g\-mo|go(\.w|od)|gr(ad|un)|haie|hcit|hd\-(m|p|t)|hei\-|hi(pt|ta)|hp( i|ip)|hs\-c|ht(c(\-| |_|a|g|p|s|t)|tp)|hu(aw|tc)|i\-(20|go|ma)|i230|iac( |\-|\/)|ibro|idea|ig01|ikom|im1k|inno|ipaq|iris|ja(t|v)a|jbro|jemu|jigs|kddi|keji|kgt( |\/)|klon|kpt |kwc\-|kyo(c|k)|le(no|xi)|lg( g|\/(k|l|u)|50|54|\-[a-w])|libw|lynx|m1\-w|m3ga|m50\/|ma(te|ui|xo)|mc(01|21|ca)|m\-cr|me(rc|ri)|mi(o8|oa|ts)|mmef|mo(01|02|bi|de|do|t(\-| |o|v)|zz)|mt(50|p1|v )|mwbp|mywa|n10[0-2]|n20[2-3]|n30(0|2)|n50(0|2|5)|n7(0(0|1)|10)|ne((c|m)\-|on|tf|wf|wg|wt)|nok(6|i)|nzph|o2im|op(ti|wv)|oran|owg1|p800|pan(a|d|t)|pdxg|pg(13|\-([1-8]|c))|phil|pire|pl(ay|uc)|pn\-2|po(ck|rt|se)|prox|psio|pt\-g|qa\-a|qc(07|12|21|32|60|\-[2-7]|i\-)|qtek|r380|r600|raks|rim9|ro(ve|zo)|s55\/|sa(ge|ma|mm|ms|ny|va)|sc(01|h\-|oo|p\-)|sdk\/|se(c(\-|0|1)|47|mc|nd|ri)|sgh\-|shar|sie(\-|m)|sk\-0|sl(45|id)|sm(al|ar|b3|it|t5)|so(ft|ny)|sp(01|h\-|v\-|v )|sy(01|mb)|t2(18|50)|t6(00|10|18)|ta(gt|lk)|tcl\-|tdg\-|tel(i|m)|tim\-|t\-mo|to(pl|sh)|ts(70|m\-|m3|m5)|tx\-9|up(\.b|g1|si)|utst|v400|v750|veri|vi(rg|te)|vk(40|5[0-3]|\-v)|vm40|voda|vulc|vx(52|53|60|61|70|80|81|83|85|98)|w3c(\-| )|webc|whit|wi(g |nc|nw)|wmlb|wonu|x700|yas\-|your|zeto|zte\-/i.test(t.substr(0,4))}return!1}function q4(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var Hr=Y();Hr.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.")});Hr.registerFlag("IS_BROWSER",()=>q4());Hr.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");Hr.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Hr.registerFlag("PROD",()=>!1);Hr.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Hr.getBool("DEBUG"));Hr.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Hr.registerFlag("IS_TEST",()=>!1);Hr.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);Hr.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);Hr.registerFlag("ENGINE_COMPILE_ONLY",()=>!1);function $s(e,t){let n=e;if(In(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];let r=[];for(;Array.isArray(n)||In(n)&&t!=="string";)r.push(n.length),n=n[0];return Array.isArray(e)&&Y().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&X4(e,r,[]),r}function X4(e,t,n){if(n=n||[],!Array.isArray(e)&&!In(e)){M(t.length===0,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}M(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),M(e.length===t[0],()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);let r=t.slice(1);for(let s=0;s<e.length;++s)X4(e[s],r,n.concat(s))}function zb(e,t,n,r){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 '${n}' passed to '${r}' must be ${e} tensor, but got ${t} tensor`)}}function $(e,t,n,r="numeric"){if(e instanceof rt)return zb(r,e.dtype,t,n),e;let s=Kf(e);if(s!=="string"&&["bool","int32","float32"].indexOf(r)>=0&&(s=r),zb(r,s,t,n),e==null||!In(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string"){let l=e==null?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${l}'`)}let a=$s(e,s);!In(e)&&!Array.isArray(e)&&(e=[e]);let i=s!=="string"?wm(e,s):_i(e,[],!0);return B.makeTensor(i,a,s)}function Wd(e,t,n,r="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map((a,o)=>$(a,`${t}[${o}]`,n,r))}var K4="__op";function V(e){let t=Object.keys(e);if(t.length!==1)throw new Error(`Please provide an object with a single key (operation name) mapping to a function. Got an object with ${t.length} keys.`);let n=t[0],r=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n=n+K4;let s=(...a)=>{B.startScope(n);try{let o=r(...a);return fy(o)&&console.error("Cannot return a Promise inside of tidy."),B.endScope(o),o}catch(o){throw B.endScope(null),o}};return Object.defineProperty(s,"name",{value:n,configurable:!0}),s}function m_(e,t){let n=$(e,"real","complex"),r=$(t,"imag","complex");jn(n.shape,r.shape,`real and imag shapes, ${n.shape} and ${r.shape}, must match in call to tf.complex().`);let s={real:n,imag:r};return B.runKernel(Jd,s)}var Ma=V({complex_:m_});function Ho(e,t,n,r){if(r==null&&(r=Kf(e)),r==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!In(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){hy(t);let s=Tt(t),a=Tt(n);M(s===a,()=>`Based on the provided shape, [${t}], the tensor should have ${s} values but has ${a}`);for(let o=0;o<n.length;++o){let i=n[o],l=o===n.length-1?i!==Tt(t.slice(o)):!0;M(n[o]===t[o]||!l,()=>`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `)}}return!In(e)&&!Array.isArray(e)&&(e=[e]),t=t||n,e=r!=="string"?wm(e,r):_i(e,[],!0),B.makeTensor(e,t,r)}function pt(e,t,n){let r=$s(e,n);return Ho(e,t,r,n)}var mg={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},wf=4;async function g_(e,t){let n=[],r=[],s=Array.isArray(e)?e.map(o=>o.name):Object.keys(e);for(let o=0;o<s.length;++o){let i=s[o],l=Array.isArray(e)?e[o].tensor:e[i];if(l.dtype!=="float32"&&l.dtype!=="int32"&&l.dtype!=="bool"&&l.dtype!=="string"&&l.dtype!=="complex64")throw new Error(`Unsupported dtype in weight '${i}': ${l.dtype}`);let u={name:i,shape:l.shape,dtype:l.dtype};if(l.dtype==="string"){let c=new Promise(async p=>{let d=await l.bytes(),h=d.reduce((g,y)=>g+y.length,0)+wf*d.length,f=new Uint8Array(h),m=0;for(let g=0;g<d.length;g++){let y=d[g],x=new Uint8Array(new Uint32Array([y.length]).buffer);f.set(x,m),m+=wf,f.set(y,m),m+=y.length}p(f)});r.push(c)}else r.push(l.data());t!=null&&(u.group=t),n.push(u)}let a=await Promise.all(r);return{data:y_(a),specs:n}}function Z4(e,t){let n={},r,s=0;for(let a of t){let o=a.name,i=a.dtype,l=a.shape,u=Tt(l),c;if("quantization"in a){let p=a.quantization;if(p.dtype==="uint8"||p.dtype==="uint16"){if(!("min"in p&&"scale"in p))throw new Error(`Weight ${a.name} with quantization ${p.dtype} doesn't have corresponding metadata min and scale.`)}else if(p.dtype==="float16"){if(i!=="float32")throw new Error(`Weight ${a.name} is quantized with ${p.dtype} which only supports weights of type float32 not ${i}.`)}else throw new Error(`Weight ${a.name} has unknown quantization dtype ${p.dtype}. Supported quantization dtypes are: 'uint8', 'uint16', and 'float16'.`);let d=mg[p.dtype],h=e.slice(s,s+u*d),f=p.dtype==="uint8"?new Uint8Array(h):new Uint16Array(h);if(i==="float32")if(p.dtype==="uint8"||p.dtype==="uint16"){c=new Float32Array(f.length);for(let m=0;m<f.length;m++){let g=f[m];c[m]=g*p.scale+p.min}}else if(p.dtype==="float16")r===void 0&&(r=k_()),c=r(f);else throw new Error(`Unsupported quantization type ${p.dtype} for weight type float32.`);else if(i==="int32"){if(p.dtype!=="uint8"&&p.dtype!=="uint16")throw new Error(`Unsupported quantization type ${p.dtype} for weight type int32.`);c=new Int32Array(f.length);for(let m=0;m<f.length;m++){let g=f[m];c[m]=Math.round(g*p.scale+p.min)}}else throw new Error(`Unsupported dtype in weight '${o}': ${i}`);s+=u*d}else if(i==="string"){let p=Tt(a.shape);c=[];for(let d=0;d<p;d++){let h=new Uint32Array(e.slice(s,s+wf))[0];s+=wf;let f=new Uint8Array(e.slice(s,s+h));c.push(f),s+=h}}else{let p=mg[i],d=e.slice(s,s+u*p);if(i==="float32")c=new Float32Array(d);else if(i==="int32")c=new Int32Array(d);else if(i==="bool")c=new Uint8Array(d);else if(i==="complex64"){c=new Float32Array(d);let h=new Float32Array(c.length/2),f=new Float32Array(c.length/2);for(let y=0;y<h.length;y++)h[y]=c[y*2],f[y]=c[y*2+1];let m=pt(h,l,"float32"),g=pt(f,l,"float32");n[o]=Ma(m,g),m.dispose(),g.dispose()}else throw new Error(`Unsupported dtype in weight '${o}': ${i}`);s+=u*p}i!=="complex64"&&(n[o]=pt(c,l,i))}return n}function y_(e){if(e===null)throw new Error(`Invalid input value: ${JSON.stringify(e)}`);let t=0,n=[];e.forEach(a=>{if(t+=a.byteLength,n.push(a.byteLength===a.buffer.byteLength?a:new a.constructor(a)),!(a instanceof Float32Array||a instanceof Int32Array||a instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${a.constructor.name}`)});let r=new Uint8Array(t),s=0;return n.forEach(a=>{r.set(new Uint8Array(a.buffer),s),s+=a.byteLength}),r.buffer}var xy=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function Lb(e){return xy?Buffer.byteLength(e):new Blob([e]).size}function A_(e){if(xy)return Buffer.from(e).toString("base64");let t=new Uint8Array(e),n="";for(let r=0,s=t.length;r<s;r++)n+=String.fromCharCode(t[r]);return btoa(n)}function x_(e){if(xy){let r=Buffer.from(e,"base64");return r.buffer.slice(r.byteOffset,r.byteOffset+r.byteLength)}let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;++r)n.set([t.charCodeAt(r)],r);return n.buffer}function by(e){if(e.length===1)return e[0];let t=0;e.forEach(s=>{t+=s.byteLength});let n=new Uint8Array(t),r=0;return e.forEach(s=>{n.set(new Uint8Array(s),r),r+=s.byteLength}),n.buffer}function Bb(e){let t="/";for(e=e.trim();e.endsWith(t);)e=e.slice(0,e.length-1);let n=e.split(t);return n[n.length-1]}function Y4(e,t){let n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:t};return e.signature!=null&&(n.signature=e.signature),e.userDefinedMetadata!=null&&(n.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(n.modelInitializer=e.modelInitializer),e.trainingConfig!=null&&(n.trainingConfig=e.trainingConfig),n}async function vy(e,t){let n={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};if(e.trainingConfig!=null&&(n.trainingConfig=e.trainingConfig),e.weightsManifest!=null){let[r,s]=await t(e.weightsManifest);n.weightSpecs=r,n.weightData=s}return e.signature!=null&&(n.signature=e.signature),e.userDefinedMetadata!=null&&(n.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(n.modelInitializer=e.modelInitializer),n}function Ap(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:Lb(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:Lb(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function b_(){let e=n=>{let r=n<<13,s=0;for(;(r&8388608)===0;)s-=8388608,r<<=1;return r&=-8388609,s+=947912704,r|s},t=new Uint32Array(2048);t[0]=0;for(let n=1;n<1024;n++)t[n]=e(n);for(let n=1024;n<2048;n++)t[n]=939524096+(n-1024<<13);return t}function v_(){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 w_(){let e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function k_(){let e=b_(),t=v_(),n=w_();return r=>{let s=new ArrayBuffer(4*r.length),a=new Uint32Array(s);for(let o=0;o<r.length;o++){let i=r[o],l=e[n[i>>10]+(i&1023)]+t[i>>10];a[o]=l}return new Float32Array(s)}}var Wt=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Wt.instance==null&&(Wt.instance=new Wt),Wt.instance}static registerSaveRouter(e){Wt.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Wt.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Wt.getHandlers(e,"save")}static getLoadHandlers(e,t){return Wt.getHandlers(e,"load",t)}static getHandlers(e,t,n){let r=[];return(t==="load"?Wt.getInstance().loadRouters:Wt.getInstance().saveRouters).forEach(a=>{let o=a(e,n);o!==null&&r.push(o)}),r}},S_=e=>Wt.registerSaveRouter(e),I_=e=>Wt.registerLoadRouter(e),C_=e=>Wt.getSaveHandlers(e),T_=(e,t)=>Wt.getLoadHandlers(e,t),gg="tensorflowjs",yg=1,Si="models_store",Ea="model_info_store";function J4(){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 Ag(e){let t=e.result;t.createObjectStore(Si,{keyPath:"modelPath"}),t.createObjectStore(Ea,{keyPath:"modelPath"})}var $i=class{constructor(e){if(this.indexedDB=J4(),e==null||!e)throw new Error("For IndexedDB, modelPath must not be null, undefined or empty.");this.modelPath=e}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");return this.databaseAction(this.modelPath,e)}async load(){return this.databaseAction(this.modelPath)}databaseAction(e,t){return new Promise((n,r)=>{let s=this.indexedDB.open(gg,yg);s.onupgradeneeded=()=>Ag(s),s.onsuccess=()=>{let a=s.result;if(t==null){let o=a.transaction(Si,"readonly"),l=o.objectStore(Si).get(this.modelPath);l.onsuccess=()=>{if(l.result==null)return a.close(),r(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));n(l.result.modelArtifacts)},l.onerror=u=>(a.close(),r(l.error)),o.oncomplete=()=>a.close()}else{let o=Ap(t),i=a.transaction(Ea,"readwrite"),l=i.objectStore(Ea),u=l.put({modelPath:this.modelPath,modelArtifactsInfo:o}),c;u.onsuccess=()=>{c=a.transaction(Si,"readwrite");let d=c.objectStore(Si).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:o});d.onsuccess=()=>n({modelArtifactsInfo:o}),d.onerror=h=>{l=i.objectStore(Ea);let f=l.delete(this.modelPath);f.onsuccess=()=>(a.close(),r(d.error)),f.onerror=m=>(a.close(),r(d.error))}},u.onerror=p=>(a.close(),r(u.error)),i.oncomplete=()=>{c==null?a.close():c.oncomplete=()=>a.close()}}},s.onerror=a=>r(s.error)})}};$i.URL_SCHEME="indexeddb://";var Q4=e=>Y().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith($i.URL_SCHEME)?N_(e.slice($i.URL_SCHEME.length)):null;Wt.registerSaveRouter(Q4);Wt.registerLoadRouter(Q4);function N_(e){return new $i(e)}function E_(e){return e.startsWith($i.URL_SCHEME)?e.slice($i.URL_SCHEME.length):e}var R_=class{constructor(){this.indexedDB=J4()}async listModels(){return new Promise((e,t)=>{let n=this.indexedDB.open(gg,yg);n.onupgradeneeded=()=>Ag(n),n.onsuccess=()=>{let r=n.result,s=r.transaction(Ea,"readonly"),o=s.objectStore(Ea).getAll();o.onsuccess=()=>{let i={};for(let l of o.result)i[l.modelPath]=l.modelArtifactsInfo;e(i)},o.onerror=i=>(r.close(),t(o.error)),s.oncomplete=()=>r.close()},n.onerror=r=>t(n.error)})}async removeModel(e){return e=E_(e),new Promise((t,n)=>{let r=this.indexedDB.open(gg,yg);r.onupgradeneeded=()=>Ag(r),r.onsuccess=()=>{let s=r.result,a=s.transaction(Ea,"readwrite"),o=a.objectStore(Ea),i=o.get(e),l;i.onsuccess=()=>{if(i.result==null)return s.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{let u=o.delete(e),c=()=>{l=s.transaction(Si,"readwrite");let d=l.objectStore(Si).delete(e);d.onsuccess=()=>t(i.result.modelArtifactsInfo),d.onerror=h=>n(i.error)};u.onsuccess=c,u.onerror=p=>(c(),s.close(),n(i.error))}},i.onerror=u=>(s.close(),n(i.error)),a.oncomplete=()=>{l==null?s.close():l.oncomplete=()=>s.close()}},r.onerror=s=>n(r.error)})}},Ks="/",mu="tensorflowjs_models",ew="info",__="model_topology",$_="weight_specs",D_="weight_data",P_="model_metadata";function tw(e){return{info:[mu,e,ew].join(Ks),topology:[mu,e,__].join(Ks),weightSpecs:[mu,e,$_].join(Ks),weightData:[mu,e,D_].join(Ks),modelMetadata:[mu,e,P_].join(Ks)}}function nw(e){for(let t of Object.values(e))window.localStorage.removeItem(t)}function F_(e){let t=e.split(Ks);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Ks)}function O_(e){return e.startsWith(Di.URL_SCHEME)?e.slice(Di.URL_SCHEME.length):e}var Di=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=tw(this.modelPath)}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserLocalStorage.save() does not support saving model topology in binary formats yet.");{let t=JSON.stringify(e.modelTopology),n=JSON.stringify(e.weightSpecs),r=Ap(e);try{this.LS.setItem(this.keys.info,JSON.stringify(r)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,A_(e.weightData));let s={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,signature:e.signature!=null?e.signature:void 0,userDefinedMetadata:e.userDefinedMetadata!=null?e.userDefinedMetadata:void 0,modelInitializer:e.modelInitializer!=null?e.modelInitializer:void 0,trainingConfig:e.trainingConfig!=null?e.trainingConfig:void 0};return this.LS.setItem(this.keys.modelMetadata,JSON.stringify(s)),{modelArtifactsInfo:r}}catch(s){throw nw(this.keys),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${r.modelTopologyBytes}, weightSpecsBytes=${r.weightSpecsBytes}, weightDataBytes=${r.weightDataBytes}.`)}}}async load(){let e=JSON.parse(this.LS.getItem(this.keys.info));if(e==null)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if(e.modelTopologyType!=="JSON")throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");let t={},n=JSON.parse(this.LS.getItem(this.keys.topology));if(n==null)throw new Error(`In local storage, the topology of model '${this.modelPath}' is missing.`);t.modelTopology=n;let r=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(r==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=r;let s=this.LS.getItem(this.keys.modelMetadata);if(s!=null){let o=JSON.parse(s);t.format=o.format,t.generatedBy=o.generatedBy,t.convertedBy=o.convertedBy,o.signature!=null&&(t.signature=o.signature),o.userDefinedMetadata!=null&&(t.userDefinedMetadata=o.userDefinedMetadata),o.modelInitializer!=null&&(t.modelInitializer=o.modelInitializer),o.trainingConfig!=null&&(t.trainingConfig=o.trainingConfig)}let a=this.LS.getItem(this.keys.weightData);if(a==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=x_(a),t}};Di.URL_SCHEME="localstorage://";var rw=e=>Y().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Di.URL_SCHEME)?M_(e.slice(Di.URL_SCHEME.length)):null;Wt.registerSaveRouter(rw);Wt.registerLoadRouter(rw);function M_(e){return new Di(e)}var z_=class{constructor(){M(Y().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),M(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let e={},t=mu+Ks,n=Ks+ew;for(let r=0;r<this.LS.length;++r){let s=this.LS.key(r);if(s.startsWith(t)&&s.endsWith(n)){let a=F_(s);e[a]=JSON.parse(this.LS.getItem(s))}}return e}async removeModel(e){e=O_(e);let t=tw(e);if(this.LS.getItem(t.info)==null)throw new Error(`Cannot find model at path '${e}'`);let n=JSON.parse(this.LS.getItem(t.info));return nw(t),n}},Au="://",Nr=class{constructor(){this.managers={}}static getInstance(){return Nr.instance==null&&(Nr.instance=new Nr),Nr.instance}static registerManager(e,t){M(e!=null,()=>"scheme must not be undefined or null."),e.endsWith(Au)&&(e=e.slice(0,e.indexOf(Au))),M(e.length>0,()=>"scheme must not be an empty string.");let n=Nr.getInstance();M(n.managers[e]==null,()=>`A model store manager is already registered for scheme '${e}'.`),n.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 sf(e){if(e.indexOf(Au)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Nr.getSchemes().join(",")}`);return{scheme:e.split(Au)[0],path:e.split(Au)[1]}}async function sw(e,t,n=!1){M(e!==t,()=>`Old path and new path are the same: '${e}'`);let r=Wt.getLoadHandlers(e);M(r.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),M(r.length<2,()=>`Copying failed because more than one (${r.length}) load handlers for source URL ${e}.`);let s=r[0],a=Wt.getSaveHandlers(t);M(a.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),M(a.length<2,()=>`Copying failed because more than one (${r.length}) save handlers for destination URL ${t}.`);let o=a[0],i=sf(e).scheme,l=sf(e).path,u=i===sf(e).scheme,c=await s.load();n&&u&&await Nr.getManager(i).removeModel(l);let p=await o.save(c);return n&&!u&&await Nr.getManager(i).removeModel(l),p.modelArtifactsInfo}async function L_(){let e=Nr.getSchemes(),t={};for(let n of e){let r=await Nr.getManager(n).listModels();for(let s in r){let a=n+Au+s;t[a]=r[s]}}return t}async function B_(e){let t=sf(e);return Nr.getManager(t.scheme).removeModel(t.path)}async function W_(e,t){return sw(e,t,!1)}async function V_(e,t){return sw(e,t,!0)}var U_=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 U_);try{Nr.registerManager(Di.URL_SCHEME,new z_)}catch(e){}try{Nr.registerManager($i.URL_SCHEME,new R_)}catch(e){}}var G_={importFetch:()=>QE()},eg,H_=class{constructor(){this.util=eR(),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return Y().global.fetch!=null?Y().global.fetch(e,t):(eg==null&&(eg=G_.importFetch()),eg(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 H_);function We(e,t="float32",n){return t=t||"float32",hy(e),new on(e,t,n)}function j_(e,t){let n=$(e,"x","cast");if(!C4(t))throw new Error(`Failed to cast to unknown dtype ${t}`);if(t==="string"&&n.dtype!=="string"||t!=="string"&&n.dtype==="string")throw new Error("Only strings can be casted to strings");let r={x:n},s={dtype:t};return B.runKernel(eo,r,s)}var ge=V({cast_:j_});function q_(e){let n={x:$(e,"x","clone","string_or_numeric")};return B.runKernel(go,n)}var Gn=V({clone_:q_});function aw(e,t=!1){console.log(e.toString(t))}j4();var X_={buffer:We,cast:ge,clone:Gn,print:aw};s_(X_);var Cn={};Le(Cn,{browserFiles:()=>t$,browserHTTPRequest:()=>o$,concatenateArrayBuffers:()=>by,copyModel:()=>W_,decodeWeights:()=>Z4,encodeWeights:()=>g_,fromMemory:()=>l$,getLoadHandlers:()=>T_,getModelArtifactsForJSON:()=>vy,getModelArtifactsInfoForJSON:()=>Ap,getSaveHandlers:()=>C_,http:()=>ky,isHTTPScheme:()=>bg,listModels:()=>L_,loadWeights:()=>n$,moveModel:()=>V_,registerLoadRouter:()=>I_,registerSaveRouter:()=>S_,removeModel:()=>B_,weightsLoaderFactory:()=>iw,withSaveHandler:()=>u$});var K_="model",Z_=".json",Y_=".weights.bin";function Wb(e){return new Promise(t=>setTimeout(t)).then(e)}var xg=class{constructor(e){if(!Y().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(xg.URL_SCHEME)&&(e=e.slice(xg.URL_SCHEME.length)),(e==null||e.length===0)&&(e=K_),this.modelJsonFileName=e+Z_,this.weightDataFileName=e+Y_}async save(e){if(typeof document=="undefined")throw new Error("Browser downloads are not supported in this environment since `document` is not present");let t=window.URL.createObjectURL(new Blob([e.weightData],{type:"application/octet-stream"}));if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserDownloads.save() does not support saving model topology in binary formats yet.");{let n=[{paths:["./"+this.weightDataFileName],weights:e.weightSpecs}],r=Y4(e,n),s=window.URL.createObjectURL(new Blob([JSON.stringify(r)],{type:"application/json"})),a=this.modelJsonAnchor==null?document.createElement("a"):this.modelJsonAnchor;if(a.download=this.modelJsonFileName,a.href=s,await Wb(()=>a.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){let o=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;o.download=this.weightDataFileName,o.href=t,await Wb(()=>o.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:Ap(e)}}}},kf=xg;kf.URL_SCHEME="downloads://";var J_=class{constructor(e){if(e==null||e.length<1)throw new Error(`When calling browserFiles, at least 1 file is required, but received ${e}`);this.jsonFile=e[0],this.weightsFiles=e.slice(1)}async load(){return new Promise((e,t)=>{let n=new FileReader;n.onload=r=>{let s=JSON.parse(r.target.result),a=s.modelTopology;if(a==null){t(new Error(`modelTopology field is missing from file ${this.jsonFile.name}`));return}if(s.weightsManifest==null){t(new Error(`weightManifest field is missing from file ${this.jsonFile.name}`));return}if(this.weightsFiles.length===0){e({modelTopology:a});return}let i=vy(s,l=>this.loadWeights(l));e(i)},n.onerror=r=>t(`Failed to read model topology and weights manifest JSON from file '${this.jsonFile.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),n.readAsText(this.jsonFile)})}loadWeights(e){let t=[],n=[];for(let a of e)t.push(...a.weights),n.push(...a.paths);let r=this.checkManifestAndWeightFiles(e),s=n.map(a=>this.loadWeightsFile(a,r[a]));return Promise.all(s).then(a=>[t,by(a)])}loadWeightsFile(e,t){return new Promise((n,r)=>{let s=new FileReader;s.onload=a=>{let o=a.target.result;n(o)},s.onerror=a=>r(`Failed to weights data from file of path '${e}'.`),s.readAsArrayBuffer(t)})}checkManifestAndWeightFiles(e){let t=[],n=this.weightsFiles.map(s=>Bb(s.name)),r={};for(let s of e)s.paths.forEach(a=>{let o=Bb(a);if(t.indexOf(o)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${o}'`);if(t.push(o),n.indexOf(o)===-1)throw new Error(`Weight file with basename '${o}' is not provided.`);r[a]=this.weightsFiles[n.indexOf(o)]});if(t.length!==this.weightsFiles.length)throw new Error(`Mismatch in the number of files in weights manifest (${t.length}) and the number of weight files provided (${this.weightsFiles.length}).`);return r}},Q_=e=>Y().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(kf.URL_SCHEME)?e$(e.slice(kf.URL_SCHEME.length)):null;Wt.registerSaveRouter(Q_);function e$(e="model"){return new kf(e)}function t$(e){return new J_(e)}function Vb(e,t,n,r){o(e),n=n==null?0:n,r=r==null?1:r,i(n,r);let s=0,a=l=>(l.then(u=>{let c=n+ ++s/e.length*(r-n);return t(c),u}),l);function o(l){M(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function i(l,u){M(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),M(u>=0&&u<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${u}`),M(u>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${u}`)}return Promise.all(e.map(a))}async function ow(e,t){t==null&&(t={});let n=t.fetchFunc==null?Y().platform.fetch:t.fetchFunc,r=e.map(p=>n(p,t.requestInit,{isBinary:!0})),s=0,a=.5,i=(t.onProgress==null?await Promise.all(r):await Vb(r,t.onProgress,s,a)).map(p=>p.arrayBuffer()),l=.5,u=1;return t.onProgress==null?await Promise.all(i):await Vb(i,t.onProgress,l,u)}async function n$(e,t="",n,r){return iw(o=>ow(o,{requestInit:r}))(e,t,n)}function iw(e){return async(t,n="",r)=>{let s=t.map(()=>!1),a={},o=r!=null?r.map(()=>!1):[],i=[];if(t.forEach((h,f)=>{let m=0;h.weights.forEach(g=>{let y="quantization"in g?g.quantization.dtype:g.dtype,x=mg[y]*Tt(g.shape),A=()=>{s[f]=!0,a[f]==null&&(a[f]=[]),a[f].push({manifestEntry:g,groupOffset:m,sizeBytes:x})};r!=null?r.forEach((b,v)=>{b===g.name&&(A(),o[v]=!0)}):A(),i.push(g.name),m+=x})}),!o.every(h=>h)){let h=r.filter((f,m)=>!o[m]);throw new Error(`Could not find weights in manifest with names: ${h.join(", ")}.
|
|
Manifest JSON has weights with names: ${i.join(", ")}.`)}let l=s.reduce((h,f,m)=>(f&&h.push(m),h),[]),u=[];l.forEach(h=>{t[h].paths.forEach(f=>{let m=n+(n.endsWith("/")?"":"/")+f;u.push(m)})});let c=await e(u),p={},d=0;return l.forEach(h=>{let f=t[h].paths.length,m=0;for(let b=0;b<f;b++)m+=c[d+b].byteLength;let g=new ArrayBuffer(m),y=new Uint8Array(g),x=0;for(let b=0;b<f;b++){let v=new Uint8Array(c[d+b]);y.set(v,x),x+=v.byteLength}a[h].forEach(b=>{let v=g.slice(b.groupOffset,b.groupOffset+b.sizeBytes),S=Z4(v,[b.manifestEntry]);for(let I in S)p[I]=S[I]}),d+=f}),p}}var r$="application/octet-stream",s$="application/json",wy=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?(M(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,M(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&M(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");let t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;let n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],r=Y4(e,n);t.body.append("model.json",new Blob([JSON.stringify(r)],{type:s$}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:r$}),"model.weights.bin");let s=await this.fetch(this.path,t);if(s.ok)return{modelArtifactsInfo:Ap(e),responses:[s]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${s.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(s){let a=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?a+=" Your path contains a .pb file extension. Support for .pb models have been removed in TensorFlow.js 1.0 in favor of .json models. You can re-convert your Python TensorFlow model using the TensorFlow.js 1.0 conversion scripts or you can convert your.pb models with the 'pb2json'NPM script in the tensorflow/tfjs-converter repository.":a+=" Please make sure the server is serving valid JSON for this request.",new Error(a)}let n=t.modelTopology,r=t.weightsManifest;if(n==null&&r==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);return vy(t,s=>this.loadWeights(s))}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,r]=a$(t),s=this.weightPathPrefix||n,a=[];for(let u of e)a.push(...u.weights);let o=[],i=[];for(let u of e)for(let c of u.paths)this.weightUrlConverter!=null?i.push(this.weightUrlConverter(c)):o.push(s+c+r);this.weightUrlConverter&&o.push(...await Promise.all(i));let l=await ow(o,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[a,by(l)]}};wy.URL_SCHEME_REGEX=/^https?:\/\//;function a$(e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),r=e.substring(0,t),s=n>t?e.substring(n):"";return[r+"/",s]}function bg(e){return e.match(wy.URL_SCHEME_REGEX)!=null}var lw=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(r=>bg(r)):n=bg(e),n)return ky(e,t)}return null};Wt.registerSaveRouter(lw);Wt.registerLoadRouter(lw);function ky(e,t){return new wy(e,t)}function o$(e,t){return ky(e,t)}var tg=class{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}},i$=class{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}};function l$(e,t,n,r){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new tg(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 tg({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 tg({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:r}))}function u$(e){return new i$(e)}var uw={};Le(uw,{confusionMatrix:()=>f$});function c$(e,t,n=!1,r=!1){let s=$(e,"a","matMul"),a=$(t,"b","matMul");[s,a]=Lt(s,a);let o={a:s,b:a},i={transposeA:n,transposeB:r};return B.runKernel(Qa,o,i)}var Ye=V({matMul_:c$});function d$(e,t,n=1,r=0){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);let a={indices:$(e,"indices","oneHot","int32")},o={depth:t,onValue:n,offValue:r};return B.runKernel(dl,a,o)}var Vd=V({oneHot_:d$});function p$(e,t){let n=$(e,"x","transpose");if(t==null&&(t=n.shape.map((a,o)=>o).reverse()),M(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`),t.forEach(a=>{M(a>=0&&a<n.rank,()=>`All entries in 'perm' must be between 0 and ${n.rank-1} but got ${t}`)}),n.rank<=1)return n.clone();let r={x:n},s={perm:t};return B.runKernel(Uo,r,s)}var et=V({transpose_:p$});function h$(e,t,n){let r=$(e,"labels","confusionMatrix"),s=$(t,"predictions","confusionMatrix");M(n==null||n>0&&Number.isInteger(n),()=>`If provided, numClasses must be a positive integer, but got ${n}`),M(r.rank===1,()=>`Expected the rank of labels to be 1, but got ${r.rank}`),M(s.rank===1,()=>`Expected the rank of predictions to be 1, but got ${s.rank}`),M(r.shape[0]===s.shape[0],()=>`Mismatch in the number of examples: ${r.shape[0]} vs. ${s.shape[0]}. Labels and predictions should have the same number of elements.`),M(n>0&&Number.isInteger(n),()=>`numClasses is required to be a positive integer, but got ${n}`);let a=Vd(ge(r,"int32"),n),o=Vd(ge(s,"int32"),n),i=et(a),l=Ye(i,o);return ge(l,"int32")}var f$=V({confusionMatrix_:h$}),El={};Le(El,{assertAndGetBroadcastShape:()=>vt,getBroadcastDims:()=>cw,getReductionAxes:()=>Jt});function cw(e,t){let n=e.length,r=[];for(let s=0;s<n;s++){let a=n-1-s,o=e[a]||1;(t[t.length-1-s]||1)>1&&o===1&&r.unshift(a)}return r}function Jt(e,t){let n=[];for(let r=0;r<t.length;r++){let s=e[e.length-r-1],a=t.length-r-1,o=t[a];(s==null||s===1&&o>1)&&n.unshift(a)}return n}function vt(e,t){let n=[],r=Math.max(e.length,t.length);for(let s=0;s<r;s++){let a=e[e.length-s-1];a==null&&(a=1);let o=t[t.length-s-1];if(o==null&&(o=1),a===1)n.unshift(o);else if(o===1)n.unshift(a);else if(a!==o){let i=`Operands could not be broadcast together with shapes ${e} and ${t}.`;throw Error(i)}else n.unshift(a)}return n}var Mr={};Le(Mr,{fromPixels:()=>v$,fromPixelsAsync:()=>x$,toPixels:()=>b$});function dw(e,t,n){if(Ui(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let r=$s(e,n);if(r.length!==3&&r.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Ho(e,t,r,n)}var mi;function pw(e,t=3){if(t>4)throw new Error("Cannot construct Tensor with more than 4 channels from pixels.");if(e==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let n=!1,r=!1,s=!1,a=!1,o=!1,i=!1;if(e.data instanceof Uint8Array)n=!0;else if(typeof ImageData!="undefined"&&e instanceof ImageData)r=!0;else if(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)s=!0;else if(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement)a=!0;else if(e.getContext!=null)o=!0;else if(typeof ImageBitmap!="undefined"&&e instanceof ImageBitmap)i=!0;else throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${e.constructor.name}`);if(s&&s&&e.readyState<2)throw new Error("The video element has not loaded data yet. Please wait for `loadeddata` event on the <video> element.");if(bf(Md,B.backendName)!=null){let f={pixels:e},m={numChannels:t};return B.runKernel(Md,f,m)}let[u,c]=s?[e.videoWidth,e.videoHeight]:[e.width,e.height],p;if(o)p=e.getContext("2d").getImageData(0,0,u,c).data;else if(r||n)p=e.data;else if(a||s||i){if(mi==null)if(typeof document=="undefined")if(typeof OffscreenCanvas!="undefined"&&typeof OffscreenCanvasRenderingContext2D!="undefined")mi=new OffscreenCanvas(1,1).getContext("2d");else throw new Error("Cannot parse input in current context. Reason: OffscreenCanvas Context2D rendering is not supported.");else mi=document.createElement("canvas").getContext("2d");mi.canvas.width=u,mi.canvas.height=c,mi.drawImage(e,0,0,u,c),p=mi.getImageData(0,0,u,c).data}let d;if(t===4)d=new Int32Array(p);else{let f=u*c;d=new Int32Array(f*t);for(let m=0;m<f;m++)for(let g=0;g<t;++g)d[m*t+g]=p[m*4+g]}return dw(d,[c,u,t],"int32")}function m$(e){return e!=null&&e.data instanceof Uint8Array}function g$(){return typeof window!="undefined"&&typeof ImageBitmap!="undefined"&&window.hasOwnProperty("createImageBitmap")}function y$(e){return e!=null&&e.width!==0&&e.height!==0}function A$(e){return g$()&&!(e instanceof ImageBitmap)&&y$(e)&&!m$(e)}async function x$(e,t=3){let n=null;if(Y().getBool("WRAP_TO_IMAGEBITMAP")&&A$(e)){let r;try{r=await createImageBitmap(e,{premultiplyAlpha:"none"})}catch(s){r=null}r!=null&&r.width===e.width&&r.height===e.height?n=r:n=e}else n=e;return pw(n,t)}async function b$(e,t){let n=$(e,"img","toPixels");if(!(e instanceof rt)){let u=n;n=ge(u,"int32"),u.dispose()}if(n.rank!==2&&n.rank!==3)throw new Error(`toPixels only supports rank 2 or 3 tensors, got rank ${n.rank}.`);let[r,s]=n.shape.slice(0,2),a=n.rank===2?1:n.shape[2];if(a>4||a===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${a}`);if(n.dtype!=="float32"&&n.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${n.dtype}. Please use float32 or int32 tensors.`);let o=await n.data(),i=n.dtype==="float32"?255:1,l=new Uint8ClampedArray(s*r*4);for(let u=0;u<r*s;++u){let c=[0,0,0,255];for(let d=0;d<a;d++){let h=o[u*a+d];if(n.dtype==="float32"){if(h<0||h>1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${h}.`)}else if(n.dtype==="int32"&&(h<0||h>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${h}.`);a===1?(c[0]=h*i,c[1]=h*i,c[2]=h*i):c[d]=h*i}let p=u*4;l[p+0]=Math.round(c[0]),l[p+1]=Math.round(c[1]),l[p+2]=Math.round(c[2]),l[p+3]=Math.round(c[3])}if(t!=null){t.width=s,t.height=r;let u=t.getContext("2d"),c=new ImageData(l,s,r);u.putImageData(c,0,0)}return n!==e&&n.dispose(),l}var v$=V({fromPixels_:pw}),Sy={};Le(Sy,{prepareAndValidate:()=>hw});function hw(e,t){let n=e.shape.length,r=t.shape.length;if(n<1)throw new Error(`tf.gatherND() expects the input to be rank 1 or higher, but the rank was ${n}.`);if(r<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${r}.`);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[r-1]>n)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[r-1]} vs. ${n}`);if(Tt(e.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);let s=t.shape,a=s[s.length-1],o=1;for(let p=0;p<s.length-1;++p)o*=s[p];let i=e.shape,l=s.slice();l.pop();let u=1;for(let p=a;p<n;++p)u*=i[p],l.push(i[p]);let c=[...Mu(e.shape).map(p=>p/u),1].slice(0,a);return[l,o,u,c]}var Iy={};Le(Iy,{calculateShapes:()=>fw,validateInput:()=>Ty,validateUpdateShape:()=>Cy});function Cy(e,t,n){let r=t.rank>1?t.shape[t.rank-1]:1,s=t.rank>1?t.rank-1:1,a=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${r}, and batchDim: ${s}.`;if(n.rank<s)throw new Error(a+` update.rank < ${s}. `);if(e.length<r+(n.rank-s))throw new Error(a+` Output shape length < ${r+(n.rank-s)}`);if(n.rank!==s+e.length-r)throw new Error(a+` update.rank != ${s+e.length-r}`);for(let o=0;o<s;++o)if(n.shape[o]!==t.shape[o])throw new Error(a+` updates.shape[${o}] (${n.shape[o]}) != indices.shape[${o}] (${t.shape[o]}).`);for(let o=0;o<n.rank-s;++o)if(n.shape[o+s]!==e[o+r])throw new Error(a+` updates.shape[${o+s}] (${n.shape[o+s]}) != shape[${o+s}] (${e[o+s]})`)}function Ty(e,t,n){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(n.length<1)throw new Error(`Output rank must be greater or equal to 1, but got shape: ${n}`);if(n.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}`)}Cy(n,t,e)}function fw(e,t,n){let r=t.shape.length,s=r>1?t.shape[r-1]:1,a=n.length,o=1;for(let p=s;p<a;++p)o*=n[p];let i=s<1?1:s,l=Tt(t.shape)/i,u=[...Mu(n.slice(0,s)),1],c=Tt(n);return{sliceRank:s,numUpdates:l,sliceSize:o,strides:u,outputSize:c}}var Mt={};Le(Mt,{assertParamsValid:()=>k$,computeFlatOffset:()=>N$,computeOutShape:()=>I$,getNormalizedAxes:()=>C$,isSliceContinous:()=>T$,maskToAxes:()=>S$,parseSliceParams:()=>kw,sliceInfo:()=>E$,startForAxis:()=>vw,startIndicesWithElidedDims:()=>Aw,stopForAxis:()=>ww,stopIndicesWithElidedDims:()=>xw,stridesForAxis:()=>bw,stridesWithElidedDims:()=>mw});var vg=-2,w$=-1;function k$(e,t,n){let r=e.shape.length;M(r===t.length,()=>`Error in slice${r}D: Length of begin ${t} must match the rank of the array (${r}).`),M(r===n.length,()=>`Error in slice${r}D: Length of size ${n} must match the rank of the array (${r}).`);for(let s=0;s<r;++s)M(t[s]+n[s]<=e.shape[s],()=>`Error in slice${r}D: begin[${s}] + size[${s}] (${t[s]+n[s]}) would overflow input.shape[${s}] (${e.shape[s]})`)}function S$(e){let t=[],n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function I$(e,t,n){let r=[];for(let s=0;s<e.length;s++)r[s]=Math.ceil((t[s]-e[s])/n[s]);return r}function mw(e,t,n,r){let s=[...e];for(let a=s.length;a<r.length;a++)s.push(1);for(let a=0;a<n;a++)a===0?s[t]=1:(s.splice(t,0,1),s.pop());return s}function gw(e,t,n){return n<=e?n:n-(t-1)}function yw(e,t){let n=[];for(let r=0;r<e;r++)n.push(t+r);return n}function C$(e,t,n,r,s,a,o,i,l){let u=e.length,c=new Array(u),p=new Array(u),d=new Array(u);if(t.length&&n>0){let h=t[0],f=n+1;c=Aw(o,h,f,r,e),p=xw(i,h,f,s,e),d=mw(a,h,f,e)}else for(let h=0;h<u;h++)c[h]=vw(o,r,a,e,h,l),p[h]=ww(i,s,a,e,h,l),d[h]=bw(a,h,l);return{begin:c,end:p,strides:d}}function Aw(e,t,n,r,s){let a=[...s],o=yw(n,t);for(let i=0;i<a.length;i++)if(o.indexOf(i)>-1)a[i]=0;else{let l=gw(t,n,i),u=r[l];e&1<<l&&(u=0),a[i]=u}return a}function xw(e,t,n,r,s){let a=[...s],o=yw(n,t);for(let i=0;i<a.length;i++)if(o.indexOf(i)>-1)a[i]=Number.MAX_SAFE_INTEGER;else{let l=gw(t,n,i),u=r[l];e&1<<l&&(u=Number.MAX_SAFE_INTEGER),a[i]=u}for(let i=0;i<a.length;i++){let l=s[i];a[i]<0&&(a[i]+=l),a[i]=Od(0,a[i],s[i])}return a}function bw(e,t,n){let r=e[t];return(n&1<<t||r==null)&&(r=1),r}function vw(e,t,n,r,s,a){let o=t[s],i=n[s]||1;(e&1<<s||a&1<<s||o==null)&&(i>0?o=Number.MIN_SAFE_INTEGER:o=Number.MAX_SAFE_INTEGER);let l=r[s];return o<0&&(o+=l),o=Od(0,o,l-1),o}function ww(e,t,n,r,s,a){let o=t[s],i=n[s]||1;(e&1<<s||a&1<<s||o==null)&&(i>0?o=Number.MAX_SAFE_INTEGER:o=Number.MIN_SAFE_INTEGER);let l=r[s];return o<0&&(o+=l),i>0?o=Od(0,o,l):o=Od(-1,o,l-1),o}function T$(e,t,n){let r=n.length;for(let s=0;s<n.length;s++)if(n[s]>1){r=s;break}for(let s=r+1;s<n.length;s++)if(t[s]>0||n[s]!==e[s])return!1;return!0}function N$(e,t){let n=e.length>0?e[e.length-1]:1;for(let r=0;r<e.length-1;r++)n+=e[r]*t[r];return n}function kw(e,t,n){let r,s=e.shape.length;typeof t=="number"?r=[t,...new Array(s-1).fill(0)]:t.length<s?r=t.concat(new Array(s-t.length).fill(0)):r=t.slice(),r.forEach(o=>{M(o!==-1,()=>"slice() does not support negative begin indexing.")});let a;return n==null?a=new Array(s).fill(-1):typeof n=="number"?a=[n,...new Array(s-1).fill(-1)]:n.length<s?a=n.concat(new Array(s-n.length).fill(-1)):a=n,a=a.map((o,i)=>o>=0?o:(M(o===-1,()=>`Negative size values should be exactly -1 but got ${o} for the slice() size at index ${i}.`),e.shape[i]-r[i])),[r,a]}function E$(e,t,n,r,s,a,o,i,l){let u;if(r==null?(u=new Array(t.length),u.fill(1)):u=r,o!=null&&(o&o-1)!==0)throw new Error("Multiple ellipses in slice is not allowed.");let c=!1,p={dims:u.length,numAddAxisAfterEllipsis:0,begin:t.slice(),end:n.slice(),strides:u.slice(),beginMask:s,endMask:a,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:l};for(let A=0;A<p.dims;A++)c&&(1<<A&i)!==0&&p.numAddAxisAfterEllipsis++,1<<A&o&&(c=!0);c||(p.ellipsisMask|=1<<p.dims,p.dims++);let d={dims:e.length,beginMask:0,endMask:0,beginValid:!1,endValid:!1};R$(p,d);let h=!0,f=!0,m=!0,g=[],y=[];for(let A=0;A<e.length;++A){if(d.strides[A]===0)throw Error(`strides[${A}] must be non-zero`);let b=!!(d.shrinkAxisMask&1<<A),v=e[A];if(v===-1){g.push(b?1:-1);continue}let S=[d.beginMask&1<<A,d.endMask&1<<A],I=[d.strides[A]>0?0:-1,d.strides[A]>0?v:v-1];if(b&&d.strides[A]<=0)throw Error("only stride 1 allowed on non-range indexing.");m=m&&d.strides[A]===1;let E=!!(d.beginMask&1<<A&&d.endMask&1<<A);if(d.beginValid&&d.endValid){if(b){let D=d.begin[A]<0?v+d.begin[A]:d.begin[A];if(d.begin[A]=D,d.end[A]=d.begin[A]+1,D<0||D>=v)throw Error(`slice index ${d.begin[A]} of dimension ${A} out of bounds.`)}else d.begin[A]=Ub(d.begin[A],0,d.strides[A],v,S,I),d.end[A]=Ub(d.end[A],1,d.strides[A],v,S,I);let _=d.strides[A]===1&&d.begin[A]===0&&d.end[A]===v;h=h&&_,f=f&&(A===0&&d.strides[A]===1||_)}else h=h&&d.strides[A]===1&&E,f=f&&(A===0&&d.strides[A]===1||E);let R,P=!1;if(d.beginValid&&d.endValid?(R=d.end[A]-d.begin[A],P=!0):b?(R=1,P=!0):E&&v>=0&&(d.strides[A]<0?R=-v:R=v,P=!0),P){let _;R===0||R<0!=d.strides[A]<0?_=0:_=Math.trunc(R/d.strides[A])+(R%d.strides[A]!==0?1:0),g.push(_)}else g.push(-1)}for(let A=0;A<d.finalShapeGatherIndices.length;++A){let b=d.finalShapeGatherIndices[A];b>=0?y.push(g[b]):b===vg&&y.push(1)}return{finalShapeSparse:y.filter((A,b)=>d.finalShapeGatherIndices[b]!==vg),finalShape:y,isIdentity:h,sliceDim0:f,isSimpleSlice:m,begin:d.begin,end:d.end,strides:d.strides}}function R$(e,t){t.beginMask=0,t.endMask=0,t.shrinkAxisMask=0;let n=0;t.beginValid=e.begin!=null,t.endValid=e.end!=null,t.begin=new Array(t.dims),t.end=new Array(t.dims),t.strides=new Array(t.dims),t.finalShapeGatherIndices=[],t.finalShapeGatherIndicesSparse=[],t.inputShapeGatherIndicesSparse=new Array(t.dims);for(let r=0;r<e.dims;r++)if(1<<r&e.ellipsisMask){let s=Math.min(t.dims-(e.dims-r)+1+e.numAddAxisAfterEllipsis,t.dims);for(;n<s;n++)t.begin[n]=0,t.end[n]=0,t.strides[n]=1,t.beginMask|=1<<n,t.endMask|=1<<n,t.finalShapeGatherIndices.push(n),t.finalShapeGatherIndicesSparse.push(-1),t.inputShapeGatherIndicesSparse[n]=r}else if(1<<r&e.newAxisMask)t.finalShapeGatherIndices.push(vg),t.finalShapeGatherIndicesSparse.push(-1);else{if(n===t.begin.length)throw Error(`Index out of range using input dim ${n}; input has only ${t.dims} dims, ${t.begin.length}.`);e.begin!=null&&(t.begin[n]=e.begin[r]),e.end!=null&&(t.end[n]=e.end[r]),t.strides[n]=e.strides[r],e.beginMask&1<<r&&(t.beginMask|=1<<n),e.endMask&1<<r&&(t.endMask|=1<<n),e.shrinkAxisMask&1<<r?(t.finalShapeGatherIndices.push(w$),t.finalShapeGatherIndicesSparse.push(-1),t.shrinkAxisMask|=1<<n):(t.finalShapeGatherIndices.push(n),t.finalShapeGatherIndicesSparse.push(r)),t.inputShapeGatherIndicesSparse[n]=r,n++}}function Ub(e,t,n,r,s,a){if(s[t])return n>0?a[t]:a[t+1&1];{let o=e<0?r+e:e;return o<a[0]?a[0]:o>a[1]?a[1]:o}}var ce={};Le(ce,{Serializable:()=>Sw,SerializationMap:()=>vi,registerClass:()=>jo});var Sw=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},vi=class{constructor(){this.classNameMap={}}static getMap(){return vi.instance==null&&(vi.instance=new vi),vi.instance}static register(e){vi.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function jo(e){M(e.className!=null,()=>"Class being registered does not have the static className property defined."),M(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),M(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),vi.register(e)}var Iw={};Le(Iw,{TEST_EPSILON_FLOAT16:()=>Cw,encodeStrings:()=>Tw,expectArrayBuffersEqual:()=>M$,expectArraysClose:()=>$$,expectArraysEqual:()=>P$,expectNumbersClose:()=>F$,expectPromiseToFail:()=>D$,expectValuesInRange:()=>O$,testEpsilon:()=>Ny});var _$=.001,Cw=.1;function $$(e,t,n){return n==null&&(n=Ny()),wg(e,t,(r,s)=>Ey(r,s,n))}function Ny(){return B.backend.floatPrecision()===32?_$:Cw}function wg(e,t,n){let r=!0;if((In(e)||In(t))&&(r=!1),In(e)&&In(t)&&(r=!0),r){let o=e.constructor.name,i=t.constructor.name;if(o!==i)throw new Error(`Arrays are of different type. Actual: ${o}. Expected: ${i}`)}if(Array.isArray(e)&&Array.isArray(t)){let o=$s(e),i=$s(t);if(!Ka(o,i))throw new Error(`Arrays have different shapes. Actual: [${o}]. Expected: [${i}]`)}let s=In(e)?e:_i(e),a=In(t)?t:_i(t);if(s.length!==a.length)throw new Error(`Arrays have different lengths actual: ${s.length} vs expected: ${a.length}.
|
|
Actual: ${s}.
|
|
Expected: ${a}.`);for(let o=0;o<a.length;++o){let i=s[o],l=a[o];if(!n(i,l))throw new Error(`Arrays differ: actual[${o}] = ${i}, expected[${o}] = ${l}.
|
|
Actual: ${s}.
|
|
Expected: ${a}.`)}}function D$(e,t){e().then(()=>t.fail(),()=>t())}function P$(e,t){let n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Na(e)||Na(e[0])||Na(t)||Na(t[0])?wg(e,n,(r,s)=>r==s):wg(e,t,(r,s)=>Ey(r,s,0))}function F$(e,t,n){if(n==null&&(n=Ny()),!Ey(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function Ey(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function O$(e,t,n){for(let r=0;r<e.length;r++)if(e[r]<t||e[r]>n)throw new Error(`Value out of range:${e[r]} low: ${t}, high: ${n}`)}function M$(e,t){let n=new Float32Array(e),r=new Float32Array(t);if(n.length!==r.length)throw new Error(`Expected ArrayBuffer to be of length ${r.length}, but it was ${n.length}`);for(let s=0;s<r.length;s++)if(n[s]!==r[s])throw new Error(`Expected ArrayBuffer value at ${s} to be ${r[s]} but got ${n[s]} instead`)}function Tw(e){for(let t=0;t<e.length;t++){let n=e[t];Array.isArray(n)?Tw(n):e[t]=mp(n)}return e}var Ry="0.0.0";function _y(){Y().set("PROD",!0)}function z$(){Y().set("DEBUG",!0)}function L$(){Y().set("DEPRECATION_WARNINGS_ENABLED",!1),console.warn("TensorFlow.js deprecation warnings have been disabled.")}function $y(e){Y().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}a_($y);function B$(){B.disposeVariables()}function sn(){return B}function Sf(){return B.memory()}function W$(e){return B.profile(e)}function K(e,t){return B.tidy(e,t)}function ne(e){yy(e).forEach(n=>n.dispose())}function fn(e){return B.keep(e)}function V$(e){return B.time(e)}function Dy(e){return B.setBackend(e)}function dc(){return B.ready()}function qn(){return B.backendName}function U$(e){B.removeBackend(e)}function Py(e){return B.findBackend(e)}function G$(e){return B.findBackendFactory(e)}function Rl(e,t,n=1){return B.registerBackend(e,t,n)}function zr(){return B.backend}function H$(e,t){Y().setPlatform(e,t)}function j$(e,t){let n=$(e,"a","add"),r=$(t,"b","add");[n,r]=Lt(n,r);let s={a:n,b:r};return B.runKernel(ea,s)}var ue=V({add_:j$});function q$(e,t){let n=$(e,"a","floorDiv"),r=$(t,"b","floorDiv");[n,r]=Lt(n,r);let s={a:n,b:r};return B.runKernel(ho,s)}var xp=V({floorDiv_:q$});function X$(e,t){let n=$(e,"a","div"),r=$(t,"b","div");if([n,r]=Lt(n,r),n.dtype==="int32"&&r.dtype==="int32")return xp(n,r);let s={a:n,b:r},a={};return B.runKernel(lo,s,a)}var de=V({div_:X$});function K$(e,t){let n=$(e,"a","mul"),r=$(t,"b","mul");[n,r]=Lt(n,r);let s={a:n,b:r};return B.runKernel(Co,s)}var L=V({mul_:K$});function Z$(e){let t=$(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return B.runKernel(Qd,n)}else{let n={x:t};return B.runKernel(Gi,n)}}var rn=V({abs_:Z$});function Y$(e){let n={x:$(e,"x","acos")};return B.runKernel(zu,n)}var Nw=V({acos_:Y$});function J$(e){let n={x:$(e,"x","acosh")};return B.runKernel(Lu,n)}var Ew=V({acosh_:J$});function Q$(e){M(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),M(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);let t=e.map((s,a)=>$(s,`tensors${a}`,"addN")),n=t[0];t.forEach(s=>{if(s.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(s=>{if(!Ka(s.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let r=t;return B.runKernel(Za,r)}var km=V({addN_:Q$});function eD(e,t=null,n=!1){let s={x:$(e,"x","all","bool")},a={axis:t,keepDims:n};return B.runKernel(Bu,s,a)}var Fy=V({all_:eD});function tD(e,t=null,n=!1){let s={x:$(e,"x","any","bool")},a={axis:t,keepDims:n};return B.runKernel(Wu,s,a)}var If=V({any_:tD});function nD(e,t=0){let r={x:$(e,"x","argMax")},s={axis:t};return B.runKernel(Ya,r,s)}var Rr=V({argMax_:nD});function rD(e,t=0){let r={x:$(e,"x","argMin")},s={axis:t};return B.runKernel(Vu,r,s)}var Rw=V({argMin_:rD});function sD(e){let n={x:$(e,"x","asin")};return B.runKernel(Uu,n)}var _w=V({asin_:sD});function aD(e){let n={x:$(e,"x","asinh")};return B.runKernel(Gu,n)}var $w=V({asinh_:aD});function oD(e){let n={x:$(e,"x","atan")};return B.runKernel(Hu,n)}var Dw=V({atan_:oD});function iD(e,t){let n=$(e,"a","atan2"),r=$(t,"b","atan2");[n,r]=Lt(n,r);let s={a:n,b:r};return B.runKernel(qu,s)}var Pw=V({atan2_:iD});function lD(e){let n={x:$(e,"x","atanh")};return B.runKernel(ju,n)}var Fw=V({atanh_:lD});function uD(e,t,n,r,s="NHWC",a){let o=e[3],i=[...t,o],l=zw(s);return bp(e,i,n,a,r,null,null,l)}function Ow(e,t,n,r,s,a,o="channelsLast"){let[i,l]=Cf(t),u;if(o==="channelsLast")u=[i,l,e[3],e[3]];else if(o==="channelsFirst")u=[i,l,e[1],e[1]];else throw new Error(`Unknown dataFormat ${o}`);return bp(e,u,n,r,s,a,!1,o)}function cD(e,t,n,r,s,a,o="NDHWC"){let[i,l,u]=kg(t),c,p;if(o==="NDHWC")p="channelsLast",c=[i,l,u,e[4],e[4]];else if(o==="NCDHW")p="channelsFirst",c=[i,l,u,e[1],e[1]];else throw new Error(`Unknown dataFormat ${o}`);return Mw(e,c,n,r,s,!1,p,a)}function bp(e,t,n,r,s,a,o=!1,i="channelsLast"){let[l,u,c,p]=[-1,-1,-1,-1];if(i==="channelsLast")[l,u,c,p]=e;else if(i==="channelsFirst")[l,p,u,c]=e;else throw new Error(`Unknown dataFormat ${i}`);let[d,h,,f]=t,[m,g]=Cf(n),[y,x]=Cf(r),A=xu(d,y),b=xu(h,x),{padInfo:v,outHeight:S,outWidth:I}=hD(s,u,c,m,g,A,b,a,i),E=o?f*p:f,R;return i==="channelsFirst"?R=[l,E,S,I]:i==="channelsLast"&&(R=[l,S,I,E]),{batchSize:l,dataFormat:i,inHeight:u,inWidth:c,inChannels:p,outHeight:S,outWidth:I,outChannels:E,padInfo:v,strideHeight:m,strideWidth:g,filterHeight:d,filterWidth:h,effectiveFilterHeight:A,effectiveFilterWidth:b,dilationHeight:y,dilationWidth:x,inShape:e,outShape:R,filterShape:t}}function Mw(e,t,n,r,s,a=!1,o="channelsLast",i){let[l,u,c,p,d]=[-1,-1,-1,-1,-1];if(o==="channelsLast")[l,u,c,p,d]=e;else if(o==="channelsFirst")[l,d,u,c,p]=e;else throw new Error(`Unknown dataFormat ${o}`);let[h,f,m,,g]=t,[y,x,A]=kg(n),[b,v,S]=kg(r),I=xu(h,b),E=xu(f,v),R=xu(m,S),{padInfo:P,outDepth:_,outHeight:D,outWidth:T}=fD(s,u,c,p,y,x,A,I,E,R,i),F=a?g*d:g,U;return o==="channelsFirst"?U=[l,F,_,D,T]:o==="channelsLast"&&(U=[l,_,D,T,F]),{batchSize:l,dataFormat:o,inDepth:u,inHeight:c,inWidth:p,inChannels:d,outDepth:_,outHeight:D,outWidth:T,outChannels:F,padInfo:P,strideDepth:y,strideHeight:x,strideWidth:A,filterDepth:h,filterHeight:f,filterWidth:m,effectiveFilterDepth:I,effectiveFilterHeight:E,effectiveFilterWidth:R,dilationDepth:b,dilationHeight:v,dilationWidth:S,inShape:e,outShape:U,filterShape:t}}function dD(e,t,n,r,s){r==null&&(r=Oy(e,t,n));let a=e[0],o=e[1],i=Ti((a-t+2*r)/n+1,s),l=Ti((o-t+2*r)/n+1,s);return[i,l]}function pD(e,t,n,r,s,a){s==null&&(s=Oy(e,t,r));let o=e[0],i=e[1],l=e[2],u=Ti((o-t+2*s)/r+1,a),c=Ti((i-t+2*s)/r+1,a),p=Ti((l-t+2*s)/r+1,a);return[u,c,p,n]}function Oy(e,t,n,r=1){let s=xu(t,r);return Math.floor((e[0]*(n-1)-n+s)/2)}function Cf(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function kg(e){return typeof e=="number"?[e,e,e]:e}function xu(e,t){return t<=1?e:e+(e-1)*(t-1)}function hD(e,t,n,r,s,a,o,i,l){let u,c,p;if(typeof e=="number"){u={top:e,bottom:e,left:e,right:e,type:e===0?"VALID":"NUMBER"};let h=dD([t,n],a,r,e,i);c=h[0],p=h[1]}else if(e==="same"){c=Math.ceil(t/r),p=Math.ceil(n/s);let d=Math.max(0,(c-1)*r+a-t),h=Math.max(0,(p-1)*s+o-n),f=Math.floor(d/2),m=d-f,g=Math.floor(h/2),y=h-g;u={top:f,bottom:m,left:g,right:y,type:"SAME"}}else if(e==="valid")u={top:0,bottom:0,left:0,right:0,type:"VALID"},c=Math.ceil((t-a+1)/r),p=Math.ceil((n-o+1)/s);else if(typeof e=="object"){let d=l==="channelsLast"?e[1][0]:e[2][0],h=l==="channelsLast"?e[1][1]:e[2][1],f=l==="channelsLast"?e[2][0]:e[3][0],m=l==="channelsLast"?e[2][1]:e[3][1];u={top:d,bottom:h,left:f,right:m,type:d===0&&h===0&&f===0&&m===0?"VALID":"EXPLICIT"},c=Ti((t-a+d+h)/r+1,i),p=Ti((n-o+f+m)/s+1,i)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:u,outHeight:c,outWidth:p}}function fD(e,t,n,r,s,a,o,i,l,u,c){let p,d,h,f;if(typeof e=="number"){p={top:e,bottom:e,left:e,right:e,front:e,back:e,type:e===0?"VALID":"NUMBER"};let g=pD([t,n,r,1],i,1,s,e,c);d=g[0],h=g[1],f=g[2]}else if(e==="same"){d=Math.ceil(t/s),h=Math.ceil(n/a),f=Math.ceil(r/o);let m=(d-1)*s+i-t,g=(h-1)*a+l-n,y=(f-1)*o+u-r,x=Math.floor(m/2),A=m-x,b=Math.floor(g/2),v=g-b,S=Math.floor(y/2),I=y-S;p={top:b,bottom:v,left:S,right:I,front:x,back:A,type:"SAME"}}else if(e==="valid")p={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},d=Math.ceil((t-i+1)/s),h=Math.ceil((n-l+1)/a),f=Math.ceil((r-u+1)/o);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:p,outDepth:d,outHeight:h,outWidth:f}}function Ti(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 za(e){let[t,n,r]=Cf(e);return t===1&&n===1&&r===1}function Fs(e,t){return za(e)||za(t)}function zw(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function Xn(e,t,n){if(n!=null){if(typeof t=="string")throw Error(`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);if(typeof t=="number")M(wu(t),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${t}.`);else if(typeof t=="object")t.forEach(r=>{r.forEach(s=>{M(wu(s),()=>`Error in ${e}: pad must be an integer when using dimRoundingMode ${n} but got pad ${s}.`)})});else throw Error(`Error in ${e}: Unknown padding parameter: ${t}`)}}function mD(e,t){let r={x:$(e,"x","reshape","string_or_numeric")},s={shape:t};return B.runKernel(hl,r,s)}var H=V({reshape_:mD});function gD(e,t,n,r,s){let a=$(e,"x","avgPool","float32"),o=1;M(Fs(n,o),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`);let i=a,l=!1;a.rank===3&&(l=!0,i=H(a,[1,a.shape[0],a.shape[1],a.shape[2]])),M(i.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${i.rank}.`),Xn("avgPool",r,s);let u={x:i},c={filterSize:t,strides:n,pad:r,dimRoundingMode:s},p=B.runKernel(Ja,u,c);return p=ge(p,a.dtype),l?H(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var Sm=V({avgPool_:gD});function yD(e,t,n,r,s,a="NDHWC"){let o=$(e,"x","avgPool3d","float32"),i=o,l=!1;o.rank===4&&(l=!0,i=H(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),M(i.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${i.rank}.`),M(a==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),Xn("avgPool3d",r,s);let u={x:i},c={filterSize:t,strides:n,pad:r,dimRoundingMode:s,dataFormat:a},p=B.runKernel(Yd,u,c);return p=ge(p,i.dtype),l?H(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var My=V({avgPool3d_:yD});function AD(e,t=0){M(e.length>=1,()=>"Pass at least one tensor to concat");let n=Wd(e,"tensors","concat","string_or_numeric");if(n[0].dtype==="complex64"&&n.forEach(a=>{if(a.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor
|
|
with dtype ${a.dtype}. `)}),n.length===1)return Gn(n[0]);let r=n,s={axis:t};return B.runKernel(ji,r,s)}var St=V({concat_:AD});function xD(e){let n={x:$(e,"x","sigmoid","float32")};return B.runKernel(Oo,n)}var Tn=V({sigmoid_:xD});function bD(e,t,n){let r=$(e,"x","slice","string_or_numeric");if(r.rank===0)throw new Error("Slicing scalar is not possible");let s={x:r},a={begin:t,size:n};return B.runKernel(Al,s,a)}var Pe=V({slice_:bD});function vD(e){let n={x:$(e,"x","tanh","float32")};return B.runKernel(Vo,n)}var Su=V({tanh_:vD});function wD(e,t,n,r,s,a){let o=$(e,"forgetBias","basicLSTMCell"),i=$(t,"lstmKernel","basicLSTMCell"),l=$(n,"lstmBias","basicLSTMCell"),u=$(r,"data","basicLSTMCell"),c=$(s,"c","basicLSTMCell"),p=$(a,"h","basicLSTMCell"),d=St([u,p],1),h=Ye(d,i),f=ue(h,l),m=f.shape[0],g=f.shape[1]/4,y=[m,g],x=Pe(f,[0,0],y),A=Pe(f,[0,g],y),b=Pe(f,[0,g*2],y),v=Pe(f,[0,g*3],y),S=ue(L(Tn(x),Su(A)),L(c,Tn(ue(o,b)))),I=L(Su(S),Tn(v));return[S,I]}var kD=V({basicLSTMCell_:wD});function SD(e,t,n){let r=$(e,"x","batchToSpaceND"),s=t.reduce((i,l)=>i*l);M(r.rank>=1+t.length,()=>`input rank is ${r.rank} but should be > than blockShape.length ${t.length}`),M(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),M(r.shape[0]%s===0,()=>`input tensor batch is ${r.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${s}`);let a={x:r},o={blockShape:t,crops:n};return B.runKernel(Hi,a,o)}var Im=V({batchToSpaceND_:SD});function ID(e){let t;return e.rank===0||e.rank===1?t=H(e,[1,1,1,e.size]):e.rank===2?t=H(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=H(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function CD(e,t,n,r,s,a){a==null&&(a=.001);let o=$(e,"x","batchNorm"),i=$(t,"mean","batchNorm"),l=$(n,"variance","batchNorm"),u;s!=null&&(u=$(s,"scale","batchNorm"));let c;r!=null&&(c=$(r,"offset","batchNorm")),M(i.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),M(c==null||i.rank===c.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),M(u==null||i.rank===u.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let d={x:ID(o),scale:u,offset:c,mean:i,variance:l},h={varianceEpsilon:a},f=B.runKernel(fo,d,h);return H(f,o.shape)}var Iu=V({batchNorm_:CD});function TD(e,t,n,r,s,a){let o=$(e,"x","batchNorm"),i=$(t,"mean","batchNorm"),l=$(n,"variance","batchNorm"),u;s!=null&&(u=$(s,"scale","batchNorm"));let c;return r!=null&&(c=$(r,"offset","batchNorm")),M(o.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${o.rank}.`),M(i.rank===2||i.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${i.rank}.`),M(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),u!=null&&M(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`),c!=null&&M(c.rank===2||c.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${c.rank}.`),Iu(o,i,l,c,u,a)}var Lw=V({batchNorm2d_:TD});function ND(e,t,n,r,s,a){let o=$(e,"x","batchNorm"),i=$(t,"mean","batchNorm"),l=$(n,"variance","batchNorm"),u;s!=null&&(u=$(s,"scale","batchNorm"));let c;return r!=null&&(c=$(r,"offset","batchNorm")),M(o.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${o.rank}.`),M(i.rank===3||i.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${i.rank}.`),M(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),u!=null&&M(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`),c!=null&&M(c.rank===3||c.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${c.rank}.`),Iu(o,i,l,c,u,a)}var Bw=V({batchNorm3d_:ND});function ED(e,t,n,r,s,a){let o=$(e,"x","batchNorm"),i=$(t,"mean","batchNorm"),l=$(n,"variance","batchNorm"),u;s!=null&&(u=$(s,"scale","batchNorm"));let c;return r!=null&&(c=$(r,"offset","batchNorm")),M(o.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${o.rank}.`),M(i.rank===4||i.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${i.rank}.`),M(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),u!=null&&M(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`),c!=null&&M(c.rank===4||c.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${c.rank}.`),Iu(o,i,l,c,u,a)}var Ww=V({batchNorm4d_:ED});function RD(e,t,n){let r=$(e,"x","bincount"),s=$(t,"weights","bincount");M(r.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${r.dtype}`),M(n>=0,()=>`size must be non-negative, but got ${n}.`),M(s.size===r.size||s.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${r.shape}, weights shape: ${s.shape}.`);let a={x:r,weights:s},o={size:n};return B.runKernel(Qf,a,o)}var zy=V({bincount_:RD});function _D(e,t){let n=$(e,"s0","broadcastArgs","int32"),r=$(t,"s1","broadcastArgs","int32");if(n.rank!==1)throw new Error(`broadcastArgs(): first input must be a vector (rank=1). Has rank ${n.rank}`);if(r.rank!==1)throw new Error(`broadcastArgs(): second input must be a vector (rank=1). Has rank ${r.rank}`);let s={s0:n,s1:r};return B.runKernel(em,s)}var Vw=V({broadcastArgs_:_D});function $D(e,t){let n=$(e,"broadcastTo","x"),r=n.shape;if(t.some(u=>!(u>0)||u%1!==0))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.length<n.rank)throw new Error(`broadcastTo(): shape.length=${t.length} < input.rank=${n.rank}.`);if(t.length>n.rank){let u=n.shape.slice();for(;u.length<t.length;)u.unshift(1);n=H(n,u)}let s=n.shape,a=Array.from(t);for(let u=t.length-1;u>=0;u--)if(s[u]===t[u])a[u]=1;else if(n.shape[u]!==1)throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${t}].`);if(a.map((u,c)=>u>1?c:-1).filter(u=>u>=0).length===0)return Gn(n);let i={x:n},l={reps:a};return B.runKernel(na,i,l)}var $d=V({broadcastTo_:$D});function DD(e){let n={x:$(e,"x","ceil","float32")};return B.runKernel(to,n)}var Uw=V({ceil_:DD});function PD(e,t,n){let r=$(e,"x","clipByValue");M(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`);let s={x:r},a={clipValueMin:t,clipValueMax:n};return B.runKernel(ta,s,a)}var yr=V({clipByValue_:PD});function FD(e){return St(e,0)}var Gw=V({concat1d_:FD});function OD(e,t){return St(e,t)}var pc=V({concat2d_:OD});function MD(e,t){return St(e,t)}var Hw=V({concat3d_:MD});function zD(e,t){return St(e,t)}var jw=V({concat4d_:zD});function LD(e,t,n,r,s="NHWC",a=[1,1],o){let i=$(e,"x","conv2d","float32"),l=$(t,"filter","conv2d","float32"),u=i,c=!1;i.rank===3&&(c=!0,u=H(i,[1,i.shape[0],i.shape[1],i.shape[2]])),M(u.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`),M(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),Xn("conv2d",r,o);let p=s==="NHWC"?u.shape[3]:u.shape[1];M(p===l.shape[2],()=>`Error in conv2d: depth of input (${p}) must match input depth for filter ${l.shape[2]}.`),M(Fs(n,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`);let d={x:u,filter:l},h={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:o},f=B.runKernel(no,d,h);return c?H(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var La=V({conv2d_:LD});function BD(e,t,n,r,s="NWC",a=1,o){let i=$(e,"x","conv1d"),l=$(t,"filter","conv1d"),u=i,c=!1;i.rank===2&&(c=!0,u=H(i,[1,i.shape[0],i.shape[1]])),M(u.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${u.rank}.`),M(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),Xn("conv1d",r,o),M(u.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`),M(Fs(n,a),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${a}'`),M(s==="NWC",()=>`Error in conv1d: got dataFormat of ${s} but only NWC is currently supported.`);let p=H(l,[1,l.shape[0],l.shape[1],l.shape[2]]),d=H(u,[u.shape[0],1,u.shape[1],u.shape[2]]),g=La(d,p,[1,n],r,"NHWC",[1,a],o);return c?H(g,[g.shape[2],g.shape[3]]):H(g,[g.shape[0],g.shape[2],g.shape[3]])}var Ly=V({conv1d_:BD});function WD(e,t,n,r,s,a="NHWC",o){M(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let i=e,l=t,u=!1;t.rank===3&&(u=!0,l=H(t,[1,t.shape[0],t.shape[1],t.shape[2]]),i=[1,e[0],e[1],e[2]]),M(i.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${i.length}.`),M(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),M(n.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);let c=a==="NHWC"?i[3]:i[1],p=a==="NHWC"?l.shape[3]:l.shape[1];M(c===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${c}) must match input depth for filter ${n.shape[2]}.`),M(p===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${p}) must match output depth for filter ${n.shape[3]}.`),Xn("conv2dDerInput",s,o);let d={dy:l,filter:n},h={strides:r,pad:s,dataFormat:a,dimRoundingMode:o,inputShape:i},f=B.runKernel(ro,d,h);return u?H(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var By=V({conv2DBackpropInput_:WD});function VD(e,t,n,r,s,a){let o=$(e,"x","conv2dTranspose"),i=$(t,"filter","conv2dTranspose");return By(n,o,i,r,s,"NHWC",a)}var Wy=V({conv2dTranspose_:VD});function UD(e,t,n,r,s="NDHWC",a=[1,1,1]){let o=$(e,"x","conv3d"),i=$(t,"filter","conv3d"),l=o,u=!1;o.rank===4&&(u=!0,l=H(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),M(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),M(i.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${i.rank}.`),M(l.shape[4]===i.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${i.shape[3]}.`),M(Fs(n,a),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),M(s==="NDHWC",()=>`Error in conv3d: got dataFormat of ${s} but only NDHWC is currently supported.`);let c={x:l,filter:i},p={strides:n,pad:r,dataFormat:s,dilations:a},d=B.runKernel(ep,c,p);return u?H(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var Vy=V({conv3d_:UD});function GD(e,t,n,r,s){M(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let a=e,o=t,i=!1;t.rank===4&&(i=!0,o=H(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),a=[1,e[0],e[1],e[2],e[3]]);let l=a[4],u=o.shape[4];M(a.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${a.length}.`),M(o.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${o.rank}`),M(n.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),M(l===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`),M(u===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${u}) must match output depth for filter ${n.shape[4]}.`);let c={dy:o,filter:n},p={pad:s,strides:r,inputShape:a},d=B.runKernel(rm,c,p);return i?H(d,[d.shape[1],d.shape[2],d.shape[3],d.shape[4]]):d}var qw=V({conv3DBackpropInput_:GD});function HD(e,t,n,r,s){let a=$(e,"x","conv3dTranspose"),o=$(t,"filter","conv3dTranspose");return qw(n,a,o,r,s)}var Xw=V({conv3dTranspose_:HD});function jD(e){let n={x:$(e,"x","cos","float32")};return B.runKernel(so,n)}var Cm=V({cos_:jD});function qD(e){let n={x:$(e,"x","cosh","float32")};return B.runKernel(ao,n)}var Uy=V({cosh_:qD});function XD(e,t=0,n=!1,r=!1){let a={x:$(e,"x","cumprod")},o={axis:t,exclusive:n,reverse:r};return B.runKernel(qi,a,o)}var Tf=V({cumprod_:XD});function KD(e,t=0,n=!1,r=!1){let a={x:$(e,"x","cumsum")},o={axis:t,exclusive:n,reverse:r};return B.runKernel(oo,a,o)}var Gy=V({cumsum_:KD});function ZD(e,t,n,r=!1){let s=$(e,"x","denseBincount"),a=$(t,"weights","denseBincount");M(s.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${s.dtype}`),M(s.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${s.rank}.`),M(n>=0,()=>`size must be non-negative, but got ${n}.`),M(a.size===s.size||a.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${s.shape}, weights shape: ${a.shape}.`);let o={x:s,weights:a},i={size:n,binaryOutput:r};return B.runKernel(sm,o,i)}var Kw=V({denseBincount_:ZD});function YD(e,t,n="NHWC"){let r=$(e,"x","depthToSpace","float32"),s=n==="NHWC"?r.shape[1]:r.shape[2],a=n==="NHWC"?r.shape[2]:r.shape[3],o=n==="NHWC"?r.shape[3]:r.shape[1];M(t>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${t}`),M(s*t>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${s} and ${t} for depthToSpace with input shape
|
|
${r.shape}`),M(a*t>=0,()=>`Negative dimension size caused by overflow when multiplying
|
|
${a} and ${t} for depthToSpace with input shape
|
|
${r.shape}`),M(o%(t*t)===0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${o} for depthToSpace with input shape ${r.shape}`);let i={x:r},l={blockSize:t,dataFormat:n};return B.runKernel(Ki,i,l)}var Zw=V({depthToSpace_:YD});function JD(e,t,n,r,s="NHWC",a=[1,1],o){let i=$(e,"x","depthwiseConv2d","float32"),l=$(t,"filter","depthwiseConv2d","float32"),u=i,c=!1;i.rank===3&&(c=!0,u=H(i,[1,i.shape[0],i.shape[1],i.shape[2]])),M(u.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`),M(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),M(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]}.`),Xn("depthwiseConv2d",r,o);let p={x:u,filter:l},d={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:o},h=B.runKernel(io,p,d);return c?H(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var vp=V({depthwiseConv2d_:JD});function QD(e){let n={x:$(e,"x","diag")};return B.runKernel(im,n)}var eP=V({diag_:QD});function tP(e,t,n,r,s=[1,1],a="NHWC"){let o=$(e,"x","dilation2d"),i=$(t,"filter","dilation2d");M(o.rank===3||o.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${o.rank}.`),M(i.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${i.rank}.`),M(a==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${a}`);let l=o,u=!1;o.rank===3&&(l=H(o,[1,o.shape[0],o.shape[1],o.shape[2]]),u=!0);let c={x:l,filter:i},p={strides:n,pad:r,dilations:s},d=B.runKernel(tp,c,p);return u?H(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Yw=V({dilation2d_:tP});function nP(e,t){let n=$(e,"a","equal","string_or_numeric"),r=$(t,"b","equal","string_or_numeric");[n,r]=Lt(n,r),vt(n.shape,r.shape);let s={a:n,b:r};return B.runKernel(Zi,s)}var _r=V({equal_:nP});function rP(e,t,n){let r=$(t,"a","where"),s=$(n,"b","where"),a=$(e,"condition","where","bool"),o=vt(vt(a.shape,r.shape),s.shape),i=$d(a,o),l=$d(r,o),u=$d(s,o),c={condition:i,t:l,e:u};return B.runKernel(yl,c)}var Hn=V({where_:rP});function sP(e){let n={x:$(e,"x","zerosLike")};return B.runKernel(Tl,n)}var st=V({zerosLike_:sP});function aP(e,t){let n=$(e,"a","div"),r=$(t,"b","div");[n,r]=Lt(n,r);let s=de(n,r),a=st(s),o=_r(r,a);return Hn(o,a,s)}var Jw=V({divNoNan_:aP});function oP(e,t){let n=$(e,"t1","dot"),r=$(t,"t2","dot");M((n.rank===1||n.rank===2)&&(r.rank===1||r.rank===2),()=>`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${r.rank}.`);let s=n.rank===1?n.size:n.shape[1],a=r.rank===1?r.size:r.shape[0];if(M(s===a,()=>`Error in dot: inner dimensions of inputs must match, but got ${s} and ${a}.`),n.rank===1&&r.rank===1){let o=H(n,[1,-1]),i=H(r,[-1,1]),l=Ye(o,i);return H(l,[])}else if(n.rank===1&&r.rank===2){let o=H(n,[1,-1]),i=H(r,[r.shape[0],r.shape[1]]),l=Ye(o,i);return H(l,[l.size])}else if(n.rank===2&&r.rank===1){let o=H(r,[-1,1]),i=Ye(n,o);return H(i,[i.size])}else{let o=H(r,[r.shape[0],r.shape[1]]);return Ye(n,o)}}var iP=V({dot_:oP});function lP(e,...t){let n=t.map((s,a)=>$(s,`tensors${a}`,"einsum")),r={equation:e};return B.runKernel(np,n,r)}var Qw=V({einsum_:lP});function uP(e){let n={x:$(e,"x","elu","float32")};return B.runKernel(uo,n)}var wp=V({elu_:uP});function cP(e){let t=$(e,"x","erf");M(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=ge(t,"float32"));let n={x:t};return B.runKernel(Xu,n)}var e7=V({erf_:cP});function dP(e){let n={x:$(e,"x","exp")};return B.runKernel(co,n)}var $r=V({exp_:dP});function pP(e,t=0){let n=$(e,"x","expandDims","string_or_numeric");M(t<=n.rank,()=>"Axis must be <= rank of the tensor");let r={input:n},s={dim:t};return B.runKernel(Yi,r,s)}var Kt=V({expandDims_:pP});function hP(e){let n={x:$(e,"x","expm1")};return B.runKernel(Ji,n)}var t7=V({expm1_:hP});function fP(e,t){let n=$(e,"x","tile","string_or_numeric");M(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`);let r={x:n},s={reps:t};return B.runKernel(na,r,s)}var Gr=V({tile_:fP});function mP(e,t,n,r="float32"){t==null&&(t=e);let s=We([e,t],r),a=e<=t?e:t;for(let i=0;i<a;++i)s.set(1,i,i);let o=H(s.toTensor(),[e,t]);if(n==null)return o;if(n.length===1)return Gr(Kt(o,0),[n[0],1,1]);if(n.length===2)return Gr(Kt(Kt(o,0),0),[n[0],n[1],1,1]);if(n.length===3)return Gr(Kt(Kt(Kt(o,0),0),0),[n[0],n[1],n[2],1,1]);throw new Error(`eye() currently supports only 1D and 2D batchShapes, but received ${n.length}D.`)}var Hy=V({eye_:mP});function hc(e,t,n){let r={shape:e,value:t,dtype:n};return B.runKernel(Ku,{},r)}function gP(e){let n={x:$(e,"x","floor","float32")};return B.runKernel(po,n)}var kp=V({floor_:gP});function yP(e,t,n=0,r=0){let s=$(e,"x","gather"),a=$(t,"indices","gather","int32"),o={x:s,indices:a},i={axis:n,batchDims:r};return B.runKernel(el,o,i)}var Cu=V({gather_:yP});function AP(e,t){let n=$(e,"a","greater","string_or_numeric"),r=$(t,"b","greater","string_or_numeric");[n,r]=Lt(n,r),vt(n.shape,r.shape);let s={a:n,b:r};return B.runKernel(nl,s)}var Ar=V({greater_:AP});function xP(e,t){let n=$(e,"a","greaterEqual","string_or_numeric"),r=$(t,"b","greaterEqual","string_or_numeric");[n,r]=Lt(n,r),vt(n.shape,r.shape);let s={a:n,b:r};return B.runKernel(mo,s)}var _l=V({greaterEqual_:xP});function bP(e){let n={input:$(e,"input","imag")};return B.runKernel(rp,n)}var Tm=V({imag_:bP});function vP(e){let n={x:$(e,"x","isFinite")};return B.runKernel(Zu,n)}var wP=V({isFinite_:vP});function kP(e){let n={x:$(e,"x","isInf")};return B.runKernel(Yu,n)}var SP=V({isInf_:kP});function IP(e){let n={x:$(e,"x","isNaN")};return B.runKernel(Ju,n)}var n7=V({isNaN_:IP});function CP(e,t=.2){let r={x:$(e,"x","leakyRelu")},s={alpha:t};return B.runKernel(yo,r,s)}var Nm=V({leakyRelu_:CP});function TP(e,t){let n=$(e,"a","less","string_or_numeric"),r=$(t,"b","less","string_or_numeric");[n,r]=Lt(n,r),vt(n.shape,r.shape);let s={a:n,b:r};return B.runKernel(rl,s)}var jy=V({less_:TP});function NP(e,t){let n=$(e,"a","lessEqual","string_or_numeric"),r=$(t,"b","lessEqual","string_or_numeric");[n,r]=Lt(n,r),vt(n.shape,r.shape);let s={a:n,b:r};return B.runKernel(sl,s)}var $l=V({lessEqual_:NP});function r7(e,t,n){if(n<=0)throw new Error("The number of values should be positive.");let r={start:e,stop:t,num:n};return B.runKernel(dm,{},r)}function EP(e,t=5,n=1,r=1,s=.5){let a=$(e,"x","localResponseNormalization");M(a.rank===4||a.rank===3,()=>`Error in localResponseNormalization: x must be rank 3 or 4 but got
|
|
rank ${a.rank}.`),M(wu(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let o=a,i=!1;a.rank===3&&(i=!0,o=H(a,[1,a.shape[0],a.shape[1],a.shape[2]]));let l={x:o},u={depthRadius:t,bias:n,alpha:r,beta:s},c=B.runKernel(ap,l,u);return i?H(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var s7=V({localResponseNormalization_:EP});function RP(e){let n={x:$(e,"x","log","float32")};return B.runKernel(Ao,n)}var Dr=V({log_:RP});function _P(e){let n={x:$(e,"x","log1p")};return B.runKernel(Qu,n)}var Em=V({log1p_:_P});function $P(e){return M(Da(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{let r=$(t,"x","tf.grad","string_or_numeric"),s=n!=null?$(n,"dy","tf.grad"):null;return B.tidy(()=>{let{value:a,grads:o}=B.gradients(()=>e(r),[r],s);return s!=null&&jn(a.shape,s.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Rm(o),o[0]})}}function DP(e){return M(Da(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{M(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let r=Wd(t,"args","tf.grads","string_or_numeric"),s=n!=null?$(n,"dy","tf.grads"):null;return B.tidy(()=>{let{value:a,grads:o}=B.gradients(()=>e(...r),r,s);return s!=null&&jn(a.shape,s.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Rm(o),o})}}function PP(e){return M(Da(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{M(t instanceof rt,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),M(n==null||n instanceof rt,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:r,value:s}=B.gradients(()=>e(t),[t],n);return Rm(r),{grad:r[0],value:s}}}function FP(e){return M(Da(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{M(Array.isArray(t)&&t.every(s=>s instanceof rt),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),M(n==null||n instanceof rt,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let r=B.gradients(()=>e(...t),t,n);return n!=null&&jn(r.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Rm(r.grads),r}}function a7(e,t){M(Da(e),()=>"The f passed in variableGrads(f) must be a function"),M(t==null||Array.isArray(t)&&t.every(u=>u instanceof Bd),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let n=t!=null;if(!n){t=[];for(let u in B.registeredVariables)t.push(B.registeredVariables[u])}let r=n?t.filter(u=>!u.trainable):null,s=t.length;t=t.filter(u=>u.trainable),M(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${s} variables is trainable.`);let a=!0,{value:o,grads:i}=B.gradients(e,t,null,a);M(i.some(u=>u!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),M(o.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${o.rank} tensor`);let l={};return t.forEach((u,c)=>{i[c]!=null&&(l[u.name]=i[c])}),r!=null&&r.forEach(u=>l[u.name]=null),{value:o,grads:l}}function Ds(e){return B.customGrad(e)}function Rm(e){if(e.filter(n=>n==null).length>0)throw new Error(`Cannot compute gradient of y=f(x) with respect to x. Make sure that
|
|
the f you passed encloses all operations that lead from x to y.`)}function OP(e){let n={x:$(e,"x","neg")};return B.runKernel(ol,n)}var zt=V({neg_:OP});function MP(e){let n={x:$(e,"x","softplus")};return B.runKernel(lc,n)}var fc=V({softplus_:MP});function zP(e){let t=$(e,"x","logSigmoid");return Ds(r=>({value:zt(fc(zt(r))),gradFunc:o=>L(o,Tn(zt(r)))}))(t)}var LP=V({logSigmoid_:zP});function BP(e,t=null,n=!1){let s={x:$(e,"x","max")},a={reductionIndices:t,keepDims:n};return B.runKernel(xo,s,a)}var gn=V({max_:BP});function WP(e,t){let n=$(e,"a","sub"),r=$(t,"b","sub");[n,r]=Lt(n,r);let s={a:n,b:r};return B.runKernel(Wo,s)}var he=V({sub_:WP});function VP(e,t=null,n=!1){let r=$(e,"x","sum");r.dtype==="bool"&&(r=ge(r,"int32"));let s={x:r},a={axis:t,keepDims:n};return B.runKernel(zo,s,a)}var ke=V({sum_:VP});function UP(e,t=-1){let n=$(e,"logits","logSoftmax");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Log Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and axis was ${t}`);return Ds((s,a)=>{let i=gn(s,t,!0),l=he(s,i),u=he(ge(l,"float32"),Dr(ke($r(l),t,!0)));return a([u]),{value:u,gradFunc:(p,d)=>{let[h]=d,f=!0,m=$r(h);return he(p,L(ke(p,t,f),m))}}})(n)}var qy=V({logSoftmax_:UP});function Xy(e,t){for(let n=0;n<e.length;++n)if(e[e.length-n-1]!==t-1-n)return!1;return!0}function o7(e,t,n){let r=e.length+t.length,s=[],a=0,o=0;for(let i=0;i<r;i++)n.indexOf(i)===-1?s.push(e[a++]):s.push(t[o++]);return s}function i7(e,t){let n=[],r=e.length;for(let a=0;a<r;a++)t.indexOf(a)===-1&&n.push(e[a]);let s=t.map(a=>e[a]);return[n,s]}function Pi(e,t){let n=t.map(r=>1);return o7(e,n,t)}function GP(e,t,n){M(Xy(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function l7(e,t){if(Xy(e,t))return null;let n=[];for(let r=0;r<t;++r)e.indexOf(r)===-1&&n.push(r);return e.forEach(r=>n.push(r)),n}function Ky(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function HP(e,t){let n=[];for(let r=t-e;r<t;++r)n.push(r);return n}function jP(e,t=null,n=!1){let r=$(e,"x","logSumExp"),s=jr(t,r.shape),a=gn(r,s,!0),o=he(r,a),i=$r(o),l=ke(i,s),u=Dr(l),c=ue(H(a,u.shape),u);if(n){let p=Pi(c.shape,s);return H(c,p)}return c}var u7=V({logSumExp_:jP});function qP(e,t){let n=$(e,"a","logicalAnd","bool"),r=$(t,"b","logicalAnd","bool");vt(n.shape,r.shape);let s={a:n,b:r};return B.runKernel(al,s)}var ms=V({logicalAnd_:qP});function XP(e){let n={x:$(e,"x","logicalNot","bool")};return B.runKernel(ec,n)}var _m=V({logicalNot_:XP});function KP(e,t){let n=$(e,"a","logicalOr","bool"),r=$(t,"b","logicalOr","bool");vt(n.shape,r.shape);let s={a:n,b:r};return B.runKernel(sp,s)}var Zy=V({logicalOr_:KP});function ZP(e,t){let n=$(e,"a","logicalXor","bool"),r=$(t,"b","logicalXor","bool");return vt(n.shape,r.shape),ms(Zy(e,t),_m(ms(e,t)))}var YP=V({logicalXor_:ZP});function JP(e,t,n,r,s){let a=$(e,"x","maxPool"),o=1,i=a,l=!1;a.rank===3&&(l=!0,i=H(a,[1,a.shape[0],a.shape[1],a.shape[2]])),M(i.rank===4,()=>`Error in maxPool: input must be rank 4 but got rank ${i.rank}.`),M(Fs(n,o),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${o}'`),Xn("maxPool",r,s);let u={x:i},c={filterSize:t,strides:n,pad:r,dimRoundingMode:s},p=B.runKernel(vo,u,c);return l?H(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var $m=V({maxPool_:JP});function QP(e,t=[1,1,1],n,r,s,a="NDHWC"){let o=$(e,"x","maxPool3d"),i=o,l=!1;o.rank===4&&(l=!0,i=H(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),M(i.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${i.rank}.`),M(a==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${a}`),Xn("maxPool3d",r,s);let u={x:i},c={filterSize:t,strides:n,pad:r,dimRoundingMode:s,dataFormat:a},p=B.runKernel(op,u,c);return l?H(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var Yy=V({maxPool3d_:QP});function eF(e,t,n,r,s=!1){let o={x:$(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:r,includeBatchInIndex:s},l=B.runKernel(mm,o,i);return{result:l[0],indexes:l[1]}}var c7=V({maxPoolWithArgmax_:eF});function tF(e,t){let n=$(e,"a","maximum"),r=$(t,"b","maximum");[n,r]=Lt(n,r),n.dtype==="bool"&&(n=ge(n,"int32"),r=ge(r,"int32")),vt(n.shape,r.shape);let s={a:n,b:r};return B.runKernel(bo,s)}var ra=V({maximum_:tF});function nF(e,t=null,n=!1){let s={x:$(e,"x","mean")},a={axis:t,keepDims:n};return B.runKernel(wo,s,a)}var Vt=V({mean_:nF});function Ft(e,t="float32"){if(t==="complex64"){let r=Ft(e,"float32"),s=Ft(e,"float32");return Ma(r,s)}let n=Zf(Tt(e),t);return B.makeTensor(n,e,t)}function gr(e,t="float32"){if(t==="complex64"){let r=gr(e,"float32"),s=Ft(e,"float32");return Ma(r,s)}let n=py(Tt(e),t);return B.makeTensor(n,e,t)}function rF(e,t,{indexing:n="xy"}={}){if(n!=="xy"&&n!=="ij")throw new TypeError(`${n} is not a valid third argument to meshgrid`);if(e===void 0)return[];let r=$(e,"x","meshgrid",e instanceof rt?e.dtype:"float32");if(t===void 0)return[r];let s=$(t,"y","meshgrid",t instanceof rt?t.dtype:"float32"),a=Tt(r.shape),o=Tt(s.shape);return n==="xy"?(r=H(r,[1,-1]),s=H(s,[-1,1]),[Ye(gr([o,1],r.dtype),r),Ye(s,gr([1,a],s.dtype))]):(r=H(r,[-1,1]),s=H(s,[1,-1]),[Ye(r,gr([1,o],r.dtype)),Ye(gr([a,1],s.dtype),s)])}function sF(e,t=null,n=!1){let s={x:$(e,"x","min")},a={axis:t,keepDims:n};return B.runKernel(ko,s,a)}var Ba=V({min_:sF});function aF(e,t){let n=$(e,"a","minimum"),r=$(t,"b","minimum");[n,r]=Lt(n,r),n.dtype==="bool"&&(n=ge(n,"int32"),r=ge(r,"int32")),vt(n.shape,r.shape);let s={a:n,b:r};return B.runKernel(So,s)}var Sp=V({minimum_:aF});function oF(e,t,n){M(n==="reflect"||n==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);let r=$(e,"x","mirrorPad");if(r.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");M(t.length===r.rank,()=>`Padding doesn't match input. Must be ${r.rank}. Got ${t.length}.`);let s=n==="reflect"?1:0;for(let i=0;i<r.rank;i++)M(t[i].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),M(t[i][0]>=0&&t[i][0]<=r.shape[i]-s&&t[i][1]>=0&&t[i][1]<=r.shape[i]-s,()=>`Padding in dimension ${i} cannot be greater than or equal to ${r.shape[i]-s} or less than 0 for input of shape ${r.shape}`);let a={paddings:t,mode:n},o={x:r};return B.runKernel(Io,o,a)}var d7=V({mirrorPad_:oF});function iF(e,t){let n=$(e,"a","mod"),r=$(t,"b","mod");[n,r]=Lt(n,r);let s={a:n,b:r};return B.runKernel(tc,s)}var mc=V({mod_:iF});function lF(e){let t=$(e,"x","square"),n={};return B.runKernel("Square",{x:t},n)}var xt=V({square_:lF});function uF(e,t=null,n=!1){e=$(e,"x","moments");let r=jr(t,e.shape),s=Vt(e,r,n),a=s.shape;n||(a=Pi(s.shape,r));let o=xt(he(ge(e,"float32"),H(s,a))),i=Vt(o,r,n);return{mean:s,variance:i}}var Dm=V({moments_:uF});function cF(e,t,n,r){let s=$(t,"data","multiRNNCell"),a=Wd(n,"c","multiRNNCell"),o=Wd(r,"h","multiRNNCell"),i=s,l=[];for(let p=0;p<e.length;p++){let d=e[p](i,a[p],o[p]);l.push(d[0]),l.push(d[1]),i=d[1]}let u=[],c=[];for(let p=0;p<l.length;p+=2)u.push(l[p]),c.push(l[p+1]);return[u,c]}var dF=V({multiRNNCell_:cF});function pF(e,t,n,r=!1){let s=$(e,"logits","multinomial"),a=s.size,o=s.rank;if(a<2)throw new Error(`Error in multinomial: you need at least 2 outcomes, but got ${a}.`);if(o>2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${o}`);n=n||Math.random();let l={logits:o===1?H(s,[1,-1]):s},u={numSamples:t,seed:n,normalized:r},c=B.runKernel(gm,l,u);return o===1?H(c,[c.size]):c}var p7=V({multinomial_:pF});function hF(e,t){let n=$(e,"a","notEqual","string_or_numeric"),r=$(t,"b","notEqual","string_or_numeric");[n,r]=Lt(n,r),vt(n.shape,r.shape);let s={a:n,b:r};return B.runKernel(il,s)}var Tu=V({notEqual_:hF});function fF(e){let n={x:$(e,"x","onesLike")};return B.runKernel(cl,n)}var Pr=V({onesLike_:fF});function mF(e,t){let n=$(e,"v1","outerProduct"),r=$(t,"v2","outerProduct");M(n.rank===1&&r.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${r.rank}.`);let s=H(n,[-1,1]),a=H(r,[1,-1]);return Ye(s,a)}var gF=V({outerProduct_:mF});function yF(e,t,n=0){let r=$(e,"x","pad");if(r.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");let s={paddings:t,constantValue:n},a={x:r};return B.runKernel(To,a,s)}var Xr=V({pad_:yF});function AF(e,t,n=0){return M(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),Xr(e,[t],n)}var xF=V({pad1d_:AF});function bF(e,t,n=0){return M(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Xr(e,t,n)}var vF=V({pad2d_:bF});function wF(e,t,n=0){return M(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."),Xr(e,t,n)}var kF=V({pad3d_:wF});function SF(e,t,n=0){return M(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."),Xr(e,t,n)}var IF=V({pad4d_:SF});function CF(e,t,n){let r=$(e,"x","spaceToBatchND");M(r.rank>=1+t.length,()=>`input rank ${r.rank} should be > than [blockShape] ${t.length}`),M(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),M(r.shape.reduce((o,i,l)=>l>0&&l<=t.length?o&&(i+n[l-1][0]+n[l-1][1])%t[l-1]===0:o,!0),()=>`input spatial dimensions ${r.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);let s={x:r},a={blockShape:t,paddings:n};return B.runKernel(bl,s,a)}var Pm=V({spaceToBatchND_:CF});function TF(e,t,n,r,s,a,o){s==null&&(s=[1,1]),a==null&&(a=1),r===0&&(r="valid");let i=$(e,"x","maxPool"),l=i,u=!1;i.rank===3&&(u=!0,l=H(i,[1,i.shape[0],i.shape[1],i.shape[2]])),M(Fs(a,s),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${a} and dilations '${s}'`);let c=Ow(l.shape,t,a,s,r),p=[c.dilationHeight,c.dilationWidth],d;r==="same"?d=EF([c.filterHeight,c.filterWidth],p):d=[[0,0],[0,0]];let h=p[0]===1&&p[1]===1,[f,m]=NF([c.inHeight,c.inWidth],p,d),g=h?r:"valid",y=h?l:Pm(l,p,f),A=(n==="avg"?()=>Sm(y,t,a,g,o):()=>$m(y,t,a,g,o))(),b=h?A:Im(A,p,m);return u?H(b,[b.shape[1],b.shape[2],b.shape[3]]):b}function NF(e,t,n){let r=n.map(c=>c[0]),s=n.map(c=>c[1]),a=e.concat(r,s),o=t.map((c,p)=>(c-a[p]%c)%c),i=s.map((c,p)=>c+o[p]),l=t.map((c,p)=>[r[p],i[p]]),u=t.map((c,p)=>[0,o[p]]);return[l,u]}function EF(e,t){let r=e.map((o,i)=>o+(o-1)*(t[i]-1)).map(o=>o-1),s=r.map(o=>Math.floor(o/2)),a=r.map((o,i)=>o-s[i]);return r.map((o,i)=>[s[i],a[i]])}var RF=V({pool_:TF});function _F(e,t){let n=$(e,"base","pow"),r=$(t,"exp","pow");[n,r]=Lt(n,r);let s={a:n,b:r};return B.runKernel(No,s)}var Wa=V({pow_:_F});function $F(e,t){let n=$(e,"x","prelu"),r=$(t,"alpha","prelu"),s={x:n,alpha:r};return B.runKernel(Eo,s)}var Fm=V({prelu_:$F});function DF(e,t=null,n=!1){let r=$(e,"x","prod");r.dtype==="bool"&&(r=ge(r,"int32"));let s={x:r},a={axis:t,keepDims:n};return B.runKernel(Ro,s,a)}var Jy=V({prod_:DF});function PF(e,t,n){let r=Tt(e),s=null;if(n==null||n==="float32")s=new Float32Array(r);else if(n==="int32")s=new Int32Array(r);else if(n==="bool")s=new Uint8Array(r);else throw new Error(`Unknown data type ${n}`);for(let a=0;a<r;a++)s[a]=t();return B.makeTensor(s,e,n)}var FF=V({rand_:PF}),Qy=Vi(Xf()),eA=class{constructor(e,t,n,r,s){this.mean=e,this.stdDev=t,this.dtype=n,this.nextVal=NaN,this.truncated=r,this.truncated&&(this.upper=this.mean+this.stdDev*2,this.lower=this.mean-this.stdDev*2);let a=s||Math.random();this.random=Qy.alea(a.toString())}nextValue(){if(!isNaN(this.nextVal)){let r=this.nextVal;return this.nextVal=NaN,r}let e,t,n=!1;for(;!n;){let r,s,a;do r=2*this.random()-1,s=2*this.random()-1,a=r*r+s*s;while(a>=1||a===0);let o=Math.sqrt(-2*Math.log(a)/a);e=this.mean+this.stdDev*r*o,t=this.mean+this.stdDev*s*o,(!this.truncated||this.isValidTruncated(e))&&(n=!0)}return(!this.truncated||this.isValidTruncated(t))&&(this.nextVal=this.convertValue(t)),this.convertValue(e)}convertValue(e){return this.dtype==null||this.dtype==="float32"?e:Math.round(e)}isValidTruncated(e){return e<=this.upper&&e>=this.lower}},OF=class{constructor(e,t,n,r){this.alpha=e,this.beta=1/t,this.dtype=n;let s=r||Math.random();this.randu=Qy.alea(s.toString()),this.randn=new eA(0,1,n,!1,this.randu()),e<1?this.d=e+2/3:this.d=e-1/3,this.c=1/Math.sqrt(9*this.d)}nextValue(){let e,t,n,r,s,a;for(;;){do r=this.randn.nextValue(),a=1+this.c*r;while(a<=0);if(a*=a*a,e=r*r,t=1-.331*e*e,n=.5*e+this.d*(1-a+Math.log(a)),s=this.randu(),s<t||Math.log(s)<n)break}return a=1/this.beta*this.d*a,this.alpha<1&&(a*=Math.pow(this.randu(),1/this.alpha)),this.convertValue(a)}convertValue(e){return this.dtype==="float32"?e:Math.round(e)}},MF=class{constructor(e=0,t=1,n,r){if(this.canReturnFloat=()=>this.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=n,r==null&&(r=Math.random()),typeof r=="number"&&(r=r.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=Qy.alea(r)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function zF(e,t,n=1,r="float32",s){if(n==null&&(n=1),r==null&&(r="float32"),r!=="float32"&&r!=="int32")throw new Error(`Unsupported data type ${r}`);let a=new OF(t,n,r,s),o=We(e,r);for(let i=0;i<o.values.length;i++)o.values[i]=a.nextValue();return o.toTensor()}var LF=V({randomGamma_:zF});function BF(e,t=0,n=1,r,s){if(r!=null&&r==="bool")throw new Error(`Unsupported data type ${r}`);let a=new eA(t,n,r,!1,s),o=We(e,r);for(let i=0;i<o.values.length;i++)o.values[i]=a.nextValue();return o.toTensor()}var h7=V({randomNormal_:BF});function WF(e,t=0,n=1,r="float32",s){let a=We(e,r),o=new MF(t,n,null,s);for(let i=0;i<a.values.length;i++)a.values[i]=o.nextValue();return a.toTensor()}var gc=V({randomUniform_:WF});function Nu(e,t,n=1,r="float32"){if(n===0)throw new Error("Cannot have a step of zero");let s={start:e,stop:t,step:n,dtype:r};return B.runKernel(rc,{},s)}function VF(e){let n={input:$(e,"input","real")};return B.runKernel(ip,n)}var Ud=V({real_:VF});function UF(e){let n={x:$(e,"x","reciprocal")};return B.runKernel(sc,n)}var f7=V({reciprocal_:UF});function GF(e){let n={x:$(e,"x","relu")};return B.runKernel(_o,n)}var Os=V({relu_:GF});function HF(e){let n={x:$(e,"x","relu6")};return B.runKernel(Do,n)}var tA=V({relu6_:HF});function jF(e,t){let r={x:$(e,"x","reverse")},s={dims:t};return B.runKernel(fl,r,s)}var Fr=V({reverse_:jF});function qF(e){let t=$(e,"x","reverse");return M(t.rank===1,()=>`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),Fr(t,0)}var XF=V({reverse1d_:qF});function KF(e,t){let n=$(e,"x","reverse");return M(n.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),Fr(n,t)}var ZF=V({reverse2d_:KF});function YF(e,t){let n=$(e,"x","reverse");return M(n.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),Fr(n,t)}var JF=V({reverse3d_:YF});function QF(e,t){let n=$(e,"x","reverse");return M(n.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),Fr(n,t)}var eO=V({reverse4d_:QF});function tO(e){let n={x:$(e,"x","round")};return B.runKernel(ml,n)}var nA=V({round_:tO});function nO(e){let n={x:$(e,"x","rsqrt","float32")};return B.runKernel(Po,n)}var rA=V({rsqrt_:nO});function Ie(e,t){if((In(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"&&In(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Ho(e,[],[],t)}function rO(e){let n={x:$(e,"x","selu")};return B.runKernel(oc,n)}var sA=V({selu_:rO});function sO(e,t,n,r,s,a=[1,1],o="NHWC"){let i=$(e,"x","separableConv2d"),l=$(t,"depthwiseFilter","separableConv2d"),u=$(n,"pointwiseFilter","separableConv2d"),c=i,p=!1;if(i.rank===3&&(p=!0,c=H(i,[1,i.shape[0],i.shape[1],i.shape[2]])),o==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");M(c.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${c.rank}.`),M(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),M(u.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),M(u.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${u.shape[0]}.`),M(u.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${u.shape[1]}.`);let d=l.shape[2],h=l.shape[3];M(u.shape[2]===d*h,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${d*h}, but got ${u.shape[2]}.`);let f=vp(c,l,r,s,o,a),g=La(f,u,1,"valid",o);return p?H(g,[g.shape[1],g.shape[2],g.shape[3]]):g}var m7=V({separableConv2d_:sO});async function aO(e,t){let n=$(e,"x","setdiff1d"),r=$(t,"y","setdiff1d");M(n.dtype===r.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${r.dtype}).`),M(n.rank===1,()=>`x should be 1D tensor, but got x (${n.shape}).`),M(r.rank===1,()=>`y should be 1D tensor, but got y (${r.shape}).`);let s=await n.data(),a=await r.data(),o=new Set(a),i=0;for(let c=0;c<s.length;c++)o.has(s[c])||i++;let l=new on([i],n.dtype),u=new on([i],"int32");for(let c=0,p=0;c<s.length;c++)o.has(s[c])||(l.values[p]=s[c],u.values[p]=c,p++);return[l.toTensor(),u.toTensor()]}var g7=aO;function oO(e){let n={x:$(e,"x","sign")};return B.runKernel(ic,n)}var y7=V({sign_:oO});function iO(e){let n={x:$(e,"x","sin","float32")};return B.runKernel(Fo,n)}var aA=V({sin_:iO});function lO(e){let n={x:$(e,"x","sinh")};return B.runKernel(xl,n)}var oA=V({sinh_:lO});function uO(e,t,n){let r=$(e,"x","slice1d");return M(r.rank===1,()=>`slice1d expects a rank-1 tensor, but got a rank-${r.rank} tensor`),Pe(r,[t],[n])}var Om=V({slice1d_:uO});function cO(e,t,n){let r=$(e,"x","slice2d");return M(r.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${r.rank} tensor`),Pe(r,t,n)}var iA=V({slice2d_:cO});function dO(e,t,n){let r=$(e,"x","slice3d");return M(r.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${r.rank} tensor`),Pe(r,t,n)}var Dl=V({slice3d_:dO});function pO(e,t,n){let r=$(e,"x","slice4d");return M(r.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${r.rank} tensor`),Pe(r,t,n)}var Fi=V({slice4d_:pO});function hO(e,t=-1){let n=$(e,"logits","softmax","float32");if(t===-1&&(t=n.rank-1),t!==n.rank-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${n.rank} and dim was ${t}`);let r={logits:n},s={dim:t};return B.runKernel(Lo,r,s)}var yc=V({softmax_:hO});function fO(e){M(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);let t={input:e};return B.runKernel(um,t)}var Mm=V({fft_:fO});function mO(e){M(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);let t={input:e};return B.runKernel(cm,t)}var Gd=V({ifft_:mO});function gO(e){let t=e.shape[e.shape.length-1],n=e.size/t,r;if(t<=2){let s=H(e,[n,t]);r=Gd(s)}else{let s=[n,2*(t-1)],a=H(Ud(e),[n,t]),o=H(Tm(e),[n,t]),i=Fr(Pe(a,[0,1],[n,t-2]),1),l=L(Fr(Pe(o,[0,1],[n,t-2]),1),Ie(-1)),u=St([a,i],1),c=St([o,l],1),p=H(Ma(u,c),[s[0],s[1]]);r=Gd(p)}if(r=Ud(r),e.rank===3&&e.shape[0]!==0){let s=r,a=e.shape[0];r=H(r,[a,r.shape[0]/a,r.shape[1]]),s.dispose()}return r}var lA=V({irfft_:gO});function yO(e,t,n=0){let s={x:$(e,"x","split")},a={numOrSizeSplits:t,axis:n};return B.runKernel(vl,s,a)}var Yt=V({split_:yO});function AO(e,t){M(e.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let n=e.shape[e.shape.length-1],r=e.size/n,s;if(t!=null&&t<n){let f=e.shape.map(g=>0),m=e.shape.map(g=>g);m[e.shape.length-1]=t,s=Pe(e,f,m),n=t}else if(t!=null&&t>n){let f=e.shape.map(m=>m);f[e.shape.length-1]=t-n,s=St([e,Ft(f)],e.shape.length-1),n=t}else s=e;let a=st(s),o=H(Ma(s,a),[r,n]),i=Mm(o),l=Math.floor(n/2)+1,u=Ud(i),c=Tm(i),p=Yt(u,[l,n-l],u.shape.length-1),d=Yt(c,[l,n-l],c.shape.length-1),h=s.shape.slice();return h[s.shape.length-1]=l,H(Ma(p[0],d[0]),h)}var zm=V({rfft_:AO});function xO(e){let n={x:$(e,"x","sqrt","float32")};return B.runKernel(Mo,n)}var En=V({sqrt_:xO});function bO(e,t){let n=$(e,"a","squaredDifference"),r=$(t,"b","squaredDifference");[n,r]=Lt(n,r),vt(n.shape,r.shape);let s={a:n,b:r},a={};return B.runKernel(Bo,s,a)}var uA=V({squaredDifference_:bO});function vO(e,t){let n=$(e,"x","squeeze");return H(n,w4(n.shape,t).newShape)}var tt=V({squeeze_:vO});function wO(e,t=0){let n=Wd(e,"tensors","stack","string_or_numeric");M(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length>0&&M(t<=n[0].rank,()=>"Axis must be <= rank of the tensor");let r=n,s={axis:t};return B.runKernel(pl,r,s)}var cn=V({stack_:wO});function kO(e,t=0){let r={x:$(e,"x","step")},s={alpha:t};return B.runKernel(Go,r,s)}var Ip=V({step_:kO});function SO(e,t,n,r,s=0,a=0,o=0,i=0,l=0){let c={x:$(e,"x","stridedSlice","string_or_numeric")},p={begin:t,end:n,strides:r,beginMask:s,endMask:a,ellipsisMask:o,newAxisMask:i,shrinkAxisMask:l};return B.runKernel(wl,c,p)}var A7=V({stridedSlice_:SO});function IO(e){let n={x:$(e,"x","tan","float32")};return B.runKernel(kl,n)}var x7=V({tan_:IO});function Ct(e,t){Ui(e);let n=$s(e,t);if(n.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Ho(e,null,n,t)}function ps(e,t,n){if(Ui(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let r=$s(e,n);if(r.length!==2&&r.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Ho(e,t,r,n)}function CO(e,t,n){if(Ui(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let r=$s(e,n);if(r.length!==4&&r.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Ho(e,t,r,n)}function TO(e,t,n){if(Ui(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let r=$s(e,n);if(r.length!==5&&r.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Ho(e,t,r,n)}function NO(e,t,n){if(Ui(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let r=$s(e,n);if(r.length!==6&&r.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(r.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||r,Ho(e,t,r,n)}function EO(e,t=1,n=!0){let r=$(e,"x","topk");if(r.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let s=r.shape[r.shape.length-1];if(t<0)throw new Error(`'k' passed to topk() must be >= 0 but got ${t}`);if(t>s)throw new Error(`'k' passed to topk() must be <= the last dimension (${s}) but got ${t}`);let a={x:r},o={k:t,sorted:n},[i,l]=B.runKernel(Sl,a,o);return{values:i,indices:l}}var b7=V({topk_:EO});function RO(e,t=0,n=1,r,s){if(r!=null&&r==="bool")throw new Error("Unsupported data type $ { dtype }");let a=new eA(t,n,r,!0,s),o=We(e,r);for(let i=0;i<o.values.length;i++)o.values[i]=a.nextValue();return o.toTensor()}var Lm=V({truncatedNormal_:RO});function _O(e,t=0){let n=$(e,"x","unique","string_or_numeric");M(n.rank>0,()=>"The input tensor must be at least 1D");let r={x:n},s={axis:t},[a,o]=B.runKernel(vm,r,s);return{values:a,indices:o}}var Sg=V({unique_:_O});function $O(e,t,n){let r=$(e,"x","unsortedSegmentSum"),s=$(t,"segmentIds","unsortedSegmentSum","int32");M(wu(n),()=>"numSegments must be of dtype int");let a={x:r,segmentIds:s},o={numSegments:n};return B.runKernel(hp,a,o)}var v7=V({unsortedSegmentSum_:$O});function DO(e,t=0){let n=$(e,"x","unstack","string_or_numeric");M(t>=-n.shape.length&&t<n.shape.length,()=>`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`);let r={value:n},s={axis:t};return B.runKernel(Cl,r,s)}var rr=V({unstack_:DO});function w7(e,t=!0,n,r){return B.makeVariable(e,t,n,r)}function k7(e,t){let n=[];for(let a=0;a<t.length;a++)t[a]&&n.push(a);let r=We(e,"int32"),s=We([n.length,e.length],"int32");for(let a=0;a<n.length;a++){let o=r.indexToLoc(n[a]),i=a*e.length;s.values.set(o,i)}return s.toTensor()}async function PO(e){let t=$(e,"condition","whereAsync","bool"),n=await t.data(),r=k7(t.shape,n);return e!==t&&t.dispose(),r}var cA=PO;async function FO(e,t,n){let r=$(e,"tensor","boolMask"),s=$(t,"mask","boolMask","bool"),a=n==null?0:n,o=s.rank,i=r.shape;M(o>0,()=>"mask cannot be scalar"),jn(i.slice(a,a+o),s.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let m=a;m<a+o;m++)l*=i[m];let u=i.slice(0,a).concat([l],i.slice(a+o)),c=H(r,u),p=H(s,[-1]),d=await cA(p),h=tt(d,[1]),f=Cu(c,h,a);return e!==r&&r.dispose(),t!==s&&s.dispose(),h.dispose(),c.dispose(),p.dispose(),d.dispose(),f}var OO=FO;function MO(e,t="euclidean",n=null,r=!1){e=$(e,"x","norm");let s=S7(e,t,n),a=s.shape;if(r){let o=jr(n,e.shape);a=Pi(s.shape,o)}return H(s,a)}function S7(e,t,n=null){if(e.rank===0)return rn(e);if(e.rank!==1&&n===null)return S7(H(e,[-1]),t,n);if(e.rank===1||typeof n=="number"||Array.isArray(n)&&n.length===1){if(t===1)return ke(rn(e),n);if(t===1/0)return gn(rn(e),n);if(t===-1/0)return Ba(rn(e),n);if(t==="euclidean"||t===2)return En(ke(Wa(rn(e),Ie(2,"int32")),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}if(Array.isArray(n)&&n.length===2){if(t===1)return gn(ke(rn(e),n[0]),n[1]-1);if(t===1/0)return gn(ke(rn(e),n[1]),n[0]);if(t===-1/0)return Ba(ke(rn(e),n[1]),n[0]);if(t==="fro"||t==="euclidean")return En(ke(xt(e),n));throw new Error(`Error in norm: invalid ord value: ${t}`)}throw new Error(`Error in norm: invalid axis: ${n}`)}var dA=V({norm_:MO});function zO(e,t,n,r,s=!0){let a=$(e,"v","movingAverage"),o=$(t,"x","movingAverage"),i=$(n,"decay","movingAverage");G4(a,o),M(Ka(a.shape,o.shape),()=>"Shape mismatch in v and x");let l=Ie(1),u=he(l,i),c=L(he(o,a),u);if(s){M(r!=null,()=>"When using zeroDebias: true, step is required.");let p=$(r,"step","movingAverage");c=de(c,he(l,Wa(i,p)))}return ue(a,c)}var LO=V({movingAverage_:zO});function BO(e,t,n){let r=$(e,"indices","scatterND","int32"),s=$(t,"updates","scatterND");Ty(s,r,n);let a={indices:r,updates:s},o={shape:n};return B.runKernel(gl,a,o)}var I7=V({scatterND_:BO});function WO(e,t,n,r){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 s=e.rank>0?e.shape[0]:1,a=e.rank>1?e.shape[1]:1;if(n.length!==a)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${a}.`);let o=t.size;if(!(t.rank===0||t.rank===1&&o===s))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${s}]`);if(t.dtype!==r.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function VO(e,t,n,r=0){let s=$(e,"sparseIndices","sparseToDense","int32"),a=$(t,"sparseValues","sparseToDense"),o=$(r,"defaultValue","sparseToDense",a.dtype);WO(s,a,n,o);let i={sparseIndices:s,sparseValues:a,defaultValue:o},l={outputShape:n};return B.runKernel(dp,i,l)}var pA=V({sparseToDense_:VO});function UO(e,t){let n=$(t,"indices","gatherND","int32"),s={params:$(e,"x","gatherND","string_or_numeric"),indices:n};return B.runKernel(tl,s)}var C7=V({gatherND_:UO});function GO(e,t){if(t==null)return e.shape.slice();if(Ka(e.shape,t))return t;if(e.shape.length===t.length){let n=[];for(let r=0;r<e.shape.length;r++)t[r]==null&&e.shape[r]!=null?n.push(e.shape[r]):n.push(t[r]);return n}return t}function HO(e,t,n,r){let s=$(e,"x","dropout");if(M(s.dtype==="float32",()=>`x has to be a floating point tensor since it's going to be scaled, but got a ${s.dtype} tensor instead.`),M(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof rt?s.clone():s;let a=GO(s,n),o=1-t,i=de(kp(ue(gc(a,0,1,"float32",r),o)),o);return L(s,i)}var T7=V({dropout_:HO});function N7(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function hA(e,t,n){let r=1-e%2,s=new Float32Array(e);for(let a=0;a<e;++a){let o=2*Math.PI*a/(e+r-1);s[a]=t-n*Math.cos(o)}return Ct(s,"float32")}async function jO(e,t,n=1){let r=$(e,"predictions","inTopK"),s=$(t,"targets","inTopK");M(r.rank>1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${r.rank}`),M(r.rank-1===s.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${r.rank} and targets rank ${s.rank}`),jn(r.shape.slice(0,r.shape.length-1),s.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");let a=r.shape[r.shape.length-1];M(n>0&&n<=a,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${a}), but got ${n}`);let o=await r.data(),i=await s.data(),[l,u]=[o.length/a,a],c=k4("bool",l);for(let p=0;p<l;p++){let d=p*u,h=o.subarray(d,d+u),f=[];for(let m=0;m<h.length;m++)f.push({value:h[m],index:m});f.sort((m,g)=>g.value-m.value),c[p]=0;for(let m=0;m<n;m++)if(f[m].index===i[p]){c[p]=1;break}}return e!==r&&r.dispose(),t!==s&&s.dispose(),pt(c,s.shape,"bool")}var qO=jO,Va={};Le(Va,{conv2d:()=>ZO,depthwiseConv2d:()=>eM,matMul:()=>nM});function XO(e,t,n,r,s,a="NHWC",o){let i=e;e.rank===3&&(i=H(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=H(t,[1,t.shape[0],t.shape[1],t.shape[2]])),M(i.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${i.shape}.`),M(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),M(n.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);let u=a==="NHWC"?i.shape[3]:i.shape[1],c=a==="NHWC"?l.shape[3]:l.shape[1];M(u===n[2],()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${n[2]}.`),M(c===n[3],()=>`Error in conv2dDerFilter: depth of dy (${c}) must match output depth for filter (${n[3]}).`),Xn("conv2dDerFilter",s,o);let p={x:i,dy:l},d={strides:r,pad:s,dataFormat:a,dimRoundingMode:o,filterShape:n};return B.runKernel(tm,p,d)}var fA=V({conv2DBackpropFilter_:XO});function Bm(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return L(e,Ip(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function Wm(e,t){let n=t,r=Jt(e.shape,t.shape);return r.length>0&&(n=ke(n,r)),H(n,e.shape)}function Vm(e,t,n,r){if(t==="linear")return e;if(t==="relu")return Os(e);if(t==="elu")return wp(e);if(t==="relu6")return tA(e);if(t==="prelu")return Fm(e,n);if(t==="leakyrelu")return Nm(e,r);if(t==="sigmoid")return Tn(e);throw new Error(`Unknown fused activation ${t}.`)}var Um=(e,t)=>!(e>0)||t==="linear";function KO({x:e,filter:t,strides:n,pad:r,dataFormat:s="NHWC",dilations:a=[1,1],dimRoundingMode:o,bias:i,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:c}){if(l=l||"linear",Um(B.state.gradientDepth,l)===!1){let v=La(e,t,n,r,s,a,o);return i!=null&&(v=ue(v,i)),Vm(v,l,u,c)}let p=$(e,"x","conv2d","float32"),d=$(t,"filter","conv2d","float32"),h=p,f=!1;p.rank===3&&(f=!0,h=H(p,[1,p.shape[0],p.shape[1],p.shape[2]])),M(h.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${h.rank}.`),M(d.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${d.rank}.`),Xn("fused conv2d",r,o),M(h.shape[3]===d.shape[2],()=>`Error in conv2d: depth of input (${h.shape[3]}) must match input depth for filter ${d.shape[2]}.`),M(Fs(n,a),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),M(s==="NHWC",()=>`Error in conv2d: got dataFormat of ${s} but only NHWC is currently supported.`);let m=bp(h.shape,d.shape,n,a,r,o),g;i!=null&&(g=$(i,"bias","fused conv2d"),[g]=Lt(g,p),vt(m.outShape,g.shape));let y;u!=null&&(y=$(u,"prelu weights","fused conv2d"));let x=(v,S)=>{let[I,E,R,P]=S,_=Bm(v,R,l);M(za(a),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`);let D=By(E.shape,_,I,n,r),T=fA(E,_,I.shape,n,r),F=[D,T];if(P!=null){let U=Wm(P,_);F.push(U)}return F},A={x:h,filter:d,bias:g,preluActivationWeights:y},b={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:o,activation:l,leakyreluAlpha:c};return i==null?Ds((S,I,E)=>{let R=B.runKernel(Fa,A,b);return E([I,S,R]),f&&(R=H(R,[R.shape[1],R.shape[2],R.shape[3]])),{value:R,gradFunc:x}})(h,d):Ds((S,I,E,R)=>{let P=B.runKernel(Fa,A,b);return R([I,S,P,E]),f&&(P=H(P,[P.shape[1],P.shape[2],P.shape[3]])),{value:P,gradFunc:x}})(h,d,g)}var ZO=V({fusedConv2d_:KO});function YO(e,t,n,r,s,a=[1,1],o){let i=e;e.rank===3&&(i=H(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=H(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let u={x:i,dy:l},c={strides:r,pad:s,dimRoundingMode:o,dilations:a,filterShape:n};return B.runKernel(am,u,c)}var E7=V({depthwiseConv2dNativeBackpropFilter_:YO});function JO(e,t,n,r,s,a=[1,1],o){let i=t,l=!1;t.rank===3&&(l=!0,i=H(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let u={dy:i,filter:n},c={strides:r,pad:s,dimRoundingMode:o,dilations:a,inputShape:e},p=B.runKernel(om,u,c);return l?H(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var R7=V({depthwiseConv2dNativeBackpropInput_:JO});function QO({x:e,filter:t,strides:n,pad:r,dataFormat:s="NHWC",dilations:a=[1,1],dimRoundingMode:o,bias:i,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:c}){if(Um(B.state.gradientDepth,l)===!1){let v=vp(e,t,n,r,s,a,o);return i!=null&&(v=ue(v,i)),Vm(v,l,u,c)}let p=$(e,"x","depthwiseConv2d","float32"),d=$(t,"filter","depthwiseConv2d","float32"),h=p,f=!1;p.rank===3&&(f=!0,h=H(p,[1,p.shape[0],p.shape[1],p.shape[2]])),M(h.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${h.rank}.`),M(d.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${d.rank}.`),M(h.shape[3]===d.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${h.shape[3]}) must match the inChannels dimension in filter ${d.shape[2]}.`),a==null&&(a=[1,1]),M(Fs(n,a),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${a}'`),Xn("fused depthwiseConv2d",r,o);let m=bp(h.shape,d.shape,n,a,r,o,!0),g;i!=null&&(g=$(i,"bias","fused conv2d"),[g]=Lt(g,p),vt(m.outShape,g.shape));let y;u!=null&&(y=$(u,"prelu weights","fused depthwiseConv2d"));let x=(v,S)=>{M(za(a),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${a}'`);let[I,E,R,P]=S,_=Bm(v,R,l),D=R7(E.shape,_,I,n,r,a,o),T=E7(E,_,I.shape,n,r,a,o);if(P!=null){let F=Wm(g,_);return[D,T,F]}return[D,T]},A={x:h,filter:d,bias:g,preluActivationWeights:y},b={strides:n,pad:r,dataFormat:s,dilations:a,dimRoundingMode:o,activation:l,leakyreluAlpha:c};return i==null?Ds((S,I,E)=>{let R=B.runKernel(Oa,A,b);return E([I,S,R]),f&&(R=H(R,[R.shape[1],R.shape[2],R.shape[3]])),{value:R,gradFunc:x}})(h,d):Ds((S,I,E,R)=>{let P=B.runKernel(Oa,A,b);return R([I,S,P,E]),f&&(P=H(P,[P.shape[1],P.shape[2],P.shape[3]])),{value:P,gradFunc:x}})(h,d,g)}var eM=V({fusedDepthwiseConv2d_:QO});function tM({a:e,b:t,transposeA:n=!1,transposeB:r=!1,bias:s,activation:a="linear",preluActivationWeights:o,leakyreluAlpha:i}){if(Um(B.state.gradientDepth,a)===!1){let _=Ye(e,t,n,r);return s!=null&&(_=ue(_,s)),Vm(_,a,o,i)}let l=$(e,"a","fused matMul"),u=$(t,"b","fused matMul");[l,u]=Lt(l,u);let c=n?l.shape[l.rank-2]:l.shape[l.rank-1],p=r?u.shape[u.rank-1]:u.shape[u.rank-2],d=n?l.shape[l.rank-1]:l.shape[l.rank-2],h=r?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);M(c===p,()=>`Error in fused matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${l.shape} and ${u.shape} and transposeA=${n} and transposeB=${r} must match.`);let A=vt(l.shape.slice(0,-2),u.shape.slice(0,-2)).concat([d,h]),b=n?H(l,[g,c,d]):H(l,[g,d,c]),v=r?H(u,[y,h,p]):H(u,[y,p,h]),S;s!=null&&(S=$(s,"bias","fused matMul"),[S]=Lt(S,l),vt(A,S.shape));let I;o!=null&&(I=$(o,"prelu weights","fused matMul"));let E=(_,D)=>{let[T,F,U,X]=D,z=Bm(H(_,U.shape),U,a),Z,W;if(!n&&!r?(Z=Ye(z,F,!1,!0),W=Ye(T,z,!0,!1)):!n&&r?(Z=Ye(z,F,!1,!1),W=Ye(z,T,!0,!1)):n&&!r?(Z=Ye(F,z,!1,!0),W=Ye(T,z,!1,!1)):(Z=Ye(F,z,!0,!0),W=Ye(z,T,!0,!0)),s!=null){let ee=Wm(X,z);return[Z,W,ee]}else return[Z,W]},R={a:b,b:v,bias:S,preluActivationWeights:I},P={transposeA:n,transposeB:r,activation:a,leakyreluAlpha:i};return s==null?Ds((D,T,F)=>{let U=B.runKernel(Pa,R,P);return F([D,T,U]),{value:H(U,A),gradFunc:E}})(b,v):Ds((D,T,F,U)=>{let X=B.runKernel(Pa,R,P);return U([D,T,X,F]),{value:H(X,A),gradFunc:E}})(b,v,S)}var nM=V({fusedMatMul_:tM});function rM(e){return hA(e,.54,.46)}var sM=V({hammingWindow_:rM});function aM(e){return hA(e,.5,.5)}var _7=V({hannWindow_:aM});function oM(e,t,n,r=!1,s=0){let a=0,o=[];for(;a+t<=e.size;)o.push(Pe(e,a,t)),a+=n;if(r)for(;a<e.size;){let i=a+t-e.size,l=St([Pe(e,a,t-i),hc([i],s)]);o.push(l),a+=n}return o.length===0?ps([],[0,t]):H(St(o),[o.length,t])}var $7=V({frame_:oM});function iM(e,t,n,r,s=_7){r==null&&(r=N7(t));let a=$7(e,t,n),o=L(a,s(t));return zm(o,r)}var lM=V({stft_:iM});function uM(e,t,n,r,s="bilinear",a=0){let o=$(e,"image","cropAndResize"),i=$(t,"boxes","cropAndResize","float32"),l=$(n,"boxInd","cropAndResize","int32"),u=i.shape[0];M(o.rank===4,()=>`Error in cropAndResize: image must be rank 4,but got rank ${o.rank}.`),M(i.rank===2&&i.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${u},4] but had shape ${i.shape}.`),M(l.rank===1&&l.shape[0]===u,()=>`Error in cropAndResize: boxInd must be have size [${u}] but had shape ${i.shape}.`),M(r.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${r.length}.`),M(r[0]>=1&&r[1]>=1,()=>`cropSize must be atleast [1,1], but was ${r}`),M(s==="bilinear"||s==="nearest",()=>`method must be bilinear or nearest, but was ${s}`);let c={image:o,boxes:i,boxInd:l},p={method:s,extrapolationValue:a,cropSize:r};return B.runKernel(Xi,c,p)}var cM=V({cropAndResize_:uM});function dM(e){let t=$(e,"image","flipLeftRight","float32");M(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);let n={image:t};return B.runKernel(Qi,n,{})}var pM=V({flipLeftRight_:dM});function hM(e){let t=$(e,"image","grayscaleToRGB"),n=t.rank-1,r=t.shape[n];M(t.rank>=2,()=>`Error in grayscaleToRGB: images must be at least rank 2, but got rank ${t.rank}.`),M(r===1,()=>`Error in grayscaleToRGB: last dimension of a grayscale image should be size 1, but got size ${r}.`);let s=new Array(t.rank);return s.fill(1,0,n),s[n]=3,Gr(t,s)}var fM=V({grayscaleToRGB_:hM});function mM(e,t,n=0,r=.5){let s=$(e,"image","rotateWithOffset","float32");M(s.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${s.rank}.`);let a={image:s},o={radians:t,fillValue:n,center:r};return B.runKernel(Nl,a,o)}var gM=V({rotateWithOffset_:mM});function Ac(e,t,n,r,s,a){r==null&&(r=.5),s==null&&(s=Number.NEGATIVE_INFINITY),a==null&&(a=0);let o=e.shape[0];return n=Math.min(n,o),M(0<=r&&r<=1,()=>`iouThreshold must be in [0, 1], but was '${r}'`),M(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),M(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),M(t.rank===1,()=>"scores must be a 1D tensor"),M(t.shape[0]===o,()=>`scores has incompatible shape with boxes. Expected ${o}, but was ${t.shape[0]}`),M(0<=a&&a<=1,()=>`softNmsSigma must be in [0, 1], but was '${a}'`),{maxOutputSize:n,iouThreshold:r,scoreThreshold:s,softNmsSigma:a}}function yM(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY){let a=$(e,"boxes","nonMaxSuppression","float32"),o=$(t,"scores","nonMaxSuppression","float32"),i=Ac(a,o,n,r,s);n=i.maxOutputSize,r=i.iouThreshold,s=i.scoreThreshold;let l={maxOutputSize:n,iouThreshold:r,scoreThreshold:s};return B.runKernel(ll,{boxes:a,scores:o},l)}var AM=V({nonMaxSuppression_:yM});function xM(e,t,n){let r=bM(e,t,n),s=r<0?-(r+1):r;e.splice(s,0,t)}function bM(e,t,n){return wM(e,t,n||vM)}function vM(e,t){return e>t?1:e<t?-1:0}function wM(e,t,n){let r=0,s=e.length,a=0,o=!1;for(;r<s;){a=r+(s-r>>>1);let i=n(t,e[a]);i>0?r=a+1:(s=a,o=!i)}return o?r:-r-1}function D7(e,t,n,r,s){return mA(e,t,n,r,s,0)}function P7(e,t,n,r,s,a){return mA(e,t,n,r,s,0,!1,a,!0)}function F7(e,t,n,r,s,a){return mA(e,t,n,r,s,a,!0)}function mA(e,t,n,r,s,a,o=!1,i=!1,l=!1){let u=[];for(let g=0;g<t.length;g++)t[g]>s&&u.push({score:t[g],boxIndex:g,suppressBeginIndex:0});u.sort(Gb);let c=a>0?-.5/a:0,p=[],d=[];for(;p.length<n&&u.length>0;){let g=u.pop(),{score:y,boxIndex:x,suppressBeginIndex:A}=g;if(y<s)break;let b=!1;for(let v=p.length-1;v>=A;--v){let S=kM(e,x,p[v]);if(S>=r){b=!0;break}if(g.score=g.score*SM(r,c,S),g.score<=s)break}g.suppressBeginIndex=p.length,b||(g.score===y?(p.push(x),d.push(g.score)):g.score>s&&xM(u,g,Gb))}let h=p.length,f=n-h;i&&f>0&&(p.push(...new Array(f).fill(0)),d.push(...new Array(f).fill(0)));let m={selectedIndices:p};return o&&(m.selectedScores=d),l&&(m.validOutputs=h),m}function kM(e,t,n){let r=e.subarray(t*4,t*4+4),s=e.subarray(n*4,n*4+4),a=Math.min(r[0],r[2]),o=Math.min(r[1],r[3]),i=Math.max(r[0],r[2]),l=Math.max(r[1],r[3]),u=Math.min(s[0],s[2]),c=Math.min(s[1],s[3]),p=Math.max(s[0],s[2]),d=Math.max(s[1],s[3]),h=(i-a)*(l-o),f=(p-u)*(d-c);if(h<=0||f<=0)return 0;let m=Math.max(a,u),g=Math.max(o,c),y=Math.min(i,p),x=Math.min(l,d),A=Math.max(y-m,0)*Math.max(x-g,0);return A/(h+f-A)}function SM(e,t,n){let r=Math.exp(t*n*n);return n<=e?r:0}function Gb(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function IM(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY){let a=$(e,"boxes","nonMaxSuppressionAsync"),o=$(t,"scores","nonMaxSuppressionAsync"),i=Ac(a,o,n,r,s);n=i.maxOutputSize,r=i.iouThreshold,s=i.scoreThreshold;let l=await Promise.all([a.data(),o.data()]),u=l[0],c=l[1],{selectedIndices:p}=D7(u,c,n,r,s);return a!==e&&a.dispose(),o!==t&&o.dispose(),Ct(p,"int32")}var CM=IM;function TM(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,a=0){let o=$(e,"boxes","nonMaxSuppression"),i=$(t,"scores","nonMaxSuppression"),l=Ac(o,i,n,r,s,a);n=l.maxOutputSize,r=l.iouThreshold,s=l.scoreThreshold,a=l.softNmsSigma;let u={boxes:o,scores:i},c={maxOutputSize:n,iouThreshold:r,scoreThreshold:s,softNmsSigma:a},p=B.runKernel(ul,u,c);return{selectedIndices:p[0],selectedScores:p[1]}}var NM=V({nonMaxSuppressionWithScore_:TM});async function EM(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,a=0){let o=$(e,"boxes","nonMaxSuppressionAsync"),i=$(t,"scores","nonMaxSuppressionAsync"),l=Ac(o,i,n,r,s,a);n=l.maxOutputSize,r=l.iouThreshold,s=l.scoreThreshold,a=l.softNmsSigma;let u=await Promise.all([o.data(),i.data()]),c=u[0],p=u[1],{selectedIndices:d,selectedScores:h}=F7(c,p,n,r,s,a);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Ct(d,"int32"),selectedScores:Ct(h)}}var RM=EM;function _M(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,a=!1){let o=$(e,"boxes","nonMaxSuppression"),i=$(t,"scores","nonMaxSuppression"),l=Ac(o,i,n,r,s,null),u=l.maxOutputSize,c=l.iouThreshold,p=l.scoreThreshold,d={boxes:o,scores:i},h={maxOutputSize:u,iouThreshold:c,scoreThreshold:p,padToMaxOutputSize:a},f=B.runKernel(nc,d,h);return{selectedIndices:f[0],validOutputs:f[1]}}var $M=V({nonMaxSuppressionPadded_:_M});async function DM(e,t,n,r=.5,s=Number.NEGATIVE_INFINITY,a=!1){let o=$(e,"boxes","nonMaxSuppressionAsync"),i=$(t,"scores","nonMaxSuppressionAsync"),l=Ac(o,i,n,r,s,null),u=l.maxOutputSize,c=l.iouThreshold,p=l.scoreThreshold,[d,h]=await Promise.all([o.data(),i.data()]),{selectedIndices:f,validOutputs:m}=P7(d,h,u,c,p,a);return o!==e&&o.dispose(),i!==t&&i.dispose(),{selectedIndices:Ct(f,"int32"),validOutputs:Ie(m,"int32")}}var PM=DM;function FM(e,t,n=!1,r=!1){let s=$(e,"images","resizeBilinear");M(s.rank===3||s.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${s.rank}.`),M(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),M(r===!1||n===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let a=s,o=!1;s.rank===3&&(o=!0,a=H(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let[]=t,i={images:a},l={alignCorners:n,halfPixelCenters:r,size:t},u=B.runKernel($o,i,l);return o?H(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var OM=V({resizeBilinear_:FM});function MM(e,t,n=!1,r=!1){let s=$(e,"images","resizeNearestNeighbor");M(s.rank===3||s.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${s.rank}.`),M(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),M(s.dtype==="float32"||s.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),M(r===!1||n===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let a=s,o=!1;s.rank===3&&(o=!0,a=H(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let[]=t,i={images:a},l={alignCorners:n,halfPixelCenters:r,size:t},u=B.runKernel(ac,i,l);return o?H(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var zM=V({resizeNearestNeighbor_:MM});function LM(e,t="binary",n=!1,r=.5){let s=$(e,"image","threshold"),a=.2989,o=.587,i=.114,l=s.shape[0]*s.shape[1],u=L(Ct([r]),255),c,p,d,h;if(M(s.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${s.rank}.`),M(s.shape[2]===3||s.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${s.shape[2]}.`),M(s.dtype==="int32"||s.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${s.dtype}.`),M(t==="otsu"||t==="binary",()=>`Method must be binary or otsu, but was ${t}`),s.shape[2]===3){[c,p,d]=Yt(s,[1,1,1],-1);let g=L(c,a),y=L(p,o),x=L(d,i);h=ue(ue(g,y),x)}else h=e;if(t==="otsu"){let g=zy(ge(nA(h),"int32"),pt([]),256);u=BM(g,l)}let f=n?$l(h,u):Ar(h,u);return ge(L(f,255),"int32")}function BM(e,t){let n=Ct([-1]),r=Ct([0]),s=Ct([0]),a,o,i,l,u,c;for(let p=0;p<e.size-1;p++){a=Pe(e,0,p+1),o=Pe(e,p+1),u=de(ke(a),t),c=de(ke(o),t);let d=ke(L(a,Nu(0,a.size)));i=de(d,ke(a));let h=hc(o.shape,a.size),f=ue(Nu(0,o.size),h),m=L(o,f);l=de(ke(m),ke(o));let g=he(i,l),y=he(i,l),x=L(u,c);s=L(L(x,g),y);let A=Ar(s,r);r=Hn(A,s,r),n=Hn(A,Ct([p]),n)}return n}var WM=V({threshold_:LM});function VM(e,t,n="nearest",r="constant",s=0,a){let o=$(e,"image","transform","float32"),i=$(t,"transforms","transform","float32");M(o.rank===4,()=>`Error in transform: image must be rank 4,but got rank ${o.rank}.`),M(i.rank===2&&(i.shape[0]===o.shape[0]||i.shape[0]===1)&&i.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),M(a==null||a.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${a}.`);let l={image:o,transforms:i},u={interpolation:n,fillMode:r,fillValue:s,outputShape:a};return B.runKernel(Il,l,u)}var UM=V({transform_:VM});function GM(e,t,n){M(t%1===0,()=>`bandPart(): numLower must be an integer, got ${t}.`),M(n%1===0,()=>`bandPart(): numUpper must be an integer, got ${n}.`);let r=$(e,"a","bandPart");M(r.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${r.rank}.`);let s=r.shape,[a,o]=r.shape.slice(-2);if(!(t<=a))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${a}).`);if(!(n<=o))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${o}).`);t<0&&(t=a),n<0&&(n=o);let i=H(Nu(0,a,1,"int32"),[-1,1]),l=Nu(0,o,1,"int32"),u=he(i,l),c=ms($l(u,Ie(+t,"int32")),_l(u,Ie(-n,"int32"))),p=Ft([a,o],r.dtype);return H(cn(rr(H(r,[-1,a,o])).map(d=>Hn(c,d,p))),s)}var HM=V({bandPart_:GM});function jM(e){let t;if(Array.isArray(e)){t=!1,M(e!=null&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");let s=e[0].shape[0];for(let a=1;a<e.length;++a)M(e[a].shape[0]===s,()=>`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[a].shape[0]} vs. ${s})`)}else t=!0,e=Yt(e,e.shape[0],0).map(s=>tt(s,[0]));M(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);let n=[],r=e;for(let s=0;s<e.length;++s)n.push(B.tidy(()=>{let a=r[s];if(s>0)for(let o=0;o<s;++o){let i=L(ke(L(n[o],a)),n[o]);a=he(a,i)}return de(a,dA(a,"euclidean"))}));return t?cn(n,0):n}var qM=V({gramSchmidt_:jM});function XM(e,t=!1){if(M(e.rank>=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return Hb(e,t);{let n=e.shape.slice(0,e.shape.length-2).reduce((l,u)=>l*u),r=rr(H(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),s=[],a=[];r.forEach(l=>{let[u,c]=Hb(l,t);s.push(u),a.push(c)});let o=H(cn(s,0),e.shape),i=H(cn(a,0),e.shape);return[o,i]}}function Hb(e,t=!1){return B.tidy(()=>{M(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);let n=e.shape[0],r=e.shape[1],s=Hy(n),a=Gn(e),o=ps([[1]],[1,1]),i=Gn(o),l=n>=r?r:n;for(let u=0;u<l;++u){let c=a,p=i,d=s;[i,a,s]=B.tidy(()=>{let h=Pe(a,[u,u],[n-u,1]),f=dA(h),m=Pe(a,[u,u],[1,1]),g=Hn(Ar(m,0),ps([[-1]]),ps([[1]])),y=he(m,L(g,f)),x=de(h,y);x.shape[0]===1?i=Gn(o):i=St([o,Pe(x,[1,0],[x.shape[0]-1,x.shape[1]])],0);let A=zt(de(Ye(g,y),f)),b=Pe(a,[u,0],[n-u,r]),v=L(A,i),S=et(i);if(u===0)a=he(b,Ye(v,Ye(S,b)));else{let R=he(b,Ye(v,Ye(S,b)));a=St([Pe(a,[0,0],[u,r]),R],0)}let I=et(v),E=Pe(s,[0,u],[n,s.shape[1]-u]);if(u===0)s=he(E,Ye(Ye(E,i),I));else{let R=he(E,Ye(Ye(E,i),I));s=St([Pe(s,[0,0],[n,u]),R],1)}return[i,a,s]}),ne([c,p,d])}return!t&&n>r&&(s=Pe(s,[0,0],[n,r]),a=Pe(a,[0,0],[r,r])),[s,a]})}var KM=V({qr_:XM}),O7=(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))(O7||{});function ZM(e,t,n=3){let r=$(e,"losses","computeWeightedLoss"),s=null;t!=null&&(s=$(t,"weights","computeWeightedLoss"));let a=s==null?r:L(r,s);if(n===0)return a;if(n===2)return ke(a);if(n===1){if(s==null)return Vt(a);{let o=r.size/s.size,i=de(ke(a),ke(s));return o>1?de(i,Ie(o)):i}}if(n===3){if(s==null)return de(ke(a),Ie(r.size));{let o=L(s,gr(r.shape)),i=ge(ke(Tu(o,Ie(0))),"float32");return de(ke(a),i)}}throw Error(`Unknown reduction: ${n}`)}var sa=V({computeWeightedLoss_:ZM});function YM(e,t,n,r=3){let s=$(e,"labels","absoluteDifference"),a=$(t,"predictions","absoluteDifference"),o=null;n!=null&&(o=$(n,"weights","absoluteDifference")),jn(s.shape,a.shape,"Error in absoluteDifference: ");let i=rn(he(s,a));return sa(i,o,r)}var JM=V({absoluteDifference_:YM});function QM(e,t,n,r,s=3){let a=$(e,"labels","cosineDistance"),o=$(t,"predictions","cosineDistance"),i=null;r!=null&&(i=$(r,"weights","cosineDistance")),jn(a.shape,o.shape,"Error in cosineDistance: ");let l=Ie(1),u=he(l,ke(L(a,o),n,!0));return sa(u,i,s)}var ez=V({cosineDistance_:QM});function tz(e,t,n,r=3){let s=$(e,"labels","hingeLoss"),a=$(t,"predictions","hingeLoss"),o=null;n!=null&&(o=$(n,"weights","hingeLoss")),jn(s.shape,a.shape,"Error in hingeLoss: ");let i=Ie(1);s=he(L(Ie(2),s),i);let l=Os(he(i,L(s,a)));return sa(l,o,r)}var nz=V({hingeLoss_:tz});function rz(e,t,n,r=1,s=3){let a=$(e,"labels","huberLoss"),o=$(t,"predictions","huberLoss"),i=null;n!=null&&(i=$(n,"weights","huberLoss")),jn(a.shape,o.shape,"Error in huberLoss: ");let l=Ie(r),u=rn(he(o,a)),c=Sp(u,l),p=he(u,c),d=ue(L(Ie(.5),xt(c)),L(l,p));return sa(d,i,s)}var sz=V({huberLoss_:rz});function az(e,t,n,r=1e-7,s=3){let a=$(e,"labels","logLoss"),o=$(t,"predictions","logLoss"),i=null;n!=null&&(i=$(n,"weights","logLoss")),jn(a.shape,o.shape,"Error in logLoss: ");let l=Ie(1),u=Ie(r),c=zt(L(a,Dr(ue(o,u)))),p=L(he(l,a),Dr(ue(he(l,o),u))),d=he(c,p);return sa(d,i,s)}var oz=V({logLoss_:az});function iz(e,t,n,r=3){let s=$(e,"labels","meanSquaredError"),a=$(t,"predictions","meanSquaredError"),o=null;n!=null&&(o=$(n,"weights","meanSquaredError")),jn(s.shape,a.shape,"Error in meanSquaredError: ");let i=uA(s,a);return sa(i,o,r)}var lz=V({meanSquaredError_:iz});function uz(e,t){let n=$(e,"labels","sigmoidCrossEntropyWithLogits"),r=$(t,"logits","sigmoidCrossEntropyWithLogits");jn(n.shape,r.shape,"Error in sigmoidCrossEntropyWithLogits: ");let s=Os(r),a=L(r,n),o=Em($r(zt(rn(r))));return ue(he(s,a),o)}function cz(e,t,n,r=0,s=3){let a=$(e,"multiClassLabels","sigmoidCrossEntropy"),o=$(t,"logits","sigmoidCrossEntropy"),i=null;if(n!=null&&(i=$(n,"weights","sigmoidCrossEntropy")),jn(a.shape,o.shape,"Error in sigmoidCrossEntropy: "),r>0){let u=Ie(r),c=Ie(1),p=Ie(.5);a=ue(L(a,he(c,u)),L(p,u))}let l=uz(a,o);return sa(l,i,s)}var dz=V({sigmoidCrossEntropy_:cz});function pz(e,t,n=-1){if(n===-1&&(n=t.rank-1),n!==t.rank-1)throw Error(`Softmax cross entropy along a non-last dimension is not yet supported. Labels / logits was rank ${t.rank} and dim was ${n}`);return Ds((s,a,o)=>{let l=u7(a,[n],!0),u=he(ge(a,"float32"),l);o([s,u]);let c=zt(L(u,s));return{value:ke(c,[n]),gradFunc:(h,f)=>{let[m,g]=f,y=Pi(h.shape,[n]);return[L(H(h,y),he(ge(m,"float32"),$r(g))),L(H(h,y),he($r(g),ge(m,"float32")))]}}})(e,t)}function hz(e,t,n,r=0,s=3){let a=$(e,"onehotLabels","softmaxCrossEntropy"),o=$(t,"logits","softmaxCrossEntropy"),i=null;if(n!=null&&(i=$(n,"weights","softmaxCrossEntropy")),jn(a.shape,o.shape,"Error in softmaxCrossEntropy: "),r>0){let u=Ie(r),c=Ie(1),p=Ie(a.shape[1]);a=ue(L(a,he(c,u)),de(u,p))}let l=pz(a,o);return sa(l,i,s)}var fz=V({softmaxCrossEntropy_:hz});function mz(e,t,n,r){let s=$(e,"indices","sparseFillEmptyRows","int32"),a=$(t,"values","sparseFillEmptyRows"),o=$(n,"denseShape","sparseFillEmptyRows","int32"),i=$(r,"defaultValue","sparseFillEmptyRows",a.dtype);if(s.rank!==2)throw new Error(`Indices should be Tensor2D but received shape
|
|
${s.shape}`);if(a.rank!==1)throw new Error(`Values should be Tensor1D but received shape ${a.shape}`);if(o.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${o.shape}`);if(i.rank!==0)throw new Error(`Default value should be a scalar but received shape ${i.shape}`);let l={indices:s,values:a,denseShape:o,defaultValue:i},u=B.runKernel(lp,l);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}var gz=V({sparseFillEmptyRows_:mz});function yz(e,t,n){let r=$(e,"inputIndices","sparseReshape","int32"),s=$(t,"inputShape","sparseReshape","int32"),a=$(n,"newShape","sparseReshape","int32");if(r.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape
|
|
${r.shape}`);if(s.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${s.shape}`);if(a.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${a.shape}`);let o={inputIndices:r,inputShape:s,newShape:a},i=B.runKernel(uc,o);return{outputIndices:i[0],outputShape:i[1]}}var Az=V({sparseReshape_:yz});function xz(e,t,n){let r=$(e,"data","sparseSegmentMean"),s=$(t,"indices","sparseSegmentMean","int32"),a=$(n,"segmentIds","sparseSegmentMean","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
|
|
${s.shape}`);if(a.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
|
|
${a.shape}`);let o={data:r,indices:s,segmentIds:a};return B.runKernel(up,o)}var bz=V({sparseSegmentMean_:xz});function vz(e,t,n){let r=$(e,"data","sparseSegmentSum"),s=$(t,"indices","sparseSegmentSum","int32"),a=$(n,"segmentIds","sparseSegmentSum","int32");if(r.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.rank!==1)throw new Error(`Indices should be Tensor1D but received shape
|
|
${s.shape}`);if(a.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape
|
|
${a.shape}`);let o={data:r,indices:s,segmentIds:a};return B.runKernel(cp,o)}var wz=V({sparseSegmentSum_:vz});function kz(e,t,n,r,s,a,o,i){let l=$(e,"data","stringNGrams","string");if(l.dtype!=="string")throw new Error("Data must be of datatype string");if(l.shape.length!==1)throw new Error(`Data must be a vector, saw: ${l.shape}`);let u=$(t,"dataSplits","stringNGrams");if(u.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let c={separator:n,nGramWidths:r,leftPad:s,rightPad:a,padWidth:o,preserveShortSequences:i},p={data:l,dataSplits:u},d=B.runKernel(pp,p,c);return{nGrams:d[0],nGramsSplits:d[1]}}var Sz=V({stringNGrams_:kz});function Iz(e,t,n=!0){let r=$(e,"input","stringSplit","string"),s=$(t,"delimiter","stringSplit","string");if(r.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${r.shape}`);if(s.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${s.shape}`);let a={skipEmpty:n},o={input:r,delimiter:s},i=B.runKernel(xm,o,a);return{indices:i[0],values:i[1],shape:i[2]}}var Cz=V({stringSplit_:Iz});function Tz(e,t){let n=$(e,"input","stringToHashBucketFast","string"),r={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");let s={input:n};return B.runKernel(bm,s,r)}var Nz=V({stringToHashBucketFast_:Tz}),Ez={fft:Mm,ifft:Gd,rfft:zm,irfft:lA},Rz={hammingWindow:sM,hannWindow:_7,frame:$7,stft:lM},Se={flipLeftRight:pM,grayscaleToRGB:fM,resizeNearestNeighbor:zM,resizeBilinear:OM,rotateWithOffset:gM,cropAndResize:cM,nonMaxSuppression:AM,nonMaxSuppressionAsync:CM,nonMaxSuppressionWithScore:NM,nonMaxSuppressionWithScoreAsync:RM,nonMaxSuppressionPadded:$M,nonMaxSuppressionPaddedAsync:PM,threshold:WM,transform:UM},M7={bandPart:HM,gramSchmidt:qM,qr:KM},_z={absoluteDifference:JM,computeWeightedLoss:sa,cosineDistance:ez,hingeLoss:nz,huberLoss:sz,logLoss:oz,meanSquaredError:lz,sigmoidCrossEntropy:dz,softmaxCrossEntropy:fz},kd={sparseFillEmptyRows:gz,sparseReshape:Az,sparseSegmentMean:bz,sparseSegmentSum:wz},af={stringNGrams:Sz,stringSplit:Cz,stringToHashBucketFast:Nz},aa=class extends Sw{minimize(e,t=!1,n){let{value:r,grads:s}=this.computeGradients(e,n);if(n!=null){let a=n.map(o=>({name:o.name,tensor:s[o.name]}));this.applyGradients(a)}else this.applyGradients(s);return ne(s),t?r:(r.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return a7(e,t)}dispose(){this.iterations_!=null&&ne(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:Ie(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(aa,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var Gm=class extends aa{constructor(e,t,n=null){super(),this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=B.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,r)=>{let s=B.registeredVariables[n],a=!1;this.accumulatedGrads[r]==null&&(this.accumulatedGrads[r]={originalName:`${n}/accum_grad`,variable:K(()=>st(s).variable(a))}),this.accumulatedUpdates[r]==null&&(this.accumulatedUpdates[r]={originalName:`${n}/accum_var`,variable:K(()=>st(s).variable(a))});let o=Array.isArray(e)?e[r].tensor:e[n];if(o==null)return;let i=this.accumulatedGrads[r].variable,l=this.accumulatedUpdates[r].variable;K(()=>{let u=ue(L(i,this.rho),L(xt(o),1-this.rho)),c=L(de(En(ue(l,this.epsilon)),En(ue(i,this.epsilon))),o),p=ue(L(l,this.rho),L(xt(c),1-this.rho));i.assign(u),l.assign(p);let d=ue(L(c,-this.learningRate),s);s.assign(d)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(ne(this.accumulatedGrads.map(e=>e.variable)),ne(this.accumulatedUpdates.map(e=>e.variable)))}async getWeights(){let e=[...this.accumulatedGrads,...this.accumulatedUpdates];return[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=e.length/2,n=!1;this.accumulatedGrads=e.slice(0,t).map(r=>({originalName:r.name,variable:r.tensor.variable(n)})),this.accumulatedUpdates=e.slice(t,t*2).map(r=>({originalName:r.name,variable:r.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,rho:this.rho,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.rho,t.epsilon)}};Gm.className="Adadelta";jo(Gm);var Hm=class extends aa{constructor(e,t=.1){super(),this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,r)=>{let s=B.registeredVariables[n];this.accumulatedGrads[r]==null&&(this.accumulatedGrads[r]={originalName:`${n}/accumulator`,variable:K(()=>hc(s.shape,this.initialAccumulatorValue).variable(!1))});let a=Array.isArray(e)?e[r].tensor:e[n];if(a==null)return;let o=this.accumulatedGrads[r].variable;K(()=>{let i=ue(o,xt(a));o.assign(i);let l=ue(L(de(a,En(ue(i,B.backend.epsilon()))),-this.learningRate),s);s.assign(l)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&ne(this.accumulatedGrads.map(e=>e.variable))}async getWeights(){return[await this.saveIterations()].concat(this.accumulatedGrads.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=!1;this.accumulatedGrads=e.map(n=>({originalName:n.name,variable:n.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,initialAccumulatorValue:this.initialAccumulatorValue}}static fromConfig(e,t){return new e(t.learningRate,t.initialAccumulatorValue)}};Hm.className="Adagrad";jo(Hm);var jm=class extends aa{constructor(e,t,n,r=null){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],K(()=>{this.accBeta1=Ie(t).variable(),this.accBeta2=Ie(n).variable()}),r==null&&(this.epsilon=B.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);K(()=>{let n=he(1,this.accBeta1),r=he(1,this.accBeta2);t.forEach((s,a)=>{let o=B.registeredVariables[s],i=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${s}/m`,variable:K(()=>st(o).variable(i))}),this.accumulatedSecondMoment[a]==null&&(this.accumulatedSecondMoment[a]={originalName:`${s}/v`,variable:K(()=>st(o).variable(i))});let l=Array.isArray(e)?e[a].tensor:e[s];if(l==null)return;let u=this.accumulatedFirstMoment[a].variable,c=this.accumulatedSecondMoment[a].variable,p=ue(L(u,this.beta1),L(l,1-this.beta1)),d=ue(L(c,this.beta2),L(xt(l),1-this.beta2)),h=de(p,n),f=de(d,r);u.assign(p),c.assign(d);let m=ue(L(de(h,ue(En(f),this.epsilon)),-this.learningRate),o);o.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&&ne(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&ne(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(Wa(this.beta1,this.iterations_+1)),this.accBeta2.assign(Wa(this.beta2,this.iterations_+1))});let t=e.length/2,n=!1;this.accumulatedFirstMoment=e.slice(0,t).map(r=>({originalName:r.name,variable:r.tensor.variable(n)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(r=>({originalName:r.name,variable:r.tensor.variable(n)}))}getConfig(){return{learningRate:this.learningRate,beta1:this.beta1,beta2:this.beta2,epsilon:this.epsilon}}static fromConfig(e,t){return new e(t.learningRate,t.beta1,t.beta2,t.epsilon)}};jm.className="Adam";jo(jm);var qm=class extends aa{constructor(e,t,n,r=null,s=0){super(),this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=r,this.decay=s,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],K(()=>{this.iteration=Ie(0).variable(),this.accBeta1=Ie(t).variable()}),r==null&&(this.epsilon=B.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);K(()=>{let n=he(1,this.accBeta1),r=de(-this.learningRate,ue(L(this.iteration,this.decay),1));t.forEach((s,a)=>{let o=B.registeredVariables[s],i=!1;this.accumulatedFirstMoment[a]==null&&(this.accumulatedFirstMoment[a]={originalName:`${s}/m`,variable:st(o).variable(i)}),this.accumulatedWeightedInfNorm[a]==null&&(this.accumulatedWeightedInfNorm[a]={originalName:`${s}/v`,variable:st(o).variable(i)});let l=Array.isArray(e)?e[a].tensor:e[s];if(l==null)return;let u=this.accumulatedFirstMoment[a].variable,c=this.accumulatedWeightedInfNorm[a].variable,p=ue(L(u,this.beta1),L(l,1-this.beta1)),d=L(c,this.beta2),h=rn(l),f=ra(d,h);u.assign(p),c.assign(f);let m=ue(L(de(r,n),de(p,ue(f,this.epsilon))),o);o.assign(m)}),this.iteration.assign(ue(this.iteration,1)),this.accBeta1.assign(L(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&ne(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&ne(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)}};qm.className="Adamax";jo(qm);var Cp=class extends aa{constructor(e){super(),this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,r)=>{let s=Array.isArray(e)?e[r].tensor:e[n];if(s==null)return;let a=B.registeredVariables[n];K(()=>{let o=ue(L(this.c,s),a);a.assign(o)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=fn(Ie(-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)}};Cp.className="SGD";jo(Cp);var Xm=class extends Cp{constructor(e,t,n=!1){super(e),this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=Ie(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,r)=>{let s=B.registeredVariables[n];this.accumulations[r]==null&&(this.accumulations[r]={originalName:`${n}/momentum`,variable:K(()=>st(s).variable(!1))});let a=this.accumulations[r].variable,o=Array.isArray(e)?e[r].tensor:e[n];o!=null&&K(()=>{let i,l=ue(L(this.m,a),o);this.useNesterov?i=ue(L(this.c,ue(o,L(l,this.m))),s):i=ue(L(this.c,l),s),a.assign(l),s.assign(i)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&ne(this.accumulations.map(e=>e.variable))}setMomentum(e){this.momentum=e}async getWeights(){return[await this.saveIterations()].concat(this.accumulations.map(e=>({name:e.originalName,tensor:e.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=!1;this.accumulations=e.map(n=>({originalName:n.name,variable:n.tensor.variable(t)}))}getConfig(){return{learningRate:this.learningRate,momentum:this.momentum,useNesterov:this.useNesterov}}static fromConfig(e,t){return new e(t.learningRate,t.momentum,t.useNesterov)}};Xm.className="Momentum";jo(Xm);var Km=class extends aa{constructor(e,t=.9,n=0,r=null,s=!1){if(super(),this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=r,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=s,r==null&&(this.epsilon=B.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(n=>n.name):Object.keys(e)).forEach((n,r)=>{let s=B.registeredVariables[n],a=!1;this.accumulatedMeanSquares[r]==null&&(this.accumulatedMeanSquares[r]={originalName:`${n}/rms`,variable:K(()=>st(s).variable(a))}),this.accumulatedMoments[r]==null&&(this.accumulatedMoments[r]={originalName:`${n}/momentum`,variable:K(()=>st(s).variable(a))}),this.accumulatedMeanGrads[r]==null&&this.centered&&(this.accumulatedMeanGrads[r]={originalName:`${n}/mg`,variable:K(()=>st(s).variable(a))});let o=Array.isArray(e)?e[r].tensor:e[n];if(o==null)return;let i=this.accumulatedMeanSquares[r].variable,l=this.accumulatedMoments[r].variable;K(()=>{let u=ue(L(i,this.decay),L(xt(o),1-this.decay));if(this.centered){let c=this.accumulatedMeanGrads[r].variable,p=ue(L(c,this.decay),L(o,1-this.decay)),d=de(L(o,this.learningRate),En(he(u,ue(xt(p),this.epsilon)))),h=ue(L(l,this.momentum),d);i.assign(u),c.assign(p),l.assign(h);let f=he(s,h);s.assign(f)}else{let c=ue(L(i,this.decay),L(xt(o),1-this.decay)),p=ue(L(l,this.momentum),de(L(o,this.learningRate),En(ue(c,this.epsilon))));i.assign(c),l.assign(p);let d=he(s,p);s.assign(d)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&ne(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&ne(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&ne(this.accumulatedMoments.map(e=>e.variable))}async getWeights(){let e=[...this.accumulatedMeanSquares,...this.accumulatedMoments];return this.centered&&e.push(...this.accumulatedMeanGrads),[await this.saveIterations()].concat(e.map(t=>({name:t.originalName,tensor:t.variable})))}async setWeights(e){e=await this.extractIterations(e);let t=this.centered?e.length/3:e.length/2,n=!1;this.accumulatedMeanSquares=e.slice(0,t).map(r=>({originalName:r.name,variable:r.tensor.variable(n)})),this.accumulatedMoments=e.slice(t,t*2).map(r=>({originalName:r.name,variable:r.tensor.variable(n)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(r=>({originalName:r.name,variable:r.tensor.variable(n)})))}getConfig(){return{learningRate:this.learningRate,decay:this.decay,momentum:this.momentum,epsilon:this.epsilon,centered:this.centered}}static fromConfig(e,t){return new e(t.learningRate,t.decay,t.momentum,t.epsilon,t.centered)}};Km.className="RMSProp";jo(Km);var Ia=class{static sgd(e){return new Cp(e)}static momentum(e,t,n=!1){return new Xm(e,t,n)}static rmsprop(e,t=.9,n=0,r=null,s=!1){return new Km(e,t,n,r,s)}static adam(e=.001,t=.9,n=.999,r=null){return new jm(e,t,n,r)}static adadelta(e=.001,t=.95,n=null){return new Gm(e,t,n)}static adamax(e=.002,t=.9,n=.999,r=null,s=0){return new qm(e,t,n,r,s)}static adagrad(e,t=.1){return new Hm(e,t)}},Ai={sgd:Ia.sgd,momentum:Ia.momentum,adadelta:Ia.adadelta,adagrad:Ia.adagrad,rmsprop:Ia.rmsprop,adamax:Ia.adamax,adam:Ia.adam},$z=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function gA(){return new Promise(e=>$z(()=>e()))}var C={};Le(C,{ERF_A1:()=>Uz,ERF_A2:()=>Gz,ERF_A3:()=>Hz,ERF_A4:()=>jz,ERF_A5:()=>qz,ERF_P:()=>Vz,PARALLELIZE_THRESHOLD:()=>yA,SELU_SCALE:()=>L7,SELU_SCALEALPHA:()=>z7,applyActivation:()=>Vm,assertAndGetBroadcastShape:()=>vt,assertAxesAreInnerMostDims:()=>GP,assertParamsConsistent:()=>Dz,assignToTypedArray:()=>Qz,axesAreInnerMostDims:()=>Xy,calculateShapes:()=>fw,checkEinsumDimSizes:()=>aL,checkPadOnDimRoundingMode:()=>Xn,combineLocations:()=>o7,complexWithEvenIndex:()=>Zz,complexWithOddIndex:()=>Yz,computeConv2DInfo:()=>bp,computeConv3DInfo:()=>Mw,computeDefaultPad:()=>Oy,computeDilation2DInfo:()=>uD,computeOptimalWindowSize:()=>Fz,computeOutAndReduceShapes:()=>i7,computeOutShape:()=>Pz,computePool2DInfo:()=>Ow,computePool3DInfo:()=>cD,convertConv2DDataFormat:()=>zw,decodeEinsumEquation:()=>rL,eitherStridesOrDilationsAreOne:()=>Fs,expandShapeToKeepDim:()=>Pi,exponent:()=>tL,exponents:()=>eL,fromStringArrayToUint8:()=>CL,fromUint8ToStringArray:()=>IL,getAxesPermutation:()=>l7,getBroadcastDims:()=>cw,getComplexWithIndex:()=>Jz,getEinsumComputePath:()=>oL,getEinsumPermutation:()=>sL,getFusedBiasGradient:()=>Wm,getFusedDyActivation:()=>Bm,getImageCenter:()=>Oz,getInnerMostAxes:()=>HP,getPermuted:()=>zz,getReductionAxes:()=>Jt,getReshaped:()=>Mz,getReshapedPermuted:()=>Lz,getSliceBeginCoords:()=>Bz,getSliceSize:()=>Wz,getSparseFillEmptyRowsIndicesDenseShapeMismatch:()=>cL,getSparseFillEmptyRowsNegativeIndexErrorMessage:()=>dL,getSparseFillEmptyRowsOutOfRangeIndexErrorMessage:()=>pL,getSparseReshapeEmptyTensorZeroOutputDimErrorMessage:()=>mL,getSparseReshapeInputOutputMismatchErrorMessage:()=>yL,getSparseReshapeInputOutputMultipleErrorMessage:()=>gL,getSparseReshapeMultipleNegativeOneOutputDimErrorMessage:()=>hL,getSparseReshapeNegativeOutputDimErrorMessage:()=>fL,getSparseSegmentReductionIndicesOutOfRangeErrorMessage:()=>vL,getSparseSegmentReductionNegativeSegmentIdsErrorMessage:()=>AL,getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage:()=>xL,getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage:()=>bL,getUndoAxesPermutation:()=>Ky,isIdentityPermutation:()=>iL,log:()=>MR,mergeRealAndImagArrays:()=>Xz,prepareAndValidate:()=>hw,prepareSplitSize:()=>uL,segment_util:()=>B7,shouldFuse:()=>Um,slice_util:()=>Mt,splitRealAndImagArrays:()=>Kz,tupleValuesAreOne:()=>za,upcastType:()=>Nn,validateInput:()=>Ty,validateUpdateShape:()=>Cy,warn:()=>Ta});function Dz(e,t){let n=e[0].length;e.forEach((s,a)=>{M(s.length===n,()=>`Error in concat${n}D: rank of tensors[${a}] must be the same as the rank of the rest (${n})`)}),M(t>=0&&t<n,()=>`Error in concat${n}D: axis must be between 0 and ${n-1}.`);let r=e[0];e.forEach((s,a)=>{for(let o=0;o<n;o++)M(o===t||s[o]===r[o],()=>`Error in concat${n}D: Shape of tensors[${a}] (${s}) does not match the shape of the rest (${r}) along the non-concatenated axis ${a}.`)})}function Pz(e,t){let n=e[0].slice();for(let r=1;r<e.length;r++)n[t]+=e[r][t];return n}var yA=30;function Fz(e){return e<=yA?e:yf(e,Math.floor(Math.sqrt(e)))}function Oz(e,t,n){let r=n*(typeof e=="number"?e:e[0]),s=t*(typeof e=="number"?e:e[1]);return[r,s]}function Mz(e,t,n,r=!0){let s=[];if(r)s=s.concat(t.slice(0)),s.push(e[0]/n),s=s.concat(e.slice(1));else{s=s.concat(e[0]);let a=t.length;for(let o=0;o<a;++o)s=s.concat([e[o+1]/t[o],t[o]]);s=s.concat(e.slice(a+1))}return s}function zz(e,t,n=!0){let r=[];if(n){r.push(t);for(let s=t+1;s<e;++s)s<=2*t?(r.push(s),r.push(s-(t+1))):r.push(s)}else{let s=[],a=[];for(let o=1;o<e;++o)o>=t*2+1||o%2===1?a.push(o):s.push(o);r.push(...s),r.push(0),r.push(...a)}return r}function Lz(e,t,n,r=!0){let s=[];r?s.push(e[0]/n):s.push(e[0]*n);for(let a=1;a<e.length;++a)a<=t.length?r?s.push(t[a-1]*e[a]):s.push(e[a]/t[a-1]):s.push(e[a]);return s}function Bz(e,t){let n=[0];for(let r=0;r<t;++r)n.push(e[r][0]);return n}function Wz(e,t,n){let r=e.slice(0,1);for(let s=0;s<n;++s)r.push(e[s+1]-t[s][0]-t[s][1]);return r}var z7=1.7580993408473768,L7=1.0507009873554805,Vz=.3275911,Uz=.254829592,Gz=-.284496736,Hz=1.421413741,jz=-1.453152027,qz=1.061405429;function Xz(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 n=new Float32Array(e.length*2);for(let r=0;r<n.length;r+=2)n[r]=e[r/2],n[r+1]=t[r/2];return n}function Kz(e){let t=new Float32Array(e.length/2),n=new Float32Array(e.length/2);for(let r=0;r<e.length;r+=2)t[r/2]=e[r],n[r/2]=e[r+1];return{real:t,imag:n}}function Zz(e){let t=Math.ceil(e.length/4),n=new Float32Array(t),r=new Float32Array(t);for(let s=0;s<e.length;s+=4)n[Math.floor(s/4)]=e[s],r[Math.floor(s/4)]=e[s+1];return{real:n,imag:r}}function Yz(e){let t=Math.floor(e.length/4),n=new Float32Array(t),r=new Float32Array(t);for(let s=2;s<e.length;s+=4)n[Math.floor(s/4)]=e[s],r[Math.floor(s/4)]=e[s+1];return{real:n,imag:r}}function Jz(e,t){let n=e[t*2],r=e[t*2+1];return{real:n,imag:r}}function Qz(e,t,n,r){e[r*2]=t,e[r*2+1]=n}function eL(e,t){let n=new Float32Array(e/2),r=new Float32Array(e/2);for(let s=0;s<Math.ceil(e/2);s++){let a=(t?2:-2)*Math.PI*(s/e);n[s]=Math.cos(a),r[s]=Math.sin(a)}return{real:n,imag:r}}function tL(e,t,n){let r=(n?2:-2)*Math.PI*(e/t),s=Math.cos(r),a=Math.sin(r);return{real:s,imag:a}}var ng="->",nL=/->/g,jb=",",qb="...";function rL(e,t){e=e.replace(/\s/g,"");let n=(e.length-e.replace(nL,"").length)/ng.length;if(n<1)throw new Error("Equations without an arrow are not supported.");if(n>1)throw new Error(`Equation must contain exactly one arrow ("${ng}").`);let[r,s]=e.split(ng);M(r.indexOf(qb)===-1,()=>`The ellipsis notation ("${qb}") is not supported yet.`);let a=r.split(jb),o=a.length;if(t!==o)throw new Error(`Expected ${o} input tensors, received ${t}`);if(o>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");let i=[];for(let d=0;d<s.length;++d){let h=s[d];if(!a.some(f=>f.indexOf(h)!==-1))throw new Error(`Output subscripts contain the label ${h} not present in the input subscripts.`);i.indexOf(h)===-1&&i.push(h)}for(let d=0;d<r.length;++d){let h=r[d];i.indexOf(h)===-1&&h!==jb&&i.push(h)}let l=new Array(a.length);for(let d=0;d<o;++d){if(new Set(a[d].split("")).size!==a[d].length)throw new Error(`Found duplicate axes in input component ${a[d]}. Support for duplicate axes in input is not implemented yet.`);l[d]=[];for(let h=0;h<a[d].length;++h)l[d].push(i.indexOf(a[d][h]))}let u=i.length,c=s.length,p=[];for(let d=c;d<u;++d)p.push(d);return{allDims:i,summedDims:p,idDims:l}}function sL(e,t){let n=new Array(e);n.fill(-1);for(let s=0;s<t.length;++s)n[t[s]]=s;let r=[];for(let s=0;s<e;++s)n[s]===-1&&r.push(s);return n=n.filter(s=>s!==-1),{permutationIndices:n,expandDims:r}}function aL(e,t,n){let r=new Array(e);for(let s=0;s<n.length;++s){let a=n[s].shape;for(let o=0;o<t[s].length;++o)r[t[s][o]]===void 0?r[t[s][o]]=a[o]:M(r[t[s][o]]===a[o],()=>`Expected dimension ${r[t[s][o]]} at axis ${o} of input shaped ${JSON.stringify(a)}, but got dimension ${a[o]}`)}}function oL(e,t){let n=e,r=[],s=0;e.length===0&&n.push(-1),s=e.length+1;for(let o=0;o<s;++o)r.push([]);let a=[];for(let o=0;o<n.length;++o){let i=n[o],l=lL(t,i);for(let u of l)a.indexOf(u)===-1&&(r[o].push(u),a.push(u))}return{path:n,steps:r}}function iL(e){return e.every((t,n)=>t===n)}function lL(e,t){let n=[];for(let r=0;r<e.length;++r)(e[r].length===0||e[r].indexOf(t)!==-1||t===-1)&&n.push(r);return n}function uL(e,t,n=0){let r=[];if(typeof t=="number")M(e.shape[n]%t===0,()=>"Number of splits must evenly divide the axis."),r=new Array(t).fill(e.shape[n]/t);else{let s=t.reduce((o,i)=>(i===-1&&(o+=1),o),0);M(s<=1,()=>"There should be only one negative value in split array.");let a=t.indexOf(-1);if(a!==-1){let o=t.reduce((i,l)=>l>0?i+l:i);t[a]=e.shape[n]-o}M(e.shape[n]===t.reduce((o,i)=>o+i),()=>"The sum of sizes must match the size of the axis dimension."),r=t}return r}function cL(e){return`Received SparseTensor with denseShape[0] = 0 but
|
|
indices.shape[0] = ${e}`}function dL(e,t){return`indices(${e}, 0) is invalid: ${t} < 0`}function pL(e,t,n){return`indices(${e}, 0) is invalid: ${t} >= ${n}`}function hL(e,t){return`only one output dimension may be -1, not both ${e} and ${t}`}function fL(e,t){return`size ${e} must be non-negative, not ${t}`}function mL(){return"reshape cannot infer the missing input size for an empty tensor unless all specified input sizes are non-zero"}function gL(e,t){let n=Tt(e),r=Tt(t);return`Input to reshape is a SparseTensor with ${n}
|
|
dense values, but the requested shape requires a multiple of ${r}. inputShape=${e} outputShape= ${t}`}function yL(e,t){let n=Tt(e),r=Tt(t);return`Input to reshape is a tensor with ${n} dense values, but the requested shape has ${r}. inputShape=${e} outputShape=${t}`}function AL(){return"segment ids must be >= 0"}function xL(){return"segment ids are not increasing"}function bL(e,t){return`Segment id ${e} out of range [0, ${t}), possibly because segmentIds input is not sorted.`}function vL(e,t,n){return`Bad: indices[${e}] == ${t} out of range [0, ${n})`}var B7={};Le(B7,{collectGatherOpShapeInfo:()=>SL,computeOutShape:()=>kL,segOpComputeOptimalWindowSize:()=>wL});function wL(e,t){let n=!1,r;for(e<=yA?(r=e,n=!0):r=yf(e,Math.floor(Math.sqrt(e)));!n;)r>t||r===e?n=!0:r=yf(e,r+1);return r}function kL(e,t,n){let r=[],s=e.length;for(let a=0;a<s;a++)a!==t?r.push(e[a]):r.push(n);return r}function SL(e,t,n,r){let s=t.shape.length,a=e.shape.length;if(r!==0&&(r<-s||r>s))throw new Error(`Expect batchDims in the range of [-${s}, ${s}], but got ${r}`);if(r<0&&(r+=s),r>a)throw new Error(`batchDims (${r}) must be less than rank(x) (
|
|
${a}).`);if(n<r)throw new Error(`batchDims (${r}) must be less than or equal to axis (${n}).`);for(let p=0;p<r;++p)if(e.shape[p]!==t.shape[p])throw new Error(`x.shape[${p}]: ${e.shape[p]} should be equal to indices.shape[${p}]: ${t.shape[p]}.`);let o=e.shape[n],i=[],l=1,u=1,c=1;for(let p=0;p<r;++p)i.push(e.shape[p]),l*=e.shape[p];for(let p=r;p<n;p++)i.push(e.shape[p]),u*=e.shape[p];for(let p=r;p<s;p++)i.push(t.shape[p]);for(let p=n+1;p<a;p++)i.push(e.shape[p]),c*=e.shape[p];return{batchSize:l,sliceSize:c,outerSize:u,dimSize:o,outputShape:i}}function IL(e){try{return e.map(t=>vf(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function CL(e){return e.map(t=>mp(t))}var Kr={};Le(Kr,{nonMaxSuppressionV3Impl:()=>D7,nonMaxSuppressionV4Impl:()=>P7,nonMaxSuppressionV5Impl:()=>F7,whereImpl:()=>k7});var js=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,js.prototype)}},us=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,us.prototype)}},j=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,j.prototype)}},Ve=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,Ve.prototype)}},W7=class extends Error{constructor(e){super(e),Object.setPrototypeOf(this,W7.prototype)}},V7=class{constructor(e){this.maxEntries=e||100,this.cache=new Map}get(e){let t;return this.cache.has(e)&&(t=this.cache.get(e),this.cache.delete(e),this.cache.set(e,t)),t}put(e,t){if(this.cache.has(e))this.cache.delete(e);else if(this.cache.size>=this.maxEntries){let n=this.cache.keys().next().value;this.cache.delete(n)}this.cache.set(e,t)}getMaxEntries(){return this.maxEntries}setMaxEntries(e){if(e<0)throw new Error(`The maxEntries of LRU caches must be at least 0, but got ${e}.`);if(this.maxEntries>e)for(let t=0;t<this.maxEntries-e;t++){let n=this.cache.keys().next().value;this.cache.delete(n)}this.maxEntries=e}};function Oi(e,t){if(Array.isArray(e)){let n=[];for(let r=0;r<t;r++)n=n.concat(e);return n}else{let n=new Array(t);return n.fill(e),n}}function Ts(e,t){if(!e)throw new W7(t)}function Xb(e,t){let n=0;for(let r of e)r===t&&n++;return n}function tr(e){return e.length===1?e[0]:e}function It(e){return Array.isArray(e)?e:[e]}function qs(e){let n=e.replace(/(.)([A-Z][a-z0-9]+)/g,"$1_$2").replace(/([a-z])([A-Z])/g,"$1_$2").toLowerCase();return n[0]!=="_"?n:"private"+n}function wi(e){return e.length<=1||e.indexOf("_")===-1?e:e.replace(/[_]+(\w|$)/g,(t,n)=>n.toUpperCase())}var Vr={};function AA(e){if(e==null)return null;let t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function Ig(e){if(!(e==null||typeof e!="object"))if(Array.isArray(e))e.forEach(t=>Ig(t));else{let t=Object.keys(e);for(let n of t){let r=e[n];r!=null&&typeof r=="object"&&(!Array.isArray(r)&&r.type==="ndarray"&&typeof r.value=="number"?e[n]=r.value:Ig(r))}}}function Tp(e,t={},n={},r="object",s=!1){if(typeof e=="string"){let a=e,o;if(a in n)o=n[a];else if(a in Vr)o=Vr[a];else if(o=t[a],o==null)throw new j(`Unknown ${r}: ${e}. This may be due to one of the following reasons:
|
|
1. The ${r} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
|
|
2. The custom ${r} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return o}else{let a=e;if(a.className==null||a.config==null)throw new j(`${r}: Improper config format: ${JSON.stringify(a)}.
|
|
'className' and 'config' must set.`);let o=a.className,i,l;if(o in n?[i,l]=n[o]:o in Vr?[i,l]=Vr.className:o in t&&([i,l]=t[o]),i==null)throw new j(`Unknown ${r}: ${o}. This may be due to one of the following reasons:
|
|
1. The ${r} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code.
|
|
2. The custom ${r} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(l!=null){let u={};for(let h of Object.keys(Vr))u[h]=Vr[h];for(let h of Object.keys(n))u[h]=n[h];let c=a.config;c.customObjects=u;let p={...Vr};for(let h of Object.keys(n))Vr[h]=n[h];Ig(a.config);let d=l(i,a.config,n,s);return Vr={...p},d}else{let u={...Vr};for(let p of Object.keys(n))Vr[p]=n[p];let c=new i(a.config);return Vr={...u},c}}}function TL(e,t){return e<t?-1:e>t?1:0}function jh(e,t){return-1*TL(e,t)}function _a(e){if(e==null)return e;let t=[];for(let n of e)t.indexOf(n)===-1&&t.push(n);return t}function NL(e){if(e==null)throw new j(`Invalid value in obj: ${JSON.stringify(e)}`);for(let t in e)if(e.hasOwnProperty(t))return!1;return!0}function Pl(e,t,n){if(n!=null&&e.indexOf(n)<0)throw new j(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function xA(e,t,n=0,r=1/0){return Ts(n>=0),Ts(r>=n),Array.isArray(e)&&e.length>=n&&e.length<=r&&e.every(s=>typeof s===t)}function mn(e,t){Array.isArray(e)?(w.assert(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,r)=>mn(n,`element ${r+1} of ${t}`))):w.assert(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${U7(e)}.`)}function U7(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>U7(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function EL(e,t,n){let r=n!=null?n():w.now(),s;return(...o)=>{let i=n!=null?n():w.now();return i-r<t||(r=i,s=e(...o)),s}}function G7(e){return e==="relu"?"relu":e==="linear"?"linear":e==="elu"?"elu":null}var RL=0;function H7(){return RL++}var qh={};function Zm(e=""){return e in qh||(qh[e]=0),qh[e]+=1,e+qh[e].toString()}var _L=["channelsFirst","channelsLast"],$L=["nearest","bilinear"],DL=["valid","same","causal"],PL=["max","avg"],FL=["sum","mul","concat","ave"],uu=new Map;function Ht(e){Pl(_L,"DataFormat",e)}function OL(e){Pl($L,"InterpolationFormat",e)}function Lr(e){Pl(DL,"PaddingMode",e)}function j7(e){Pl(PL,"PoolMode",e)}var Dd=[],Kb="/";function Ni(e,t){Dd.push(e);try{let n=t();return Dd.pop(),n}catch(n){throw Dd.pop(),n}}function ML(){return Dd.length===0?"":Dd.join(Kb)+Kb}function q7(e){if(!K7(e))throw new Error("Not a valid tensor name: '"+e+"'");return ML()+e}function X7(e){if(!K7(e))throw new Error("Not a valid tensor name: '"+e+"'");uu.has(e)||uu.set(e,0);let t=uu.get(e);if(uu.set(e,uu.get(e)+1),t>0){let n=`${e}_${t}`;return uu.set(n,1),n}else return e}var zL=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function K7(e){return!!e.match(zL)}function LL(e){return e===parseInt(e.toString(),10)}function $a(e,t,n){t==null&&(t=0),n==null&&(n=e.length);let r=1;for(let s=t;s<n;++s)r*=e[s];return r}function Eu(e){if(e.length===0)return Number.NaN;let t=Number.POSITIVE_INFINITY;for(let n=0;n<e.length;n++){let r=e[n];r<t&&(t=r)}return t}function Ua(e){if(e.length===0)return Number.NaN;let t=Number.NEGATIVE_INFINITY;for(let n=0;n<e.length;n++){let r=e[n];r>t&&(t=r)}return t}function gs(e,t){if(t<e)throw new j(`end (${t}) < begin (${e}) is forbidden.`);let n=[];for(let r=e;r<t;++r)n.push(r);return n}var rg;function an(){return rg==null&&(rg=zr().epsilon()),rg}function ys(){return"channelsLast"}function Ym(e,t){return ge(e,t)}function Np(e,t=-1){let n=e.shape.slice();return t<0&&(t=n.length+t+1),n.splice(t,0,1),H(e,n)}function BL(e,t){return K(()=>{if(e.shape.length!==2)throw new j(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);let n=Np(e,1);return Cg(n,[1,t,1])})}function WL(e){let t=[$a(e.shape)];return H(e,t)}function VL(e){if(e.rank<=1)throw new j(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);let t=[e.shape[0],$a(e.shape,1)];return H(e,t)}function Ei(e,t,n){return K(()=>{switch(e.rank){case 1:return Om(e,t,n);case 2:return iA(e,[t,0],[n,e.shape[1]]);case 3:return Dl(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return Fi(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return Pe(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return Pe(e,[t,0,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4],e.shape[5]]);default:throw new j(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}})}function sg(e,t,n){return K(()=>{switch(e.rank){case 1:return Om(e,t,n);case 2:return iA(e,[0,t],[e.shape[0],n]);case 3:return Dl(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return Fi(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new j(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Xh(e,t,n,r){return K(()=>{switch(e.rank){case 1:return Om(e,t,n);case 2:switch(r){case 1:return Ei(e,t,n);case 2:return sg(e,t,n);default:throw new j(`The axis is not within the rank of the tensor ${r}`)}case 3:switch(r){case 1:return Ei(e,t,n);case 2:return Dl(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return sg(e,t,n);default:throw new j(`The axis is not within the rank of the tensor ${r}`)}case 4:switch(r){case 1:return Ei(e,t,n);case 2:return Fi(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return Fi(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return sg(e,t,n);default:throw new j(`The axis is not within the rank of the tensor ${r}`)}default:throw new j(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function bA(e,t=-1){let n;return t<0&&(n=e[0].rank,n!==0?t=n:t=0),t===e[0].rank&&(t=-1),St(e,t)}function Zb(e,t){switch(e.rank){case 1:return Gw([e,t]);case 2:return pc([e,t],0);case 3:return Hw([e,t],0);case 4:return jw([e,t],0);default:throw new j(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function Cg(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new j(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return Gr(e,t)}function Jm(e,t=0,n=1,r,s){return h7(e,t,n,r,s)}function Rs(e,t,n,r){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 s=e.shape.slice(-1)[0],a=t.shape.slice(-2)[0];if(s!==a)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 Va.matMul({a:e,b:t,transposeA:!1,transposeB:!1,bias:r?Tg(e.rank,r,ys()):null,activation:n});{let s=e.shape.slice(),a=s.pop();e=H(e,[-1,a]);let o=t.shape.slice(),i=o.pop(),l=o.pop(),u=[...o,i],c=Array.from({length:t.rank},(f,m)=>m===0?t.rank-2:m<=t.rank-2?m-1:m);t=H(et(t,c),[l,-1]);let p=[...s,...u],d=!1,h=!1;return H(Va.matMul({a:e,b:t,transposeA:d,transposeB:h,bias:r?Tg(e.rank,r,ys()):null,activation:n}),p)}}function Z7(e,t,n){return K(()=>(Array.isArray(t)?t=Ct(t,"int32"):t=ge(t,"int32"),Cu(e,t,n)))}function Ep(e){return L(e,e)}function Tg(e,t,n){let r=t.shape;if(t.rank!==1&&t.rank!==e)throw new j(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(e===5){if(n==="channelsFirst")return r.length===1?H(t,[1,r[0],1,1,1]):H(t,[1,r[3],r[0],r[1],r[2]]);if(n==="channelsLast")return r.length===1?H(t,[1,1,1,1,r[0]]):H(t,[1].concat(r))}else if(e===4){if(n==="channelsFirst")return r.length===1?H(t,[1,r[0],1,1]):H(t,[1,r[2],r[0],r[1]]);if(n==="channelsLast")return r.length===1?H(t,[1,1,1,r[0]]):H(t,[1].concat(r))}else if(e===3){if(n==="channelsFirst")return r.length===1?H(t,[1,r[0],1]):H(t,[1,r[1],r[0]]);if(n==="channelsLast")return r.length===1?H(t,[1,1,r[0]]):H(t,[1].concat(r))}else if(e<3)return t;throw new j(`Unsupported input rank by biasAdd: ${t.rank}`)}function bs(e,t,n){return K(()=>(n==null&&(n=ys()),Ht(n),ue(e,Tg(e.rank,t,n))))}function UL(e,t=1){if(t!==1)throw new Ve(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return wp(e)}function GL(e){return K(()=>de(e,ue(rn(e),1)))}function Y7(e,t,n,r){return K(()=>T7(e,t,n,r))}function HL(e){return K(()=>{let t=ue(.5,L(.2,e));return yr(t,0,1)})}function Rp(e,t,n=!1){return n?e():t()}var jL=["fanIn","fanOut","fanAvg"],qL=["normal","uniform","truncatedNormal"];function XL(e){Pl(jL,"FanMode",e)}function KL(e){Pl(qL,"Distribution",e)}var Zr=class extends ce.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}},vA=class extends Zr{apply(e,t){return Ft(e,t)}};vA.className="Zeros";ce.registerClass(vA);var Qm=class extends Zr{apply(e,t){return gr(e,t)}};Qm.className="Ones";ce.registerClass(Qm);var wA=class extends Zr{constructor(e){if(super(),typeof e!="object")throw new j(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new j(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return K(()=>L(Ie(this.value),gr(e,t)))}getConfig(){return{value:this.value}}};wA.className="Constant";ce.registerClass(wA);var kA=class extends Zr{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 gc(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}};kA.className="RandomUniform";ce.registerClass(kA);var SA=class extends Zr{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 Jm(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};SA.className="RandomNormal";ce.registerClass(SA);var IA=class extends Zr{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 Lm(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};IA.className="TruncatedNormal";ce.registerClass(IA);var CA=class extends Zr{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 j("Identity matrix initializer can only be used for 2D square matrices.");return L(this.gain,Hy(e[0]))})}getConfig(){return{gain:this.gain}}};CA.className="Identity";ce.registerClass(CA);function ZL(e,t="channelsLast"){let n,r;if(Ht(t),e.length===2)n=e[0],r=e[1];else if([3,4,5].indexOf(e.length)!==-1){if(t==="channelsFirst"){let s=$a(e,2);n=e[1]*s,r=e[0]*s}else if(t==="channelsLast"){let s=$a(e,0,e.length-2);n=e[e.length-2]*s,r=e[e.length-1]*s}}else{let s=$a(e);n=Math.sqrt(s),r=Math.sqrt(s)}return[n,r]}var sr=class extends Zr{constructor(e){if(super(),e.scale<0)throw new j(`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,XL(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,KL(this.distribution),this.seed=e.seed}apply(e,t){let n=ZL(e),r=n[0],s=n[1],a=this.scale;if(this.mode==="fanIn"?a/=Math.max(1,r):this.mode==="fanOut"?a/=Math.max(1,s):a/=Math.max(1,(r+s)/2),this.distribution==="normal"){let o=Math.sqrt(a);if(t=t||"float32",t!=="float32"&&t!=="int32")throw new Ve(`${this.getClassName()} does not support dType ${t}.`);return Lm(e,0,o,t,this.seed)}else{let o=Math.sqrt(3*a);return gc(e,-o,o,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}};sr.className="VarianceScaling";ce.registerClass(sr);var e0=class extends sr{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return sr.className}};e0.className="GlorotUniform";ce.registerClass(e0);var t0=class extends sr{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return sr.className}};t0.className="GlorotNormal";ce.registerClass(t0);var n0=class extends sr{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return sr.className}};n0.className="HeNormal";ce.registerClass(n0);var r0=class extends sr{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return sr.className}};r0.className="HeUniform";ce.registerClass(r0);var s0=class extends sr{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return sr.className}};s0.className="LeCunNormal";ce.registerClass(s0);var a0=class extends sr{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return sr.className}};a0.className="LeCunNormal";ce.registerClass(a0);var TA=class extends Zr{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 n=e[0]>e[1]?[e[1],e[0]]:e,r=Jm(n,0,1,"float32"),s=M7.gramSchmidt(r);return e[0]>e[1]&&(s=et(s)),L(this.gain,s)})}getConfig(){return{gain:this.gain,seed:this.seed}}};TA.className="Orthogonal";ce.registerClass(TA);var Yb={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 Jb(e,t={}){return Tp(e,ce.SerializationMap.getMap().classNameMap,t,"initializer")}function Ot(e){return AA(e)}function Rt(e){if(typeof e=="string"){let t=e in Yb?Yb[e]:e;if(t==="GlorotNormal")return new t0;if(t==="GlorotUniform")return new e0;if(t==="HeNormal")return new n0;if(t==="HeUniform")return new r0;if(t==="LeCunNormal")return new s0;if(t==="LeCunUniform")return new a0;{let n={};return n.className=t,n.config={},Jb(n)}}else return e instanceof Zr?e:Jb(e)}function Ng(e){return Array.isArray(e)&&Array.isArray(e[0])}function Nf(e){return e.length===0?[]:Array.isArray(e[0])?e:[e]}function He(e){let t;if(Array.isArray(e)){if(e.length!==1)throw new j(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function mt(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(e.length===1)return e=e,e[0];throw new j(`Expected exactly 1 Shape; got ${e.length}`)}else return e}function Ef(e){let t=0;for(let n of e)n.shape.length===0?t+=1:t+=n.shape.reduce((r,s)=>r*s);return t}var Qb="Variable",J7=class{constructor(e,t="float32",n=Qb,r=!0,s=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=H7(),n=n==null?Qb:n,this.originalName=q7(n),this.name=X7(this.originalName),this.trainable_=r,this.constraint=s,this.val=w7(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),YL(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 YL(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}function Eg(e){return e.map(t=>t.read())}function NA(e){e.forEach(t=>{t[0].write(t[1])})}var Zt=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||{}}},cs=class{constructor(e,t,n,r,s,a,o){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=r,this.callArgs=s,this.outputTensorIndex=o,this.id=H7(),a!=null&&(this.originalName=q7(a),this.name=X7(this.originalName)),this.rank=t.length}},JL=0,o0=class{constructor(e,t){this.callArgs=t,this.id=JL++,this.outboundLayer=e.outboundLayer,this.inboundLayers=e.inboundLayers,this.nodeIndices=e.nodeIndices,this.tensorIndices=e.tensorIndices,this.inputTensors=e.inputTensors,this.outputTensors=e.outputTensors,this.inputMasks=e.inputMasks,this.outputMasks=e.outputMasks,this.inputShapes=e.inputShapes,this.outputShapes=e.outputShapes;for(let n of e.inboundLayers)n!=null&&n.outboundNodes.push(this);e.outboundLayer.inboundNodes.push(this)}getConfig(){let e=[];for(let t of this.inboundLayers)t!=null?e.push(t.name):e.push(null);return{outboundLayer:this.outboundLayer?this.outboundLayer.name:null,inboundLayers:e,nodeIndices:this.nodeIndices,tensorIndices:this.tensorIndices}}},QL=0,at=class extends ce.Serializable{constructor(e={}){super(),this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=QL++,this.activityRegularizer=null,this.inputSpec=null,this.supportsMasking=!1,this._trainableWeights=[],this._nonTrainableWeights=[],this._losses=[],this._updates=[],this._built=!1,this.inboundNodes=[],this.outboundNodes=[];let t=e.name;if(!t){let n=this.getClassName();t=qs(n)+"_"+Zm(n)}if(this.name=t,this.trainable_=e.trainable==null?!0:e.trainable,e.inputShape!=null||e.batchInputShape!=null){let n;if(e.batchInputShape!=null)n=e.batchInputShape;else if(e.inputShape!=null){let s=null;e.batchSize!=null&&(s=e.batchSize),n=[s].concat(e.inputShape)}this.batchInputShape=n;let r=e.dtype;r==null&&(r=e.inputDType),r==null&&(r="float32"),this.dtype=r}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 us(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new j(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return tr(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return tr(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new js(`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 js(`Layer ${this.name} is not connected, no input to return.`);return tr(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new js(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new js(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return tr(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 j(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let n=0;n<e.length;n++){let r=e[n],s=t[n];if(s==null)continue;let a=r.rank;if(s.ndim!=null&&a!==s.ndim)throw new j(`Input ${n} is incompatible with layer ${this.name}: expected ndim=${s.ndim}, found ndim=${a}`);if(s.maxNDim!=null&&a>s.maxNDim)throw new j(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${s.maxNDim}, found ndim=${a}`);if(s.minNDim!=null&&a<s.minNDim)throw new j(`Input ${n} is incompatible with layer ${this.name}: expected min_ndim=${s.minNDim}, found ndim=${a}.`);if(s.dtype!=null&&r.dtype!==s.dtype)throw new j(`Input ${n} is incompatible with layer ${this.name} : expected dtype=${s.dtype}, found dtype=${r.dtype}.`);if(s.axes){let o=r.shape;for(let i in s.axes){let l=Number(i),u=s.axes[i],c=l>=0?o[l]:o[o.length+l];if(u!=null&&[u,null].indexOf(c)===-1)throw new j(`Input ${n} is incompatible with layer ${this.name}: expected axis ${l} of input shape to have value ${u} but got shape ${o}.`)}}if(s.shape!=null)for(let o=0;o<s.shape.length;++o){let i=s.shape[o],l=r.shape[o];if(i!=null&&l!=null&&i!==l)throw new j(`Input ${n} is incompatible with layer ${this.name}: expected shape=${s.shape}, found shape=${r.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 n=It(e),r=!0;for(let a of n)if(!(a instanceof cs)){r=!1;break}let s=!0;for(let a of n)if(a instanceof cs){s=!1;break}if(r===s)throw new j("Arguments to apply() must be all SymbolicTensors or all Tensors");return Ni(this.name,()=>{if(!this.built){this.assertInputCompatibility(e);let a=[];for(let o of It(e))a.push(o.shape);this.build(tr(a)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&s&&(this._refCount=1)}if(this.assertInputCompatibility(e),s){let a=this.call(e,t),o=It(a),i=[];for(let l of o)n.indexOf(l)!==-1&&(l=l.clone()),i.push(l);if(a=tr(i),this.activityRegularizer!=null)throw new Ve("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return a}else{let a=eB(e),o=this.computeOutputShape(a),i,l=tB(e);if(this.warnOnIncompatibleInputShape(Array.isArray(e)?a[0]:a),o!=null&&o.length>0&&Array.isArray(o[0])?i=o.map((u,c)=>new cs(l,u,this,It(e),t,this.name,c)):i=new cs(l,o,this,It(e),t,this.name),this.addInboundNode(e,i,null,null,a,o,t),this._refCount++,this.activityRegularizer!=null)throw new Ve("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return i}})}warnOnIncompatibleInputShape(e){if(this.batchInputShape!=null)if(e.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(e)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let t=!1;this.batchInputShape.forEach((n,r)=>{n!=null&&e[r]!=null&&e[r]!==n&&(t=!0)}),t&&console.warn(`The shape of the input tensor (${JSON.stringify(e)}) does not match the expectation of layer ${this.name}: ${JSON.stringify(this.batchInputShape)}`)}}get outputShape(){if(this.inboundNodes==null||this.inboundNodes.length===0)throw new js(`The layer ${this.name} has never been called and thus has no defined output shape.`);let e=[];for(let t of this.inboundNodes){let n=JSON.stringify(t.outputShapes);e.indexOf(n)===-1&&e.push(n)}if(e.length===1){let t=this.inboundNodes[0].outputShapes;return Array.isArray(t)&&Array.isArray(t[0])&&t.length===1?t[0]:t}else throw new js(`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 us(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return Ef(this.weights)}build(e){this.built=!0}getWeights(e=!1){return Eg(e?this.trainableWeights:this.weights)}setWeights(e){K(()=>{let t=this.weights;if(t.length!==e.length)throw new j(`You called setWeights(weights) on layer "${this.name}" with a weight list of length ${e.length}, but the layer was expecting ${t.length} weights. Provided weights: ${e}...`);if(t.length===0)return;let n=[],r=Eg(t);for(let s=0;s<r.length;++s){let a=r[s],o=t[s],i=e[s];if(!w.arraysEqual(a.shape,i.shape))throw new j(`Layer weight shape ${a.shape} not compatible with provided weight shape ${i.shape}`);n.push([o,i])}NA(n)})}addWeight(e,t,n,r,s,a,o,i){if(this._addedWeightNames.indexOf(e)!==-1)throw new j(`Duplicate weight name ${e} for layer ${this.name}`);this._addedWeightNames.push(e),n==null&&(n="float32"),this.fastWeightInitDuringBuild&&(r=i!=null?i():Rt("zeros"));let l=r.apply(t,n),u=new J7(l,n,e,a,o);return l.dispose(),s!=null&&this.addLoss(()=>s.apply(u.read())),a==null&&(a=!0),a?this._trainableWeights.push(u):this._nonTrainableWeights.push(u),u}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){e==null||Array.isArray(e)&&e.length===0||(e=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(n=>{if(n!=null)throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`)});else throw new TypeError(`Layer ${this.name} does not support masking, but was passed an inputMask.`);return null}return t}addInboundNode(e,t,n,r,s,a,o=null){let i=It(e);t=It(t),n=It(n),r=It(r),s=Nf(s),a=Nf(a);let l=[],u=[],c=[];for(let p of i)l.push(p.sourceLayer),u.push(p.nodeIndex),c.push(p.tensorIndex);new o0({outboundLayer:this,inboundLayers:l,nodeIndices:u,tensorIndices:c,inputTensors:i,outputTensors:t,inputMasks:n,outputMasks:r,inputShapes:s,outputShapes:a},o);for(let p=0;p<t.length;p++)t[p].sourceLayer=this,t[p].nodeIndex=this.inboundNodes.length-1,t[p].tensorIndex=p}getConfig(){let e={name:this.name,trainable:this.trainable};return this.batchInputShape!=null&&(e.batchInputShape=this.batchInputShape),this.dtype!=null&&(e.dtype=this.dtype),e}disposeWeights(){return this.weights.forEach(e=>e.dispose()),this.weights.length}assertNotDisposed(){if(this._refCount===0)throw new Error(`Layer '${this.name}' is already disposed.`)}dispose(){if(!this.built)throw new Error(`Cannot dispose Layer ${this.name} because it has not been built yet.`);if(this._refCount===null)throw new Error(`Cannot dispose Layer ${this.name} because it has not been used yet.`);this.assertNotDisposed();let e=0;return--this._refCount===0&&(e=this.disposeWeights()),{refCountAfterDispose:this._refCount,numDisposedVariables:e}}};function eB(e){e=It(e);let t=[];for(let n of e)t.push(n.shape);return tr(t)}function tB(e){return"float32"}function Q7(e,t,n){if((t==null||n!=null&&n>0)&&(t=e.sourceLayer,n=e.nodeIndex),t.inboundNodes.length===0)return[e];{let r=t.inboundNodes[n];if(r.inboundLayers.length===0)return r.inputTensors;{let s=[];for(let a=0;a<r.inboundLayers.length;a++){let o=r.inputTensors[a],i=r.inboundLayers[a],l=r.nodeIndices[a],u=Q7(o,i,l);for(let c of u)s.indexOf(c)===-1&&s.push(c)}return s}}}var xc=class extends at{constructor(e){if(super({dtype:e.dtype,name:e.name!=null?e.name:Zm("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 j("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 j("An InputLayer should be passed either a `batchInputShape` or an `inputShape`.");t=[e.batchSize].concat(e.inputShape)}else if(e.batchSize!=null)throw new j("Cannot specify batchSize if batchInputShape is specified when creating an InputLayer.");let n=e.dtype||"float32";this.batchInputShape=t,this.dtype=n,this.inputSpec=[{shape:t}];let r=new cs(this.dtype,this.batchInputShape,this,[],{},this.name);r.nodeIndex=0,r.tensorIndex=0,new o0({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:[r],outputTensors:[r],inputMasks:[null],outputMasks:[null],inputShapes:[t],outputShapes:[t]})}apply(e,t){throw new j(`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}}};xc.className="InputLayer";ce.registerClass(xc);function e6(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 j("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 n=e.dtype;return n==null&&(n="float32"),new xc({batchInputShape:t,name:e.name,dtype:n,sparse:e.sparse}).inboundNodes[0].outputTensors[0]}function nB(e,t){if(e.dtype==null||e.dtype===t.dtype)return t;try{return ge(t,e.dtype)}catch(n){throw new j(`The dtype of the feed (${t.dtype}) can not be cast to the dtype of the key '${e.name}' (${e.dtype}).`)}}var Ii=class{constructor(e){if(this.id2Value={},this.id2Mask={},this.name2Id={},e instanceof Ii)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,n){if(this.id2Value[e.id]==null)this.id2Value[e.id]=nB(e,t),this.name2Id[e.name]=e.id,n!=null&&(this.id2Mask[e.id]=n);else throw new j(`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 cs){if(this.id2Value[e.id]==null)throw new j(`Nonexistent key: ${e.name}`);return this.id2Value[e.id]}else{let t=this.name2Id[e];if(t==null)throw new j(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Value[t]}}getMask(e){if(e instanceof cs){if(this.id2Value[e.id]==null)throw new j(`Nonexistent key: ${e.name}`);return this.id2Mask[e.id]}else{let t=this.name2Id[e];if(t==null)throw new j(`Feed dict has no SymbolicTensor name: ${e}`);return this.id2Mask[t]}}disposeMasks(){this.id2Mask!=null&&ne(this.id2Mask)}},Rf=new V7,_f=new V7;function rB(e){Rf!=null&&Rf.setMaxEntries(e),_f!=null&&_f.setMaxEntries(e)}function Sd(e,t,n,r){let s=n==null?!1:n.training,a=Array.isArray(e),o=a?e:[e],i=o.map(f=>f.name),l=[],u=t.names();for(let f of i)u.indexOf(f)!==-1?l.push(t.getValue(f)):l.push(null);r!=null&&(r.maxNumTensors=-1/0,r.minNumTensors=1/0);let c=i.join(",")+"|"+t.names().join(","),p=Rf.get(c),d;if(p==null){let f=sB(o,t);p=f.sorted,d=f.recipientCounts,Rf.put(c,p),_f.put(c,d)}d={},s||Object.assign(d,_f.get(c));let h=new Ii(t);for(let f=0;f<p.length;++f){if(r!=null){let R=Sf().numTensors;R>r.maxNumTensors&&(r.maxNumTensors=R),R<r.minNumTensors&&(r.minNumTensors=R)}let m=p[f],g=m.sourceLayer;if(g instanceof xc)continue;let y=[],x=[],A=[],b=!1;for(let R of m.inputs){let P=h.getValue(R),_=h.getMask(R);y.push(P),x.push(_),_!=null&&(b=!0),s||(d[R.name]--,d[R.name]===0&&!t.hasKey(R)&&i.indexOf(R.name)===-1&&!P.isDisposed&&R.sourceLayer.stateful!==!0&&A.push(P))}b&&(n=n||{},n.mask=x[0]);let v=It(g.apply(y,n)),S=null;g.supportsMasking&&(S=g.computeMask(y,x));let I=oB(m),E=Array.isArray(I)?I:[I];for(let R=0;R<E.length;++R){h.hasKey(E[R])||h.add(E[R],v[R],Array.isArray(S)?S[0]:S);let P=i.indexOf(E[R].name);P!==-1&&(l[P]=v[R])}s||ne(A)}return h.disposeMasks(),a?l:l[0]}function sB(e,t){w.assert(e!=null&&e.length>0,()=>"Expected at least one fetch, got none");let n=[],r={};if(e.length===1){let s=ev(e[0],t);n=s.sorted,r=s.recipientMap}else{let s=new Set;for(let a of e){let{sorted:o,recipientMap:i}=ev(a,t);for(let l of o)s.has(l.name)||(n.push(l),s.add(l.name));for(let l in i)r[l]==null&&(r[l]=new Set),i[l].forEach(u=>r[l].add(u))}}return{sorted:n,recipientCounts:aB(r)}}function aB(e){let t={};for(let n in e)t[n]=e[n].size;return t}function ev(e,t){let n=new Set,r=[],s={};for(let i of t.names())n.add(i);let a=[],o=[];for(a.push(e);a.length>0;){let i=a[a.length-1];if(n.has(i.name)){a.pop();continue}let l=o[o.length-1]===a.length-1;if(i.inputs.length===0||l)a.pop(),r.push(i),n.add(i.name),l&&o.pop();else{o.push(a.length-1);for(let u of i.inputs)s[u.name]==null&&(s[u.name]=new Set),s[u.name].add(i.name),!n.has(u.name)&&a.push(u)}}return{sorted:r,recipientMap:s}}function oB(e){let t;if(e.sourceLayer.inboundNodes.length===1)t=e.sourceLayer.output;else{let n=null;for(let r=0;r<e.sourceLayer.inboundNodes.length;++r)for(let s of e.sourceLayer.inboundNodes[r].outputTensors)if(s.id===e.id){n=r;break}t=e.sourceLayer.getOutputAt(n)}return t}var iB=Y();iB.registerFlag("TOPOLOGICAL_SORT_CACHE_MAX_ENTRIES",()=>100,rB);var t6={kernelName:Gi,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,Ip(ge(n,"float32"),-1))}}},lB={kernelName:zu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let r=xt(ge(n,"float32")),s=En(he(Ie(1),r));return zt(de(e,s))}}}},uB={kernelName:Lu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let r=En(he(xt(ge(n,"float32")),1));return de(e,r)}}}},cB={kernelName:ea,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=vt(n.shape,r.shape);return{a:()=>{let i=e,l=Jt(n.shape,s);return l.length>0&&(i=ke(i,l)),H(i,n.shape)},b:()=>{let i=e,l=Jt(r.shape,s);return l.length>0&&(i=ke(i,l)),H(i,r.shape)}}}},dB={kernelName:Za,saveAllInputs:!0,gradFunc:(e,t)=>{let n={};return t.forEach((r,s)=>{n[s]=()=>e.clone()}),n}},pB={kernelName:Ya,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>st(n)}}},hB={kernelName:Vu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>st(n)}}},fB={kernelName:Uu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>de(e,En(he(Ie(1),xt(ge(n,"float32")))))}}},mB={kernelName:Gu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let r=En(ue(Ie(1),xt(ge(n,"float32"))));return de(e,r)}}}},gB={kernelName:qu,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=vt(n.shape,r.shape);return{a:()=>{let i=ue(xt(n),xt(r)),l=L(e,de(r,i)),u=Jt(n.shape,s);return u.length>0&&(l=ke(l,u)),H(l,n.shape)},b:()=>{let i=ue(xt(n),xt(r)),l=zt(L(e,de(n,i))),u=Jt(r.shape,s);return u.length>0&&(l=ke(l,u)),H(l,r.shape)}}}},yB={kernelName:Hu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>de(e,ue(xt(ge(n,"float32")),1))}}},AB={kernelName:ju,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>de(e,he(Ie(1),xt(ge(n,"float32"))))}}};function xB(e,t,n,r,s,a){let o=$(e,"dy","avgPool3dGrad"),i=$(t,"input","avgPool3dGrad"),l=o,u=i,c=!1;i.rank===4&&(c=!0,l=H(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),u=H(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),M(l.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`),M(u.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${u.rank}.`),Xn("avgPool3dGrad",s,a);let p={dy:l,input:u},d={filterSize:n,strides:r,pad:s,dimRoundingMode:a},h=B.runKernel(Jf,p,d);return c?H(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var bB=V({avgPool3dGrad_:xB}),vB={kernelName:Yd,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,{filterSize:s,strides:a,pad:o,dimRoundingMode:i}=n;return{x:()=>bB(e,r,s,a,o,i)}}};function wB(e,t,n,r,s){let a=$(e,"dy","avgPoolGrad"),o=$(t,"input","avgPoolGrad");M(o.rank===a.rank,()=>`Rank of input (${o.rank}) does not match rank of dy (${a.rank})`);let i=o,l=a,u=!1;o.rank===3&&(u=!0,i=H(o,[1,o.shape[0],o.shape[1],o.shape[2]]),l=H(a,[1,a.shape[0],a.shape[1],a.shape[2]])),M(l.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`),M(i.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${i.rank}.`);let c={dy:l,input:i},p={filterSize:n,strides:r,pad:s},d=B.runKernel(Yf,c,p);return u?H(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var kB=V({avgPoolGrad_:wB}),SB={kernelName:Ja,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,{filterSize:s,strides:a,pad:o}=n;return{x:()=>kB(e,r,s,a,o)}}},IB={kernelName:Qa,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{let[r,s]=t,{transposeA:a,transposeB:o}=n;return!a&&!o?{a:()=>Ye(e,s,!1,!0),b:()=>Ye(r,e,!0,!1)}:!a&&o?{a:()=>Ye(e,s,!1,!1),b:()=>Ye(e,r,!0,!1)}:a&&!o?{a:()=>Ye(s,e,!1,!0),b:()=>Ye(r,e,!1,!1)}:{a:()=>Ye(s,e,!0,!0),b:()=>Ye(e,r,!0,!0)}}},CB={kernelName:Hi,gradFunc:(e,t,n)=>{let{blockShape:r,crops:s}=n;return{x:()=>Pm(e,r,s)}}},TB={kernelName:D4,gradFunc:(e,t,n)=>{let r=n,s=r.inputShape,a=r.shape,o=Array.from(a);for(let l=s.length-1;l>=0;l--)if(s[l]===a[l])o[l]=1;else if(s[l]!==1)throw new Error(`broadcastTo(): [${s}] cannot be broadcast to [${a}].`);let i=[];for(let l=0;l<o.length;l++)o[l]>1&&i.push(l);return{x:()=>ke(e,i,!0)}}},NB={kernelName:eo,gradFunc:e=>({x:()=>e.clone()})},EB={kernelName:to,gradFunc:e=>({x:()=>st(e)})},RB={kernelName:ta,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,{clipValueMin:s,clipValueMax:a}=n;return{x:()=>Hn(ms(_l(r,s),$l(r,a)),e,st(e))}}},_B={kernelName:Qd,inputsToSave:["x"],gradFunc:t6.gradFunc},$B={kernelName:ji,saveAllInputs:!0,gradFunc:(e,t,n)=>{let r=t.map(l=>l.shape),{axis:s}=n,a=jr(s,t[0].shape)[0],o=r.map(l=>l[a]);return Yt(e,o,a).map(l=>()=>l)}},DB={kernelName:no,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[r,s]=t,{dilations:a,strides:o,pad:i,dataFormat:l}=n;return M(za(a),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`),{x:()=>By(r.shape,e,s,o,i,l),filter:()=>fA(r,e,s.shape,o,i,l)}}},PB={kernelName:ro,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{let[r,s]=t,{strides:a,pad:o,dataFormat:i,dimRoundingMode:l}=n;return{dy:()=>La(e,s,a,o,i,1,l),filter:()=>fA(e,r,s.shape,a,o,i,l)}}};function FB(e,t,n,r,s){let a=e;e.rank===4&&(a=H(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let o=t;o.rank===4&&(o=H(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),M(a.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${a.shape}.`),M(o.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${o.shape}.`),M(n.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`),M(a.shape[4]===n[3],()=>`Error in conv3dDerFilter: depth of input ${a.shape[4]}) must match input depth in filter (${n[3]}.`),M(o.shape[4]===n[4],()=>`Error in conv3dDerFilter: depth of dy (${o.shape[4]}) must match output depth for filter (${n[4]}).`);let i={x:a,dy:o},l={strides:r,pad:s,filterShape:n};return B.runKernel(nm,i,l)}var OB=V({conv3DBackpropFilter_:FB}),MB={kernelName:ep,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:r,strides:s,pad:a}=n;M(za(r),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${r}'`);let[o,i]=t;return{x:()=>qw(o.shape,e,i,s,a),filter:()=>OB(o,e,i.shape,s,a)}}},zB={kernelName:so,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(zt(aA(ge(n,"float32"))),e)}}},LB={kernelName:ao,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(oA(ge(n,"float32")),e)}}},BB={kernelName:oo,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,{axis:s,exclusive:a,reverse:o}=n;return{x:()=>{let i=l7([s],r.rank),l=Gy(e,s,a,!o);return i!=null&&(l=et(l,i)),l}}}},WB={kernelName:io,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:r,strides:s,pad:a,dimRoundingMode:o}=n,i=r==null?[1,1]:r;M(za(i),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${i}'`);let[l,u]=t;return M(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),M(u.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${u.rank}.`),M(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]}.`),M(Fs(s,i),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${s} and dilations '${i}'.`),Xn("depthwiseConv2d",a,o),{x:()=>R7(l.shape,e,u,s,a,i,o),filter:()=>E7(l,e,u.shape,s,a,i,o)}}},VB={kernelName:tp,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[r,s]=t,a={x:r,filter:s,dy:e},o={x:r,filter:s,dy:e};return{x:()=>B.runKernel(Af,a,n),filter:()=>B.runKernel(xf,o,n)}}},UB={kernelName:uo,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t,r={dy:e,y:n};return{x:()=>B.runKernel(lm,r)}}},GB={kernelName:Xu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,r=L($r(zt(xt(n))),2/Math.sqrt(Math.PI));return{x:()=>L(e,r)}}},HB={kernelName:co,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,n)}}},jB={kernelName:Yi,inputsToSave:["input"],gradFunc:(e,t)=>{let[n]=t;return{input:()=>H(e,n.shape)}}},qB={kernelName:Ji,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,$r(n))}}},XB={kernelName:po,gradFunc:e=>({x:()=>st(e)})},KB={kernelName:ho,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=vt(n.shape,r.shape);return{a:()=>{let i=de(e,ge(r,"float32")),l=Jt(n.shape,s);return l.length>0?H(ke(i,l),n.shape):i},b:()=>{let i=L(e,ge(n,"float32")),l=Jt(r.shape,s);l.length>0&&(i=H(ke(i,l),r.shape));let u=xt(r);return zt(de(i,ge(u,"float32")))}}}},ZB={kernelName:fo,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{let{varianceEpsilon:r}=n,[s,a,o,i]=t,l=i==null?Ie(1):i,u=Jt(a.shape,s.shape),c=[];if(a.rank===1){for(let b=0;b<s.shape.length-1;++b)c.push(s.shape[b]);c.push(1)}let p=he(s,a),d=L(e,l),h=rA(ue(o,Ie(r))),f=L(L(L(h,h),h),Ie(-.5));return{x:()=>a.rank===1?H(L(L(e,Gr(H(h,[1,1,1,a.shape[0]]),c)),l),s.shape):H(L(L(e,h),l),s.shape),mean:()=>{let b=L(L(h,Ie(-1)),d);return a.rank===1&&(b=ke(b,u)),H(b,a.shape)},variance:()=>{let b=L(L(f,p),d);return a.rank===1&&(b=ke(b,u)),H(b,a.shape)},scale:()=>{let b=L(p,h),v=L(e,b);return a.rank===1&&(v=ke(v,u)),H(v,a.shape)},offset:()=>{let b=e;return a.rank===1&&(b=ke(b,u)),H(b,a.shape)}}}},YB={kernelName:el,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{let[r,s]=t,{axis:a}=n,o=jr(a,r.shape)[0];return{x:()=>{let l=r.shape,u=s.size,c=l.slice(0,o),p=c.length,d=l.slice(a,l.length).slice(1),h=d.length,f=tv(0,p),m=tv(p+1,p+1+h),g=nv([c,[u],d]),y=H(e,g),x=H(s,[u]),A=nv([[p],f,m]),b=et(y,A),v=v7(b,x,r.shape[o]),S=Ky(A);return v=et(v,S),v},indices:()=>s}}};function tv(e,t){let n=[];for(let r=e;r<t;++r)n.push(r);return n}function nv(e){let t=[];for(let n=0;n<e.length;++n)for(let r=0;r<e[n].length;++r)t.push(e[n][r]);return t}var JB={kernelName:mo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t;return{a:()=>st(n),b:()=>st(r)}}},QB={kernelName:go,gradFunc:e=>({x:()=>ge(e,"float32")})},eW={kernelName:Zu,gradFunc:e=>({x:()=>st(e)})},tW={kernelName:Yu,gradFunc:e=>({x:()=>st(e)})},nW={kernelName:Ju,gradFunc:e=>({x:()=>st(e)})},rW={kernelName:yo,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,{alpha:s}=n,a=Ar(r,0);return{x:()=>Hn(a,e,L(e,s))}}},sW={kernelName:Qu,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>de(e,ue(n,1))}}},aW={kernelName:Ao,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>de(e,ge(n,"float32"))}}},oW={kernelName:P4,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[r]=t,{axis:s}=n;return{logits:()=>{let o=$r(r);return he(e,L(ke(e,s,!0),o))}}}};function iW(e,t,n,r=5,s=1,a=1,o=.5){let i={x:e,y:t,dy:n},l={depthRadius:r,bias:s,alpha:a,beta:o};return B.runKernel(pm,i,l)}var lW=V({localResponseNormalizationBackprop_:iW}),uW={kernelName:ap,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[r,s]=t,{depthRadius:a,bias:o,alpha:i,beta:l}=n;return{x:()=>lW(r,s,e,a,o,i,l)}}};function n6(e,t,n,r){return t.rank<n.rank&&(t=H(t,Pi(t.shape,r))),e.rank<n.rank&&(e=H(e,Pi(e.shape,r))),{x:()=>L(e,ge(_r(n,t),e.dtype))}}var rv={kernelName:xo,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let r=n,{reductionIndices:s}=r,a=t[0],o=t[1],i=jr(s,a.shape),l=n6(e,o,a,i);return{x:()=>l.x()}}},cW={kernelName:bo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t;return{a:()=>L(e,ge(_l(n,r),"float32")),b:()=>L(e,ge(jy(n,r),"float32"))}}};function dW(e,t,n,r,s,a,o){let i=$(e,"dy","maxPool3dGrad"),l=$(t,"input","maxPool3dGrad"),u=$(n,"output","maxPool3dGrad"),c=i,p=l,d=u,h=!1;l.rank===4&&(h=!0,c=H(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),p=H(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),d=H(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]])),M(c.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${c.rank}.`),M(p.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${p.rank}.`),M(d.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${d.rank}.`),Xn("maxPool3dGrad",a,o);let f={dy:c,input:p,output:d},m={filterSize:r,strides:s,pad:a,dimRoundingMode:o},g=B.runKernel(fm,f,m);return h?H(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}var pW=V({maxPool3dGrad_:dW}),hW={kernelName:op,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[r,s]=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=n;return{x:()=>pW(e,r,s,a,o,i,l)}}};function fW(e,t,n,r,s,a,o){let i=$(e,"dy","maxPoolGrad"),l=$(t,"input","maxPoolGrad"),u=$(n,"output","maxPoolGrad");M(l.rank===i.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${i.rank})`),M(i.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${i.rank}.`),M(l.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`),Xn("maxPoolGrad",a,o);let c={dy:i,input:l,output:u},p={filterSize:r,strides:s,pad:a,dimRoundingMode:o};return B.runKernel(hm,c,p)}var mW=V({maxPoolGrad_:fW}),gW={kernelName:vo,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[r,s]=t,{filterSize:a,strides:o,pad:i}=n;return{x:()=>mW(e,r,s,a,o,i)}}},yW={kernelName:wo,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,{axis:s}=n,a=jr(s,r.shape),i=i7(r.shape,a)[1],l=Tt(i);return{x:()=>{let c=r.shape.slice();a.forEach(h=>{c[h]=1});let p=H(e,c);return de(L(p,gr(r.shape,"float32")),l)}}}},AW={kernelName:ko,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let r=n,{axis:s}=r,[a,o]=t,i=jr(s,a.shape),l=n6(e,o,a,i);return{x:()=>l.x()}}},xW={kernelName:So,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t;return{a:()=>L(e,ge($l(n,r),"float32")),b:()=>L(e,ge(Ar(n,r),"float32"))}}},bW={kernelName:Io,inputsToSave:["x"],gradFunc:(e,t,n)=>{let r=t[0],{paddings:s}=n,a=s.map(o=>o[0]);return{x:()=>Pe(e,a,r.shape)}}},vW={kernelName:tc,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=vt(n.shape,r.shape);return{a:()=>{let i=Jt(n.shape,s);return i.length>0?H(ke(e,i),n.shape):e},b:()=>{let i=L(e,zt(kp(de(n,r)))),l=Jt(r.shape,s);return l.length>0?H(ke(i,l),r.shape):i}}}},wW={kernelName:Co,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=vt(n.shape,r.shape);return{a:()=>{let i=L(e,ge(r,"float32")),l=Jt(n.shape,s);return l.length>0?H(ke(i,l),n.shape):i},b:()=>{let i=L(e,ge(n,"float32")),l=Jt(r.shape,s);return l.length>0?H(ke(i,l),r.shape):i}}}},kW={kernelName:ol,gradFunc:e=>({x:()=>zt(e)})},SW={kernelName:dl,inputsToSave:["indices"],gradFunc:(e,t)=>{let n=t[0];return{indices:()=>Ft(n.shape,"float32")}}},IW={kernelName:cl,gradFunc:e=>({x:()=>st(e)})},CW={kernelName:pl,saveAllInputs:!0,gradFunc:(e,t,n)=>{let{axis:r}=n;return rr(e,r).map(a=>()=>a)}},sv={kernelName:To,inputsToSave:["x"],gradFunc:(e,t,n)=>{let r=t[0],{paddings:s}=n,a=s.map(o=>o[0]);return{x:()=>Pe(e,a,r.shape)}}},TW={kernelName:No,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{let[n,r,s]=t,a=n,o=r,i=vt(a.shape,o.shape);return{a:()=>{let c=ge(o,"float32"),p=L(e,L(c,Wa(a,he(c,Ie(1))))),d=Jt(a.shape,i);return d.length>0&&(p=ke(p,d)),H(p,a.shape)},b:()=>{let c=Ar(a,0),p=Hn(c,Dr(a),st(a)),d=L(e,L(s,p)),h=Jt(o.shape,i);return h.length>0&&(d=ke(d,h)),H(d,o.shape)}}}},NW={kernelName:Eo,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{let[n,r]=t,s=Ar(n,0);return{x:()=>Hn(s,e,L(e,r)),alpha:()=>{let a=Hn(s,st(e),L(e,n)),o=Jt(r.shape,e.shape);return o.length>0&&(a=ke(a,o)),H(a,r.shape)}}}};function EW(e,t,n){let r=e.shape.slice();r[n]=1;let s=H(t,r),a=Tf(e,n,!0,!1),o=Tf(e,n,!0,!0),i=L(a,o);return L(s,i)}function RW(e,t,n){let r=e.shape.length,s=r-n.length,a=C.getAxesPermutation(n,r),o=e;a!=null&&(o=et(e,a));let i=o.shape.slice(),u=i.splice(r-n.length,n.length).reduce((d,h)=>d*h,1);i.push(u);let c=o.reshape(i),p=EW(c,t,s);if(p=p.reshape(o.shape),a!=null){let d=C.getUndoAxesPermutation(a);p=et(p,d)}return p}var _W={kernelName:Ro,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,{axis:s}=n,a=[];return s==null?a=r.shape.map((o,i)=>i):typeof s=="number"?a=[s]:a=s,{x:()=>RW(r,e,a)}}},$W={kernelName:lo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=vt(n.shape,r.shape);return{a:()=>{let i=de(e,ge(r,"float32")),l=Jt(n.shape,s);return l.length>0?H(ke(i,l),n.shape):i},b:()=>{let i=L(e,ge(n,"float32")),l=Jt(r.shape,s);l.length>0&&(i=H(ke(i,l),r.shape));let u=xt(r);return zt(de(i,ge(u,"float32")))}}}},DW={kernelName:sc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>de(e,zt(xt(n)))}}},PW={kernelName:Do,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,r=L($l(n,6),Ip(n));return{x:()=>L(e,ge(r,"float32"))}}},FW={kernelName:_o,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,ge(Ip(n),"float32"))}}},OW={kernelName:hl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>H(e,n.shape)}}},MW={kernelName:$o,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[r]=t,s={dy:e,images:r};return{images:()=>B.runKernel(Am,s,n)}}},zW={kernelName:ac,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[r]=t,s={dy:e,images:r};return{images:()=>B.runKernel(ym,s,n)}}},LW={kernelName:fl,gradFunc:(e,t,n)=>{let{dims:r}=n,s=jr(r,e.shape);return{x:()=>Fr(e,s)}}},BW={kernelName:ml,gradFunc:e=>({x:()=>st(e)})},WW={kernelName:Po,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>zt(de(e,L(Wa(n,1.5),2)))}}},VW={kernelName:yl,inputsToSave:["condition"],gradFunc:(e,t)=>{let[n]=t;return{condition:()=>ge(st(n),"float32"),t:()=>L(e,ge(n,e.dtype)),e:()=>L(e,ge(_m(n),e.dtype))}}},UW={kernelName:oc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let r=Ar(n,Ie(0)),s=Ie(z7),a=Ie(L7),o=L(e,a),i=L(L(e,s),$r(ge(n,"float32")));return Hn(r,o,i)}}}},GW={kernelName:Oo,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,L(n,he(Ie(1),n)))}}},HW={kernelName:ic,gradFunc:e=>({x:()=>st(e)})},jW={kernelName:Fo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(Cm(ge(n,"float32")),e)}}},qW={kernelName:xl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(Uy(ge(n,"float32")),e)}}},XW={kernelName:Al,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,{begin:s,size:a}=n,o=r.shape,[i,l]=kw(r,s,a),u=[];for(let c=0;c<e.rank;c++)u.push([i[c],o[c]-i[c]-l[c]]);return{x:()=>Xr(e,u)}}},KW={kernelName:Lo,outputsToSave:[!0],gradFunc:(e,t,n)=>{let[r]=t,{dim:s}=n,a=!0,o=L(e,r);return{logits:()=>he(o,L(ke(o,[s],a),r))}}},ZW={kernelName:lc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,Tn(n))}}},av={kernelName:bl,gradFunc:(e,t,n)=>{let{blockShape:r,paddings:s}=n;return{x:()=>Im(e,r,s)}}},ov={kernelName:vl,gradFunc:(e,t,n)=>{let{axis:r}=n;return{x:()=>St(e,r)}}},YW={kernelName:Mo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>de(e,L(En(ge(n,"float32")),2))}}},JW={kernelName:cc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(e,L(ge(n,"float32"),2))}}},QW={kernelName:Bo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=Ie(2);return{a:()=>L(e,L(s,he(n,r))),b:()=>L(e,L(s,he(r,n)))}}},eV={kernelName:Go,gradFunc:e=>({x:()=>st(e)})},tV={kernelName:Wo,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,r]=t,s=vt(n.shape,r.shape);return{a:()=>{let i=e,l=Jt(n.shape,s);return l.length>0&&(i=ke(i,l)),H(i,n.shape)},b:()=>{let i=e,l=Jt(r.shape,s);return l.length>0&&(i=ke(i,l)),H(zt(i),r.shape)}}}},nV={kernelName:zo,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,s=r.shape.slice(),{axis:a}=n;jr(a,r.shape).forEach(u=>{s[u]=1});let i=H(e,s),l=L(i,gr(r.shape,"float32"));return{x:()=>l}}},rV={kernelName:kl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>de(e,xt(Cm(n)))}}},sV={kernelName:Vo,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>L(he(Ie(1),xt(n)),e)}}},aV={kernelName:na,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[r]=t,{reps:s}=n;return{x:()=>{let o=st(r);if(r.rank===1)for(let i=0;i<s[0];++i)o=ue(o,Pe(e,[i*r.shape[0]],[r.shape[0]]));else if(r.rank===2)for(let i=0;i<s[0];++i)for(let l=0;l<s[1];++l)o=ue(o,Pe(e,[i*r.shape[0],l*r.shape[1]],[r.shape[0],r.shape[1]]));else if(r.rank===3)for(let i=0;i<s[0];++i)for(let l=0;l<s[1];++l)for(let u=0;u<s[2];++u)o=ue(o,Pe(e,[i*r.shape[0],l*r.shape[1],u*r.shape[2]],[r.shape[0],r.shape[1],r.shape[2]]));else if(r.rank===4)for(let i=0;i<s[0];++i)for(let l=0;l<s[1];++l)for(let u=0;u<s[2];++u)for(let c=0;c<s[3];++c)o=ue(o,Pe(e,[i*r.shape[0],l*r.shape[1],u*r.shape[2],c*r.shape[3]],[r.shape[0],r.shape[1],r.shape[2],r.shape[3]]));else throw new Error(`Gradient for tile operation is not implemented for rank-${r.rank} tensors yet.`);return o}}}},oV={kernelName:Uo,gradFunc:(e,t,n)=>{let r=n,{perm:s}=r,a=Ky(s);return{x:()=>et(e,a)}}},iV={kernelName:Cl,gradFunc:(e,t,n)=>{let r=n,{axis:s}=r;return{value:()=>cn(e,s)}}},lV={kernelName:hp,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>uV(e,n)}}};function uV(e,t){let n=ra(t,st(t)),r=Cu(e,n),s=_l(t,Ie(0,"int32")),a=r.rank-s.rank;for(let i=0;i<a;++i)s=Kt(s,i+1);s=ms(s,gr(r.shape,"bool"));let o=st(r);return Hn(s,r,o)}var cV={kernelName:Tl,gradFunc:e=>({x:()=>st(e)})},dV=[t6,lB,uB,cB,dB,pB,hB,fB,mB,gB,yB,AB,vB,SB,IB,CB,TB,NB,EB,RB,_B,$B,PB,DB,MB,zB,LB,BB,WB,VB,$W,UB,GB,HB,jB,qB,KB,XB,ZB,YB,JB,QB,eW,tW,nW,rW,sW,aW,oW,uW,rv,rv,cW,hW,gW,yW,AW,xW,bW,vW,wW,kW,SW,IW,CW,sv,sv,TW,NW,_W,DW,PW,FW,OW,MW,zW,LW,BW,WW,VW,UW,GW,HW,jW,qW,XW,KW,ZW,av,av,ov,ov,YW,QW,JW,eV,tV,nV,rV,sV,aV,oV,iV,lV,cV];for(let e of dV)F4(e);var r6={};Le(r6,{maxNorm:()=>pV,minMaxNorm:()=>mV,nonNeg:()=>fV,unitNorm:()=>hV});function EA(e,t){return K(()=>En(ke(L(e,e),t,!0)))}var _p=class extends ce.Serializable{getConfig(){return{}}},RA=class extends _p{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=EA(e,this.axis),n=yr(t,0,this.maxValue);return L(e,de(n,ue(an(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};RA.className="MaxNorm";ce.registerClass(RA);var _A=class extends _p{constructor(e){super(),this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return K(()=>de(e,ue(an(),EA(e,this.axis))))}getConfig(){return{axis:this.axis}}};_A.className="UnitNorm";ce.registerClass(_A);var $A=class extends _p{apply(e){return Os(e)}};$A.className="NonNeg";ce.registerClass($A);var DA=class extends _p{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=EA(e,this.axis),n=ue(L(this.rate,yr(t,this.minValue,this.maxValue)),L(1-this.rate,t));return L(e,de(n,ue(an(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};DA.className="MinMaxNorm";ce.registerClass(DA);var iv={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function ln(e){return AA(e)}function lv(e,t={}){return Tp(e,ce.SerializationMap.getMap().classNameMap,t,"constraint")}function un(e){if(e==null)return null;if(typeof e=="string"){let n={className:e in iv?iv[e]:e,config:{}};return lv(n)}else return e instanceof _p?e:lv(e)}function pV(e){return new RA(e)}function hV(e){return new _A(e)}function fV(){return new $A}function mV(e){return new DA(e)}var s6={};Le(s6,{constant:()=>AV,glorotNormal:()=>IV,glorotUniform:()=>SV,heNormal:()=>CV,heUniform:()=>TV,identity:()=>wV,leCunNormal:()=>NV,leCunUniform:()=>EV,ones:()=>yV,orthogonal:()=>RV,randomNormal:()=>bV,randomUniform:()=>xV,truncatedNormal:()=>vV,varianceScaling:()=>kV,zeros:()=>gV});function gV(){return new vA}function yV(){return new Qm}function AV(e){return new wA(e)}function xV(e){return new kA(e)}function bV(e){return new SA(e)}function vV(e){return new IA(e)}function wV(e){return new CA(e)}function kV(e){return new sr(e)}function SV(e){return new e0(e)}function IV(e){return new t0(e)}function CV(e){return new n0(e)}function TV(e){return new r0(e)}function NV(e){return new s0(e)}function EV(e){return new a0(e)}function RV(e){return new TA(e)}var a6={};Le(a6,{Layer:()=>at,RNN:()=>oa,RNNCell:()=>Pp,activation:()=>tG,add:()=>cG,alphaDropout:()=>qG,average:()=>dG,averagePooling1d:()=>Vx,averagePooling2d:()=>Ux,averagePooling3d:()=>Gx,avgPool1d:()=>bG,avgPool2d:()=>wG,avgPool3d:()=>SG,avgPooling1d:()=>vG,avgPooling2d:()=>kG,avgPooling3d:()=>IG,batchNormalization:()=>yG,bidirectional:()=>LG,concatenate:()=>pG,conv1d:()=>jU,conv2d:()=>qU,conv2dTranspose:()=>XU,conv3d:()=>KU,conv3dTranspose:()=>ZU,convLstm2d:()=>FG,convLstm2dCell:()=>OG,cropping2D:()=>JU,dense:()=>nG,depthwiseConv2d:()=>eG,dot:()=>gG,dropout:()=>rG,elu:()=>BU,embedding:()=>uG,flatten:()=>aG,gaussianDropout:()=>jG,gaussianNoise:()=>HG,globalAveragePooling1d:()=>CG,globalAveragePooling2d:()=>TG,globalMaxPool1d:()=>WG,globalMaxPool2d:()=>VG,globalMaxPooling1d:()=>ek,globalMaxPooling2d:()=>tk,gru:()=>EG,gruCell:()=>RG,input:()=>k6,inputLayer:()=>LU,layerNormalization:()=>AG,leakyReLU:()=>VU,lstm:()=>_G,lstmCell:()=>$G,masking:()=>XG,maxPool1d:()=>UG,maxPool2d:()=>GG,maxPooling1d:()=>nk,maxPooling2d:()=>rk,maxPooling3d:()=>NG,maximum:()=>hG,minimum:()=>fG,multiply:()=>mG,permute:()=>lG,prelu:()=>UU,reLU:()=>WU,repeatVector:()=>oG,reshape:()=>iG,rnn:()=>MG,separableConv2d:()=>YU,simpleRNN:()=>DG,simpleRNNCell:()=>PG,softmax:()=>GU,spatialDropout1d:()=>sG,stackedRNNCells:()=>zG,thresholdedReLU:()=>HU,timeDistributed:()=>BG,upSampling2d:()=>QU,zeroPadding2d:()=>xG});async function Ca(e){if(e==null)return;let t=[],n=[],r=[];for(let s in e){let a=e[s];if(typeof a!="number"){let o=a;t.push(o.data()),n.push(s),r.push(o)}}if(t.length>0){let s=await Promise.all(t);for(let a=0;a<s.length;++a)e[n[a]]=s[a][0];ne(r)}}function o6(e){if(e!=null)for(let t in e){let n=e[t];typeof n!="number"&&n.dispose()}}var _V=125,Ru=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){}},i6=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 n of this.callbacks)await n.onEpochBegin(e,t)}async onEpochEnd(e,t){t==null&&(t={});for(let n of this.callbacks)await n.onEpochEnd(e,t)}async onBatchBegin(e,t){t==null&&(t={});for(let n of this.callbacks)await n.onBatchBegin(e,t)}async onBatchEnd(e,t){t==null&&(t={});for(let n of this.callbacks)await n.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)}},$V=class extends Ru{constructor(){super()}async onEpochBegin(e){this.seen=0,this.totals={}}async onBatchEnd(e,t){t==null&&(t={});let n=t.size==null?0:t.size;this.seen+=n;for(let r in t){let s=t[r];if(typeof s=="number")this.totals.hasOwnProperty(r)||(this.totals[r]=0),this.totals[r]=this.totals[r]+s*n;else{let a;r in this.totals?a=this.totals[r]:this.totals[r]=0;let o=K(()=>ue(this.totals[r],L(s,n)));this.totals[r]=o,a!=null&&a.dispose()}}}async onEpochEnd(e,t){if(t!=null)for(let n of this.params.metrics)this.totals[n]!=null&&(typeof this.totals[n]=="number"?t[n]=this.totals[n]/this.seen:K(()=>{let r=L(de(1,this.seen),this.totals[n]);t[n]=r,this.totals[n].dispose(),fn(t[n])}))}},l6=class extends Ru{async onTrainBegin(e){this.epoch=[],this.history={}}async onEpochEnd(e,t){t==null&&(t={}),this.epoch.push(e);for(let n in t)this.history[n]==null&&(this.history[n]=[]),this.history[n].push(t[n])}async syncData(){let e=[],t=[],n=[];for(let s in this.history){let a=this.history[s];for(let o=0;o<a.length;++o)if(typeof a[o]!="number"){let i=a[o];e.push(i.data()),t.push(s),n.push(o)}}let r=await Promise.all(e);for(let s=0;s<r.length;++s)this.history[t[s]][n[s]].dispose(),this.history[t[s]][n[s]]=r[s][0]}},u6=class extends Ru{constructor(e,t){if(super(),this.currentEpoch=0,this.nowFunc=e.nowFunc,this.nextFrameFunc=e.nextFrameFunc||gA,this.yieldEvery=t||"auto",this.yieldEvery==="auto"&&(this.yieldEvery=_V),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=EL(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,n){let r=[];this.yield!=null&&(await Ca(n),r.push(this.yield(e,t,n))),r.push(this.nextFrameFunc()),await Promise.all(r)}async onEpochBegin(e,t){this.currentEpoch=e,this.epochBegin!=null&&(await Ca(t),await this.epochBegin(e,t))}async onEpochEnd(e,t){let n=[];this.epochEnd!=null&&(await Ca(t),n.push(this.epochEnd(e,t))),this.yieldEvery==="epoch"&&n.push(this.nextFrameFunc()),await Promise.all(n)}async onBatchBegin(e,t){this.batchBegin!=null&&(await Ca(t),await this.batchBegin(e,t))}async onBatchEnd(e,t){let n=[];this.batchEnd!=null&&(await Ca(t),n.push(this.batchEnd(e,t))),this.yieldEvery==="batch"?n.push(this.nextFrameFunc()):w.isNumber(this.yieldEvery)&&n.push(this.maybeWait(this.currentEpoch,e,t)),await Promise.all(n)}async onTrainBegin(e){this.trainBegin!=null&&(await Ca(e),await this.trainBegin(e))}async onTrainEnd(e){this.trainEnd!=null&&(await Ca(e),await this.trainEnd(e))}};function c6(e,t){return e==null&&(e={}),e instanceof Ru?[e]:Array.isArray(e)&&e[0]instanceof Ru?e:It(e).map(r=>new u6(r,t))}var Is=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}`),Is.checkForDuplicate(t),Is.constructors[e]==null&&(Is.constructors[e]=[]),Is.constructors[e].push(t)}static checkForDuplicate(e){for(let t in Is.constructors)Is.constructors[+t].forEach(r=>{if(r===e)throw new j("Duplicate callback constructor.")})}static clear(){Is.constructors={}}static createCallbacks(e){let t=[];for(let n in Is.constructors){let r=+n;e>=r&&t.push(...Is.constructors[r])}return t.map(n=>new n)}},PA=Is;PA.constructors={};function d6(e,t,n,r,s,a,o,i,l){let u=new l6,c=[new $V,...PA.createCallbacks(t)];e!=null&&c.push(...e),c.push(u);let p=new i6(c);return p.setParams({epochs:n,initialEpoch:r,samples:s,steps:a,batchSize:o,verbose:t,doValidation:i,metrics:l}),{callbackList:p,history:u}}function hs(e,t={},n=!1){return Tp(e,ce.SerializationMap.getMap().classNameMap,t,"layer",n)}function $f(e,t){return K(()=>{e.dtype!=="float32"&&(e=ge(e,"float32"));let n=ke(Ep(e),t,!0),r=hc(n.shape,an()),s=En(ra(n,r));return de(e,s)})}function Fl(e,t){return K(()=>Vt(Ep(he(t,e)),-1))}function i0(e,t){return K(()=>Vt(rn(he(t,e)),-1))}function bc(e,t){return K(()=>{let n=he(e,t),r=yr(rn(e),an(),Number.MAX_VALUE),s=rn(de(n,r));return L(100,Vt(s,-1))})}function DV(e,t){return K(()=>{let n=yr(t,an(),Number.MAX_VALUE),r=Dr(ue(1,n)),s=yr(e,an(),Number.MAX_VALUE),a=Dr(ue(1,s));return Vt(Ep(he(r,a)),-1)})}function PV(e,t){return K(()=>{let n=ra(0,he(1,L(e,t)));return Vt(Ep(n),-1)})}function FV(e,t){return K(()=>{let n=ra(0,he(1,L(e,t)));return Vt(n,-1)})}function OV(e,t){return K(()=>{let n=ke(L(e,t),-1),r=gn(L(he(1,e),t),-1);return ra(0,ue(1,he(r,n)))})}function MV(e,t){return K(()=>{let n=Math.log(2),r=he(t,e),s=he(ue(r,fc(L(-2,r))),n);return Vt(s,-1)})}function Hd(e,t,n=!1){return K(()=>{if(n)t=yc(t);else{let r=ke(t,t.shape.length-1,!0);t=de(t,r)}return t=yr(t,an(),1-an()),zt(ke(L(ge(e,"float32"),Dr(t)),t.shape.length-1))})}function Df(e,t,n=!1){return K(()=>{let r=ge(kp(WL(e)),"int32");t=yr(t,an(),1-an());let s=t.shape,a=H(Vd(r,s[s.length-1]),s);return Hd(a,t,n)})}function zV(e,t){if(!w.arraysEqual(e.shape,t.shape))throw new j(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return K(()=>{let n=Os(t),r=zt(rn(t));return ue(he(n,L(t,e)),Em($r(r)))})}function l0(e,t){return K(()=>{let n;return n=yr(t,an(),1-an()),n=Dr(de(n,he(1,n))),Vt(zV(e,n),-1)})}function LV(e,t){return K(()=>{let n=yr(e,an(),1),r=yr(t,an(),1);return ke(L(e,Dr(de(n,r))),-1)})}function BV(e,t){return K(()=>{let n=Dr(ue(an(),t));return Vt(he(t,L(e,n)),-1)})}function FA(e,t){return K(()=>{let n=$f(e,-1),r=$f(t,-1),s=L(n,r);return zt(ke(s,-1))})}var Pf={meanSquaredError:Fl,meanAbsoluteError:i0,meanAbsolutePercentageError:bc,meanSquaredLogarithmicError:DV,squaredHinge:PV,hinge:FV,categoricalHinge:OV,logcosh:MV,categoricalCrossentropy:Hd,sparseCategoricalCrossentropy:Df,binaryCrossentropy:l0,kullbackLeiblerDivergence:LV,poisson:BV,cosineProximity:FA};function ag(e){if(typeof e=="string"){if(e in Pf)return Pf[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 j(t)}else return e}function OA(e,t){return K(()=>{let n=L(.5,Pr(t)),r=Ym(Ar(t,n),e.dtype);return Vt(_r(e,r),-1)})}function MA(e,t){return K(()=>Ym(_r(Rr(e,-1),Rr(t,-1)),"float32"))}function p6(e,t){return K(()=>ge(ke(ms(_r(e,1),_r(t,1))),"float32"))}function WV(e,t){return K(()=>ge(ke(ms(_r(e,1),_r(t,0))),"float32"))}function VV(e,t){return K(()=>ge(ke(ms(_r(e,0),_r(t,1))),"float32"))}function h6(e,t){return K(()=>{let n=p6(e,t),r=VV(e,t),s=ue(n,r);return ge(Hn(Ar(s,0),de(n,s),0),"float32")})}function UV(e,t){return K(()=>{let n=p6(e,t),r=WV(e,t),s=ue(n,r);return ge(Hn(Ar(s,0),de(n,s),0),"float32")})}function f6(e,t){return l0(e,t)}function m6(e,t){return e.rank===t.rank&&(e=tt(e,[e.rank-1])),t=Rr(t,-1),t.dtype!==e.dtype&&(t=ge(t,e.dtype)),ge(_r(e,t),"float32")}var GV=Fl,HV=Fl,jV=i0,qV=i0,XV=bc,KV=bc,zA=Hd,ZV=FA,g6=Df,Ff={binaryAccuracy:OA,categoricalAccuracy:MA,precision:h6,categoricalCrossentropy:zA,sparseCategoricalCrossentropy:g6,mse:GV,MSE:HV,mae:jV,MAE:qV,mape:XV,MAPE:KV,cosine:ZV};function YV(e){if(typeof e=="string"&&e in Ff)return Ff[e];if(typeof e!="string"&&e!=null)return e;throw new j(`Unknown metric ${e}`)}function Kh(e){if(Ts(e!==null,`Unknown LossOrMetricFn ${e}`),typeof e=="string")return e;{let t;for(let n of Object.keys(Pf))if(Pf[n]===e){t=n;break}if(t!==void 0)return t;for(let n of Object.keys(Ff))if(Ff[n]===e){t=n;break}return t!==void 0?t:e.name}}function JV(e){let t={Adagrad:()=>Ai.adagrad(.01),Adadelta:()=>Ai.adadelta(1,.95,an()),Adam:()=>Ai.adam(.001,.9,.999,an()),Adamax:()=>Ai.adamax(.002,.9,.999,an(),0),RMSProp:()=>Ai.rmsprop(.001,.9,0,an()),SGD:()=>Ai.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 j(`Unknown Optimizer ${e}`)}var uv=1*1024*1024;function cv(e,t,n=!1){if(e==null||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype||!Rg(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(n){let r=JSON.stringify(e);r.length>uv&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${r.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= ${uv}.`)}}function Rg(e){if(e===null)return!0;if(typeof e=="object")if(Object.getPrototypeOf(e)===Object.prototype){let t=Object.keys(e);for(let n of t)if(typeof n!="string"||!Rg(e[n]))return!1;return!0}else if(Array.isArray(e)){for(let t of e)if(!Rg(t))return!1;return!0}else return!1;else{let t=typeof e;return t==="string"||t==="number"||t==="boolean"}}function QV(e,t,n,r=console.log){let s=tU(e),a=["Layer (type)","Input Shape","Output shape","Param #"];s?(t=t||90,n=n||[.32,.61,.89,1]):(t=t||115,n=n||[.24,.48,.7,.8,1]),n[n.length-1]<=1&&(n=n.map(c=>Math.floor(t*c)));let o;if(!s){a.push("Receives inputs"),o=[];for(let c in e.nodesByDepth)o.push(...e.nodesByDepth[c])}r("_".repeat(t)),Of(a,n,r),r("=".repeat(t));let i=e.layers;for(let c=0;c<i.length;++c)s?nU(i[c],n,r):rU(i[c],n,o,r),r((c===i.length-1?"=":"_").repeat(t));e.checkTrainableWeightsConsistency();let l=eU(e),u=Ef(e.nonTrainableWeights);r(`Total params: ${l+u}`),r(`Trainable params: ${l}`),r(`Non-trainable params: ${u}`),r("_".repeat(t))}function eU(e){let t;return e.collectedTrainableWeights!=null?t=Ef(e.collectedTrainableWeights):t=Ef(e.trainableWeights),t}function tU(e){let t=!0,n=[],r=[];for(let s in e.nodesByDepth)n.push(e.nodesByDepth[s]);for(let s of n){if(s.length>1||s.length===1&&s[0].inboundLayers.length>1){t=!1;break}r.push(...s)}if(t)for(let s of e.layers){let a=!1;for(let o of s.inboundNodes)if(r.indexOf(o)!==-1)if(a){t=!1;break}else a=!0;if(!t)break}return t}function Of(e,t,n=console.log){let r="";for(let s=0;s<e.length;++s)s>0&&(r=r.slice(0,r.length-1)+" "),r+=e[s],r=r.slice(0,t[s]),r+=" ".repeat(t[s]-r.length);n(r)}function nU(e,t,n){let r,s;try{s=e.inboundNodes.map(l=>JSON.stringify(l.inputShapes)).join(",")}catch(l){s="multiple"}try{r=JSON.stringify(e.outputShape)}catch(l){r="multiple"}let a=e.name,o=e.getClassName(),i=[`${a} (${o})`,s,r,e.countParams().toString()];Of(i,t,n)}function rU(e,t,n,r){let s,a;try{a=e.inboundNodes.map(p=>JSON.stringify(p.inputShapes)).join(",")}catch(p){a="multiple"}try{s=JSON.stringify(e.outputShape)}catch(p){s="multiple"}let o=[];for(let p of e.inboundNodes)if(!(n!=null&&n.length>0&&n.indexOf(p)===-1))for(let d=0;d<p.inboundLayers.length;++d){let h=p.inboundLayers[d].name,f=p.nodeIndices[d],m=p.tensorIndices[d];o.push(`${h}[${f}][${m}]`)}let i=e.name,l=e.getClassName(),u=o.length===0?"":o[0],c=[`${i} (${l})`,a,s,e.countParams().toString(),u];Of(c,t,r);for(let p=1;p<o.length;++p)Of(["","","","",o[p]],t,r)}function y6(e,t,n){return(e==="inboundNodes"||e==="outputLayers"||e==="inputLayers")&&t===0&&typeof n=="string"}function jd(e,t){if(e===null)return null;if(typeof e=="string")return wi(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){let n=[],r=e.length;for(let s=0;s<r;++s){let a=e[s];y6(t,s,a)?n.push(a):n.push(jd(a,t))}return n}else{let n={};for(let r of Object.keys(e)){let s=e[r];if(r==="name"&&typeof s=="string")n[r]=s;else{let a=wi(r);n[a]=jd(s,a)}}return n}}function _g(e,t){if(e==null)return null;if(typeof e=="string")return qs(e);if(typeof e=="number"||typeof e=="boolean")return e;if(e instanceof Array){let n=[],r=e.length;for(let s=0;s<r;++s){let a=e[s];y6(t,s,a)?n.push(a):n.push(_g(a,t))}return n}else{let n={};for(let r of Object.keys(e)){let s=e[r],a=qs(r);(r==="name"||r==="className")&&typeof s=="string"?n[a]=s:n[a]=_g(s,r)}return n}}var LA="0.0.0",Cs=class extends at{constructor(e){if(super({}),this.containerNodes=new Set,this.name=e.name,this.name==null){let y=this.getClassName().toLowerCase();this.name=Zm(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],_a(this.inputs).length!==this.inputs.length)throw new j(`The list of inputs passed to the model is redundant. All inputs should only appear once. Found: ${this.inputs.map(y=>y.name)}`);_a(this.outputs).length!==this.outputs.length&&console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map(y=>y.name)}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(let y of this.outputs){let x=y.sourceLayer,A=y.nodeIndex,b=y.tensorIndex;this.outputLayers.push(x),this.outputLayersNodeIndices.push(A),this.outputLayersTensorIndices.push(b)}for(let y of this.inputs){let x=y.sourceLayer,A=y.nodeIndex,b=y.tensorIndex;Ts(A===0,"input layer has >1 nodes"),Ts(b===0,"input layer has >1 tensors"),this.inputLayers.push(x),this.inputLayersNodeIndices.push(A),this.inputLayersTensorIndices.push(b)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let y=0;y<this.inputLayers.length;y++){let x=this.inputLayers[y];if(!(x instanceof xc))throw new TypeError(`Input layers to a LayersModel must be InputLayer objects. Received inputs: ${e.inputs}. Input ${y} (0-based) originates from layer type ${x.getClassName()}.`);this.inputNames.push(x.name),this.feedInputShapes.push(x.batchInputShape),this.feedInputNames.push(x.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={},n={},r={},s={},a={},o=[],i=(y,x,A,b,v,S)=>{(b==null||v==null||S==null)&&(b=y.sourceLayer,v=y.nodeIndex,S=y.tensorIndex);let I=b.inboundNodes[v];if(A.indexOf(I)!==-1)throw new us(`The tensor ${y.name} at layer "${b.name}" is part of a cycle.`);if(x.indexOf(I)!==-1)return;this.containerNodes.add(Cs.nodeKey(b,v)),b.id in a||(a[b.id]=Object.keys(a).length),A.indexOf(I)===-1&&A.push(I);let E=I.inboundLayers.length;for(let R=0;R<E;R++){let P=I.inputTensors[R],_=I.inboundLayers[R],D=I.nodeIndices[R],T=I.tensorIndices[R];i(P,x,A,_,D,T)}for(x.push(I);A.indexOf(I)>=0;)A.splice(A.indexOf(I),1);o.push(I)},l=[],u=[];for(let y of this.outputs)i(y,l,u);let c=o.slice().reverse();for(let y of c){n[y.id]=y,y.id in t||(t[y.id]=0);let x=t[y.id],A=r[y.outboundLayer.id]==null?0:r[y.outboundLayer.id];x=Math.max(x,A),r[y.outboundLayer.id]=x,s[y.outboundLayer.id]=y.outboundLayer,t[y.id]=x;for(let b=0;b<y.inboundLayers.length;b++){let v=y.inboundLayers[b],S=y.nodeIndices[b],I=v.inboundNodes[S],E=t[I.id]==null?0:t[I.id];t[I.id]=Math.max(x+1,E),n[I.id]=I}}let p={};for(let y in t){let x=t[y];x in p||(p[x]=[]),p[x].push(n[y])}let d={};for(let y in r){let x=r[y];x in d||(d[x]=[]),d[x].push(s[y])}let h=Object.keys(d).map(y=>parseInt(y,10)).sort(jh);this.layers=[];for(let y of h){let x=d[y];x.sort((A,b)=>{let v=a[A.id],S=a[b.id];return v<S?-1:v>S?1:0});for(let A of x)A instanceof Cs&&this.internalContainerRefs.push(A),this.layers.push(A)}this.layersByDepth=d,h=Object.keys(p).map(y=>parseInt(y,10)).sort(jh);let f=this.inputs.slice(),m=[];for(let y of h)for(let x of p[y]){let A=x.outboundLayer;if(A!=null){for(let b of x.inputTensors)if(f.indexOf(b)===-1)throw new us(`Graph disconnected: cannot obtain value for tensor ${b} at layer "${A.name}". The following previous layers were accessed without issue: ${m}`);for(let b of x.outputTensors)f.push(b);m.push(A.name)}}this.nodesByDepth=p;let g=this.layers.map(y=>y.name);for(let y of g){let x=g.filter(A=>A===y).length;if(x!==1)throw new us(`The name "${y}" is used ${x} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new o0({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:this.inputs.map(y=>null),outputMasks:this.outputs.map(y=>null),inputShapes:this.inputs.map(y=>y.shape),outputShapes:this.outputs.map(y=>y.shape)}),this.built=!0,this._refCount=1}assertNotDisposed(){if(this._refCount===0)throw new Error(`Container '${this.name}' is already disposed.`)}dispose(){this.assertNotDisposed();let e={refCountAfterDispose:null,numDisposedVariables:0};if(--this._refCount===0){for(let t of this.layers)e.numDisposedVariables+=t.dispose().numDisposedVariables;for(let t of this.internalContainerRefs)e.numDisposedVariables+=t.dispose().numDisposedVariables}return e.refCountAfterDispose=this._refCount,e}get trainable(){return this.trainable_}set trainable(e){this.layers.forEach(t=>{t._trainableWeights.forEach(n=>n.trainable=e)}),this.trainable_=e}get trainableWeights(){if(this._trainableWeights.length>0)throw new j("Container instance unexpectedly contains _trainableWeights.The trainable weights of a Container are a union of the trainable weights of its consituent Layers. Its own _trainableWeights must remain an empty Array.");if(!this.trainable)return[];let e=[];for(let t of this.layers)e=e.concat(t.trainableWeights);return e}get nonTrainableWeights(){let e=[];for(let t of this.layers)e.push(...t.nonTrainableWeights);if(!this.trainable){let t=[];for(let n of this.layers)t.push(...n.trainableWeights);return t.concat(e)}return e}get weights(){return this.trainableWeights.concat(this.nonTrainableWeights)}loadWeights(e,t=!0){let n={},r=0;for(let a of this.layers)for(let o of a.weights){if(n[o.originalName]!=null)throw new j(`Duplicate weight name: ${o.originalName}`);n[o.originalName]=o,r++}let s=[];for(let a in e){let o=a;if(n[a]==null){let i=a.split("/");o=i.slice(0,-2).concat([i[i.length-1]]).join("/")}if(n[o]!=null)s.push([n[o],e[a]]);else if(t)throw new j(`Provided weight data has no target variable: ${a}`);delete n[o]}if(t){let a=[];for(let o in n)a.push(o);if(a.length>0)throw new j(`${a.length} of ${r} weights are not set: ${a}`)}NA(s)}updatedConfig(){let e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${LA}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){let n=_g(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return K(()=>{e=It(e);let n=new Ii;for(let r=0;r<this.inputs.length;++r)n.add(this.inputs[r],e[r]);return Sd(this.outputs,n,t)})}computeMask(e,t){return K(()=>{e=It(e);let n;return t==null?n=Oi(null,e.length):n=It(t),this.runInternalGraph(e,n)[1]})}computeOutputShape(e){let t=Nf(e);if(t.length!==this.inputLayers.length)throw new j(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);let n={};for(let o=0;o<t.length;o++){let i=this.inputLayers[o],l=t[o],u=i.name+"_0_0";n[u]=l}let r=Object.keys(this.nodesByDepth).map(o=>parseInt(o,10)).sort(jh);if(r.length>1)for(let o of r){let i=this.nodesByDepth[o];for(let l of i){let u=l.outboundLayer;if(this.inputLayers.map(f=>f.id).indexOf(u.id)!==-1)continue;let c=[];for(let f=0;f<l.inboundLayers.length;f++){let m=l.inboundLayers[f],g=l.nodeIndices[f],y=l.tensorIndices[f],x=`${m.name}_${g}_${y}`,A=n[x];c.push(A)}let p=u.computeOutputShape(tr(c)),d=Nf(p),h=u.inboundNodes.indexOf(l);for(let f=0;f<d.length;f++){let m=`${u.name}_${h}_${f}`;n[m]=d[f]}}}let s=[],a=[];for(let o=0;o<this.outputLayers.length;o++){let i=this.outputLayers[o],l=this.outputLayersNodeIndices[o],u=this.outputLayersTensorIndices[o],c=`${i.name}_${l}_${u}`;a.push(c)}for(let o=0;o<a.length;o++){let i=a[o];Ts(i in n),s.push(n[i])}return tr(s)}runInternalGraph(e,t){t==null&&(t=Oi(null,e.length));let n={};for(let i=0;i<this.inputs.length;++i){let l=this.inputs[i],u=e[i],c=t[i];n[l.id]=[u,c]}let r=Object.keys(this.nodesByDepth).map(i=>parseInt(i,10)).sort(jh);for(let i of r){let l=this.nodesByDepth[i];for(let u of l){let c=u.outboundLayer,p=u.inputTensors,d=u.outputTensors,h=new Array;for(let f of p)f.id in n&&h.push(n[f.id]);if(h.length===p.length){let f={},m,g,y,x;if(u.callArgs!=null&&(f=u.callArgs),h.length===1){let[A,b]=h[0];f.mask==null&&(f.mask=b),y=It(c.call(A,f)),x=It(c.computeMask(A,b)),m=[A],g=[b]}else m=h.map(A=>A[0]),g=h.map(A=>A[1]),f.mask==null&&(f.mask=g),y=It(c.call(m,f)),x=It(c.computeMask(m,g));if(c.activityRegularizer)throw new Ve("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let A=0;A<d.length;++A){let b=d[A],v=y[A],S=x[A];n[b.id]=[v,S]}}}}let s=[],a=[],o=[];for(let i of this.outputs){Ts(i.id in n,`Could not compute output ${i.name} : ${i.id}`);let[l,u]=n[i.id];o.push(l.shape),s.push(l),a.push(u)}return[s,a,o]}buildNodeConversionMap(e){let t={},n;for(let r of this.layers){n=r instanceof Cs?1:0;for(let s=0;s<r.inboundNodes.length;s++){let a=Cs.nodeKey(r,s);this.containerNodes.has(a)&&(t[a]=n,n+=1)}}return t}getLayer(e,t){if(t!=null){if(this.layers.length<=t)throw new j(`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 j("Provide either a layer name or layer index");for(let n of this.layers)if(n.name===e)return n;throw new j(`No such layer: ${e}`)}calculateLosses(){return K(()=>{let e=[];for(let t of this.layers)for(let n=0;n<t.inboundNodes.length;++n){let r=Cs.nodeKey(t,n);this.containerNodes.has(r)&&e.push(...t.calculateLosses())}return e})}getConfig(){let e={name:this.name},t=this.buildNodeConversionMap(this.layers),n=[];for(let a of this.layers){let o=a.getClassName(),i=a.getConfig(),l=[];for(let c=0;c<a.inboundNodes.length;c++){let p=a.inboundNodes[c],d=Cs.nodeKey(a,c),h={};if(this.containerNodes.has(d)){if(p.callArgs)try{JSON.stringify(p.callArgs),h=p.callArgs}catch(f){console.warn(`Layer ${a.name} was passed non-serializable keyword arguments: ${p.callArgs}. They will not be included in the serialized model (and thus will be missing at deserialization time).`),h={}}if(p.inboundLayers.length>0){let f=[];for(let m=0;m<p.inboundLayers.length;m++){let g=p.inboundLayers[m],y=p.nodeIndices[m],x=p.tensorIndices[m],A=Cs.nodeKey(g,y),b=t[A];b==null&&(b=0),f.push([g.name,b,x,h])}l.push(f)}}}let u={};u.name=a.name,u.className=o,u.config=i,u.inboundNodes=l,n.push(u)}e.layers=n;let r=[];for(let a=0;a<this.inputLayers.length;a++){let o=this.inputLayers[a],i=this.inputLayersNodeIndices[a],l=Cs.nodeKey(o,i);if(!this.containerNodes.has(l))continue;let u=t[l];u==null&&(u=0);let c=this.inputLayersTensorIndices[a];r.push([o.name,u,c])}e.inputLayers=r;let s=[];for(let a=0;a<this.outputLayers.length;a++){let o=this.outputLayers[a],i=this.outputLayersNodeIndices[a],l=Cs.nodeKey(o,i);if(!this.containerNodes.has(l))continue;let u=t[l];u==null&&(u=0);let c=this.outputLayersTensorIndices[a];s.push([o.name,u,c])}return e.outputLayers=s,e}static fromConfig(e,t,n={},r=!1){let s={},a={};function o(m,g){m.name in a?a[m.name].push(g):a[m.name]=[g]}function i(m,g){let y=[],x;for(let A of g){let b=A[0],v=A[1],S=A[2];if(x=A[3]==null?{}:A[3],!(b in s)){o(m,g);return}let I=s[b];if(I.inboundNodes.length<=v){o(m,g);return}let E=I.inboundNodes[v];y.push(E.outputTensors[S])}y.length>0&&m.apply(tr(y),x)}function l(m){let g=m.name,y=hs(m,t.customObjects!=null?t.customObjects:{});y.setFastWeightInitDuringBuild(r),s[g]=y,m.inboundNodes.forEach(A=>{if(!(A instanceof Array))throw new j(`Corrupted configuration, expected array for nodeData: ${A}`);o(y,A)})}let u=t.name,c=t.layers;for(let m of c)l(m);for(;!NL(a);)for(let m of c){let g=s[m.name];if(g.name in a){let y=a[g.name];delete a[g.name];for(let x of y)i(g,x)}}let p=[],d=[],h=t.inputLayers;for(let m of h){let g=m[0],y=m[1],x=m[2];Ts(g in s);let b=s[g].inboundNodes[y].outputTensors;p.push(b[x])}let f=t.outputLayers;for(let m of f){let g=m[0],y=m[1],x=m[2];Ts(g in s);let b=s[g].inboundNodes[y].outputTensors;d.push(b[x])}return new e({inputs:p,outputs:d,name:u})}get stateful(){if(this._stateful)throw new j("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 sU(e,t,n){let r=t.length;if(e==null||Array.isArray(e)&&e.length===0)return t.map(s=>null);if(r===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!==r)throw new Error(`Provided ${n} is an array of ${e.length} element(s), but the model has ${r} 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 s=[];return t.forEach(a=>{a in e?s.push(e[a]):s.push(null)}),s}else throw new Error(`The model has multiple (${r}) outputs, so ${n} must be either an array with ${r} elements or an object with ${t} keys. Provided ${n} not understood: ${JSON.stringify(e)}`)}function A6(e,t){return sU(e,t,"classWeight")}async function x6(e,t,n,r){if(t!=null||r!=null)throw new Error("Support sampleWeight is not implemented yet");if(n!=null){let s=K(()=>{if(e.shape.length===1)return Gn(e);if(e.shape.length===2){if(e.shape[1]>1)return Rr(e,1);if(e.shape[1]===1)return H(e,[e.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${e.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}else throw new Error(`Unexpected rank of target (y) tensor (${e.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)}),a=Array.from(await s.data());ne(s);let o=[];return a.forEach(i=>{if(n[i]==null)throw new Error(`classWeight must contain all classes in the training data. The class ${i} exists in the data but not in classWeight`);o.push(n[i])}),Ct(o,"float32")}else return null}function aU(e,t){return L(e,t)}var oU=32;function b6(e,t){let n,r,s=t;n=s.xs,r=s.ys,w.assert(n!=null&&r!=null,()=>`A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates ${t}`);let a=dv("input",e.inputNames,n),o=dv("output",e.outputNames,r),i=a[0].shape[0];w.assert(a.length===e.inputs.length,()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${a.length} inputs. (Expected input keys: ${JSON.stringify(e.inputNames)})`),w.assert(o.length===e.outputs.length,()=>`LayersModel has ${e.outputs.length} outputs, but the dataset provides ${o.length} outputs. (Expected output keys: ${JSON.stringify(e.outputNames)})`);for(let l=0;l<a.length;l++)w.assert(a[l].shape[0]===i,()=>`Batch size mismatch: input ${e.inputNames[l]} has ${a[l].shape[0]}; expected ${i} based on input ${e.inputNames[0]}.`);for(let l=0;l<o.length;l++)w.assert(o[l].shape[0]===i,()=>`Batch size mismatch: output ${e.outputNames[l]} has ${o[l].shape[0]}; expected ${i} based on input ${e.inputNames[0]}.`);return{xs:a,ys:o}}function dv(e,t,n){if(n instanceof rt)return[n];if(Array.isArray(n))return w.assert(n.length===t.length,()=>`Received an array of ${n.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`),n;{let r=[];for(let s of t){if(n[s]==null)throw new j(`The feature data generated by the dataset lacks the required ${e} key '${s}'.`);r.push(n[s])}return r}}function iU(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 lU(e,t,n){let r=n.batchesPerEpoch!=null;if(w.assert(e.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),w.assert(n!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),w.assert(n.epochs!=null&&n.epochs>0&&Number.isInteger(n.epochs),()=>`For fitDataset(), config.epochs is expected to be a positive integer, but got ${n.epochs}`),w.assert(!r||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${n.batchesPerEpoch}`),w.assert(n.validationSplit==null,()=>"`validationSplit` is not supported by `fitDataset()`. Use validationData instead."),e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;try{let s=n.validationData!=null,a,o;if(s)if(pv(n.validationData))w.assert(n.validationBatches==null||n.validationBatches>0&&Number.isInteger(n.validationBatches),()=>`For fitDataset() with dataset-based validation, config.validationBatches is expected not to be provided, or to be a positive integer, but got ${n.validationBatches}`);else{let g=iU(n.validationData);a=g.xs,o=g.ys}let i=e.makeTrainFunction(),l=e.getDedupedMetricsNames(),u;s?u=l.slice().concat(l.map(g=>"val_"+g)):u=l.slice();let c=c6(n.callbacks,n.yieldEvery),p=n.verbose==null?1:n.verbose,{callbackList:d,history:h}=d6(c,p,n.epochs,null,null,uU(t,n),null,s,u);d.setModel(e),e.history=h,await d.onTrainBegin(),e.stopTraining_=!1;let f=n.initialEpoch==null?0:n.initialEpoch,m=await t.iterator();for(;f<n.epochs;){let g={};await d.onEpochBegin(f);let y=0,x=0;for(r||(m=await t.iterator());!r||y<n.batchesPerEpoch;){let A=await m.next();if(r&&A.done){console.warn(`You provided \`batchesPerEpoch\` as ${n.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, ${n.batchesPerEpoch*n.epochs} batches). You may need to use the repeat() function when building your dataset.`);break}if(A.value!=null){let{xs:b,ys:v}=b6(e,A.value),S={};S.batch=x,S.size=b[0].shape[0],await d.onBatchBegin(x,S);let I=[];if(n.classWeight!=null){let P=A6(n.classWeight,e.outputNames);for(let _=0;_<P.length;++_)I.push(await x6(v[_],null,P[_]))}let E=b.concat(v).concat(I),R=i(E);ne(E);for(let P=0;P<l.length;++P){let _=l[P],D=R[P];S[_]=D,fn(D)}await d.onBatchEnd(x,S),o6(S),x++,y++}if(r?y>=n.batchesPerEpoch:A.done){if(s){let b;pv(n.validationData)?b=It(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):b=It(e.evaluate(a,o,{batchSize:n.validationBatchSize==null?oU:n.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 d.onEpochEnd(f,g),f++,e.stopTraining_)break}return await d.onTrainEnd(),await e.history.syncData(),e.history}finally{e.isTraining=!1}}function uU(e,t){let n=null;return t.batchesPerEpoch!=null?n=t.batchesPerEpoch:Number.isFinite(e.size)&&(n=e.size),n}function pv(e){return typeof e.iterator=="function"}function cU(e){return typeof e.next=="function"}async function dU(e,t,n){n=n||{};let r=n.batches!=null,s=e.testFunction,a=[];if(n.verbose>0)throw new Ve("Verbose mode is not implemented yet.");w.assert(!r||n.batches>0&&Number.isInteger(n.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(n.batches)}`);let o=cU(t)?t:await t.iterator(),i=0,l=0;for(;!r||l<n.batches;){let u=await o.next();if(a=K(()=>{if(u.value){let{xs:c,ys:p}=b6(e,u.value),d=c.concat(p),h=K(()=>s(d));if(ne(d),l===0)for(let m=0;m<h.length;++m)a.push(Ie(0));let f=d[0].shape[0];for(let m=0;m<h.length;++m){let g=h[m],y=a[m];a[m]=K(()=>ue(a[m],L(f,g))),l>0&&ne(y)}ne(h),i+=f,++l}return a}),u.done){r&&console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${n.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let u=0;u<a.length;++u){let c=a[u];a[u]=de(a[u],i),ne(c)}return tr(a)}function $g(e){w.assert(e>0&&Number.isInteger(e),()=>`batchSize is required to be a positive integer, but got ${e}`)}function Id(e,t,n){return e==null?[null]:Array.isArray(e)?e.map(r=>Ei(r,t,n-t)):Ei(e,t,n-t)}function BA(e,t){return K(()=>e==null?null:Array.isArray(e)?e.map(n=>BA(n,t)):Z7(e,t.dtype==="int32"?t:ge(t,"int32")))}function Dg(e,t){let n=[],r=0,s=null;for(;r<e;)s=r+t,s>=e&&(s=e),n.push([r,s]),r=s;return n}async function pU(e,t,n,r,s,a,o,i,l,u,c,p,d,h,f){s==null&&(s=32),a==null&&(a=1),c==null&&(c=!0),d==null&&(d=0);let m=!1;if(l!=null&&u!=null&&(m=!0),f!=null&&(m=!0,h==null))throw new j("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");let g=e.checkNumSamples(n,s,h,"steps_per_epoch"),y;g!=null&&(y=gs(0,g)),o==null&&(o=1);let{callbackList:x,history:A}=d6(i,o,a,d,g,h,s,m,p);x.setModel(e),e.history=A,await x.onTrainBegin(),e.stopTraining_=!1;for(let b=d;b<a;++b){await x.onEpochBegin(b);let v={};if(h!=null)throw new Ve("stepsPerEpoch mode is not implemented yet.");{if(c==="batch")throw new Ve("batch shuffling is not implemneted yet");c&&w.shuffle(y);let S=Ct(y),I=Dg(g,s);for(let E=0;E<I.length;++E){let R={};if(await x.onBatchBegin(E,R),K(()=>{let P=I[E][0],_=I[E][1],D=Ei(S,P,_-P);R.batch=E,R.size=_-P;let T=BA(n,D),F=t(T);for(let U=0;U<r.length;++U){let X=r[U],z=F[U];R[X]=z,fn(z)}if(E===I.length-1&&m){let U=e.testLoop(l,u,s);for(let X=0;X<r.length;++X){let z=r[X],Z=U[X];fn(Z),v["val_"+z]=Z}}}),await x.onBatchEnd(E,R),o6(R),e.stopTraining_)break}S.dispose()}if(await x.onEpochEnd(b,v),e.stopTraining_)break}return await x.onTrainEnd(),await e.history.syncData(),e.history}async function hU(e,t,n,r={}){if(e.isTraining)throw new Error("Cannot start training because another fit() call is ongoing.");e.isTraining=!0;let s,a,o,i,l,u,c,p,d;try{let h=r.batchSize==null?32:r.batchSize;$g(h);let f=!1,m=await e.standardizeUserData(t,n,r.sampleWeight,r.classWeight,f,h);s=m[0],a=m[1],d=m[2];let g=!1,y;if(r.validationData!=null&&r.validationData.length>0){if(g=!0,r.validationData.length===2)l=r.validationData[0],u=r.validationData[1];else throw r.validationData.length===3?new Ve("validationData including sample weights is not supported yet."):new j(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${r.validationData} is invalid.`);let R=!0,P=await e.standardizeUserData(l,u,null,null,R,h);c=P[0],p=P[1],y=c.concat(p)}else if(r.validationSplit!=null&&r.validationSplit>0&&r.validationSplit<1){g=!0;let R=Math.floor(s[0].shape[0]*(1-r.validationSplit)),P=s[0].shape[0];c=Id(s,R,P),o=s,s=Id(s,0,R),p=Id(a,R,P),i=a,a=Id(a,0,R),y=c.concat(p)}else r.validationSteps!=null&&(g=!0);let x=s.concat(a).concat(d);e.checkTrainableWeightsConsistency();let A=e.makeTrainFunction(),b=e.getDedupedMetricsNames(),v,S;g?(e.makeTestFunction(),v=e.testFunction,S=b.slice().concat(b.map(R=>"val_"+R))):(v=null,y=[],S=b.slice());let I=c6(r.callbacks,r.yieldEvery);return await pU(e,A,x,b,h,r.epochs,r.verbose,I,v,y,r.shuffle,S,r.initialEpoch,null,null)}finally{e.isTraining=!1,ls(s,t),ls(a,n),ls(o,t),ls(i,n),ls(c,l),ls(p,u),d!=null&&ne(d)}}function v6(e){let t=[];e instanceof rt&&(e=[e]);for(let n=0;n<e.length;++n){let r=e[n];if(r.rank===1)t.push(Np(r,1));else{if(r.rank===0)throw new Error("Expected tensor to be at least 1D, but received a 0D tensor (scalar).");t.push(r)}}return t}function ls(e,t){if(e==null)return;let n=[];if(t instanceof rt)n.push(t.id);else if(Array.isArray(t))t.forEach(s=>n.push(s.id));else if(t!=null)for(let s in t){let a=t[s];n.push(a.id)}let r=[];if(e instanceof rt)n.indexOf(e.id)===-1&&r.push(e);else if(Array.isArray(e))e.forEach(s=>{n.indexOf(s.id)===-1&&r.push(s)});else if(e!=null)for(let s in e){let a=e[s];n.indexOf(a.id)===-1&&r.push(a)}r.forEach(s=>{s.isDisposed||s.dispose()})}function fU(e){return e instanceof rt}function Pg(e){return Array.isArray(e)}function hv(e){return!fU(e)&&!Pg(e)}function fv(e,t,n,r=!0,s=""){if(t==null||t.length===0){if(e!=null){let o=!1;if(Pg(e)&&e.length>0)o=!0;else if(hv(e)){for(let i in e)if(e.hasOwnProperty(i)){o=!0;break}}else o=!0;if(o)throw new j(`Error when checking model ${s} expected no data, but got ${e}`)}return[]}if(e==null)return t.map(o=>null);let a;if(hv(e)){e=e,a=[];for(let o of t){if(e[o]==null)throw new j(`No data provided for "${o}". Need data for each key in: ${t}`);a.push(e[o])}}else if(Pg(e)){if(e=e,e.length!==t.length)throw new j(`Error when checking model ${s}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${e}`);a=e}else{if(e=e,t.length>1)throw new j(`The model ${s} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);a=[e]}if(a=v6(a),n!=null)for(let o=0;o<t.length;++o){if(n[o]==null)continue;let i=a[o];if(i.shape.length!==n[o].length)throw new j(`Error when checking ${s}: expected ${t[o]} to have ${n[o].length} dimension(s). but got array with shape ${i.shape}`);for(let l=0;l<n[o].length;++l){if(l===0&&!r)continue;let u=i.shape[l],c=n[o][l];if(c!=null&&c>=0&&u!==c)throw new j(`${s} expected a batch of elements where each example has shape [${n[o].slice(1,n[o].length)}] (i.e.,tensor shape [*,${n[o].slice(1,n[o].length)}]) but the ${s} received an input with ${i.shape[0]} examples, each with shape [${i.shape.slice(1,i.shape.length)}] (tensor shape [${i.shape}])`)}}return a}function mU(e,t,n){let r=_a(e.map(a=>a.shape[0]));r.sort();let s=_a(t.map(a=>a.shape[0]));if(s.sort(),r.length>1)throw new j(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map(a=>a.shape))}`);if(s.length>1)throw new j(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map(a=>a.shape))}`);if(r.length>0&&s.length>0&&!w.arraysEqual(r,s))throw new j(`Input Tensors should have the same number of samples as target Tensors. Found ${r[0]} input sample(s) and ${s[0]} target sample(s).`)}function gU(e,t,n){let r=[Fl,l0,Hd];for(let s=0;s<e.length;++s){let a=e[s],o=t[s],i=n[s];if(o!=null){if(o===Hd&&a.shape[a.shape.length-1]===1)throw new j(`You are passing a target array of shape ${a.shape} while using a loss 'categorical_crossentropy'. 'categorical_crossentropy'expects targets to be binary matrices (1s and 0s) of shape [samples, classes].`);if(r.indexOf(o)!==-1){let l=a.shape.slice(1),u=i.slice(1);for(let c=0;c<l.length;++c){let p=l[c],d=u[c];if(d!=null&&p!==d)throw new j(`A target Tensor with shape ${a.shape} was passed for an output of shape ${i}, while using a loss function that expects targets to have the same shape as the output.`)}}}}}function mv(e,t,n,r=!0,s=""){let a;if(Array.isArray(e)){if(e.length!==t.length)throw new j(`Error when checking model ${s}: 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).`);a=e}else{if(t.length>1)throw new j(`The model expects ${t.length} ${s} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);a=[e]}if(n!=null)for(let o=0;o<t.length;++o){if(n[o]==null)continue;let i=a[o];if(i.shape.length!==n[o].length)throw new j(`Error when checking ${s}: expected ${t[o]} to have ${n[o].length} dimension(s), but got array with shape ${JSON.stringify(i.shape)}`);for(let l=0;l<n[o].length;++l){if(l===0&&!r)continue;let u=i.shape[l],c=n[o][l];if(c!=null&&c!==u)throw new j(`Error when checking ${s}: expected ${t[o]} to have shape ${JSON.stringify(n[o])} but got array with shape ${JSON.stringify(i.shape)}.`)}}}function yU(e,t){if(e==null||Array.isArray(e)&&e.length===0)return t.map(r=>[]);let n;if(typeof e=="string"||typeof e=="function")n=[e];else if(Array.isArray(e)||typeof e=="object")n=e;else throw new TypeError(`Type of metrics argument not understood. Expected an string,function, Array, or Object, found: ${e}`);if(Array.isArray(n))return t.map(r=>n);{let r=[];for(let s of t){let a=n.hasOwnProperty(s)?n[s]:[];Array.isArray(a)||(a=[a]),r.push(a)}return r}}var AU="layers-model",Ys=class extends Cs{constructor(e){super(e),this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new j("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).");QV(this,e,t,n)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=JV(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof aa))throw new j("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(!Array.isArray(e.loss)&&typeof e.loss!="string"&&typeof e.loss!="function"){e.loss=e.loss;for(let a in e.loss)if(this.outputNames.indexOf(a)===-1)throw new j(`Unknown entry in loss dictionary: "${a}". Only expected the following keys: ${this.outputNames}`);for(let a of this.outputNames)e.loss[a]==null&&console.warn(`Output "${a}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${a} during training`),t.push(ag(e.loss[a]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new j(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);t=e.loss.map(o=>ag(o))}else{let a=ag(e.loss);this.outputs.forEach(o=>{t.push(a)})}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let a=0;a<this.outputs.length;++a){let o=this.internalOutputShapes[a],i=this.outputNames[a];this.feedOutputNames.push(i),this.feedOutputShapes.push(o),this.feedLossFns.push(this.lossFunctions[a])}let n=[];this.metrics=e.metrics,this.metricsNames=["loss"],this.metricsTensors=[],Ni("loss",()=>{for(let a=0;a<this.outputs.length;++a){if(n.indexOf(a)!==-1)continue;let o=this.lossFunctions[a];this.outputs.length>1&&(this.metricsTensors.push([o,a]),this.metricsNames.push(this.outputNames[a]+"_loss"))}});let r=yU(e.metrics,this.outputNames),s=(a,o,i)=>{this.outputNames.length>1&&(o=this.outputNames[a]+"_"+o),this.metricsNames.push(o),this.metricsTensors.push([i,a])};Ni("metric",()=>{for(let a=0;a<this.outputs.length;++a){if(n.indexOf(a)!==-1)continue;let o=r[a];(l=>{let u="",c,p,d;for(let h of l){if(typeof h=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(h)!==-1){let m=this.internalOutputShapes[a];m[m.length-1]===1||this.lossFunctions[a]===l0?["accuracy","acc"].indexOf(h)!==-1?p=OA:["crossentropy","ce"].indexOf(h)!==-1&&(p=f6):this.lossFunctions[a]===Df?["accuracy","acc"].indexOf(h)!==-1?p=m6:["crossentropy","ce"].indexOf(h)!==-1&&(p=g6):["accuracy","acc"].indexOf(h)!==-1?p=MA:["crossentropy","ce"].indexOf(h)!==-1&&(p=zA);let g;["accuracy","acc"].indexOf(h)!==-1?g="acc":["crossentropy","ce"].indexOf(h)!==-1&&(g="ce"),d=p,c=u+g}else d=YV(h),c=u+Kh(h);let f;Ni(c,()=>{f=d}),s(a,c,f)}})(o)}}),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){this.collectedTrainableWeights!=null&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(e,t,n={}){let r=n.batchSize==null?32:n.batchSize;$g(r);let s=!0,a=this.standardizeUserDataXY(e,t,s,r);try{let o=a[0].concat(a[1]);this.makeTestFunction();let i=this.testFunction,l=this.testLoop(i,o,r,n.verbose,n.steps);return tr(l)}finally{ls(a[0],e),ls(a[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),dU(this,e,t)}checkNumSamples(e,t,n,r="steps"){let s;if(n!=null){if(s=null,t!=null)throw new j(`If ${r} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else if(e!=null)Array.isArray(e)?s=e[0].shape[0]:s=e.shape[0];else throw new j(`Either the input data should have a defined shape, or ${r} shoud be specified.`);return s}execute(e,t){if(Array.isArray(t)&&t.length===0)throw new j("`outputs` is an empty Array, which is not allowed.");let n=Array.isArray(t),r=n?t:[t],s=this.retrieveSymbolicTensors(r),a=new Ii;if(e instanceof rt&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new j(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let i=0;i<this.inputs.length;++i)a.add(this.inputs[i],e[i])}else for(let i of this.inputs){let l=e[i.name];if(l==null)throw new j(`No value is provided for the model's input ${i.name}`);a.add(i,l)}let o=Sd(s,a);return n?o:o[0]}retrieveSymbolicTensors(e){let t=Oi(null,e.length),n=e.length;for(let r of this.layers){let s=Array.isArray(r.output)?r.output:[r.output],a=s.map(o=>o.name);for(let o=0;o<e.length;++o){let i=a.indexOf(e[o]);if(i!==-1&&(t[o]=s[i],n--),n===0)break}if(n===0)break}if(n>0){let r=[];throw t.forEach((s,a)=>{s==null&&r.push(e[a])}),new j(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(r)}`)}return t}predictLoop(e,t=32,n=!1){return K(()=>{let r=this.checkNumSamples(e);if(n)throw new Ve("Verbose predictLoop() is not implemented yet.");let s=Dg(r,t),a=this.outputs.map(o=>[]);for(let o=0;o<s.length;++o)K(()=>{let l=s[o][0],u=s[o][1],c=Id(e,l,u),p=[];if(Array.isArray(c))for(let h=0;h<c.length;++h)p.push({key:this.inputs[h],value:c[h]});else p.push({key:this.inputs[0],value:c});let d=new Ii(p);return Sd(this.outputs,d)}).forEach((l,u)=>a[u].push(l));return tr(a.map(o=>St(o,0)))})}predict(e,t={}){let n=v6(e);mv(n,this.inputNames,this.feedInputShapes,!1);try{let r=t.batchSize==null?32:t.batchSize;return $g(r),this.predictLoop(n,r)}finally{ls(n,e)}}predictOnBatch(e){mv(e,this.inputNames,this.feedInputShapes,!0);let t=(Array.isArray(e)?e[0]:e).shape[0];return this.predictLoop(e,t)}standardizeUserDataXY(e,t,n=!0,r){if(this.optimizer_==null)throw new us("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");let s=[];for(let a=0;a<this.feedOutputShapes.length;++a){let o=this.feedOutputShapes[a];this.feedLossFns[a]===Df?s.push(o.slice(0,o.length-1).concat([1])):s.push(o)}if(e=fv(e,this.feedInputNames,this.feedInputShapes,!1,"input"),t=fv(t,this.feedOutputNames,s,!1,"target"),mU(e,t,null),gU(t,this.feedLossFns,this.feedOutputShapes),this.stateful&&r!=null&&r>0&&e[0].shape[0]%r!==0)throw new j(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${r}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,n,r,s=!0,a){let[o,i]=this.standardizeUserDataXY(e,t,s,a);if(n!=null)throw new Error("sample weight is not supported yet.");let l=null;if(r!=null){let u=A6(r,this.outputNames);l=[];for(let c=0;c<u.length;++c)l.push(await x6(i[c],null,u[c]))}return[o,i,l]}testLoop(e,t,n,r=0,s){return K(()=>{let a=this.checkNumSamples(t,n,s,"steps"),o=[];if(r>0)throw new Ve("Verbose mode is not implemented yet.");if(s!=null)throw new Ve("steps mode in testLoop() is not implemented yet");{let i=Dg(a,n),l=Ct(gs(0,a));for(let u=0;u<i.length;++u){let c=i[u][0],p=i[u][1],d=Ei(l,c,p-c),h=BA(t,d),f=e(h);if(u===0)for(let m=0;m<f.length;++m)o.push(Ie(0));for(let m=0;m<f.length;++m){let g=f[m];o[m]=ue(o[m],L(p-c,g))}}for(let u=0;u<o.length;++u)o[u]=de(o[u],a)}return o})}getDedupedMetricsNames(){let e=this.metricsNames,t=[];for(let n=0;n<e.length;++n){let r=e[n],s=r;Xb(e,r)>1&&(s+=`_${Xb(e.slice(0,n),r)}`),t.push(s)}return t}makeTrainFunction(){return e=>{let t=[],n=e.slice(0,this.inputs.length),r=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),s=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+this.outputs.length*2),a=[],o=()=>{let c=[];for(let f=0;f<this.inputs.length;++f)c.push({key:this.inputs[f],value:n[f]});let p=new Ii(c),d=Sd(this.outputs,p,{training:!0}),h;for(let f=0;f<this.lossFunctions.length;++f){let g=this.lossFunctions[f](r[f],d[f]);s[f]!=null&&(g=aU(g,s[f]));let y=Vt(g);t.push(y),f===0?h=g:h=ue(h,g)}for(let f=0;f<this.metricsTensors.length;++f){let m;if(this.outputs.length>1&&f<this.outputs.length)m=t[f];else{let g=this.metricsTensors[f][0],y=this.metricsTensors[f][1];m=Vt(g(r[y],d[y]))}fn(m),a.push(m)}return h=Vt(h),this.calculateLosses().forEach(f=>{h=ue(h,f)}),h},i=this.collectedTrainableWeights.map(c=>c.read()),l=!0;return[this.optimizer_.minimize(o,l,i)].concat(a)}}makeTestFunction(){this.testFunction=e=>K(()=>{let t=[],n,r=e.slice(0,this.inputs.length),s=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),a=[];for(let l=0;l<this.inputs.length;++l)a.push({key:this.inputs[l],value:r[l]});let o=new Ii(a),i=Sd(this.outputs,o);for(let l=0;l<this.lossFunctions.length;++l){let u=this.lossFunctions[l],c=Vt(u(s[l],i[l]));l===0?n=c:n=ue(n,c),t.push(n)}for(let l=0;l<this.metricsTensors.length;++l){let u=this.metricsTensors[l][0],c=this.metricsTensors[l][1],p=Vt(u(s[c],i[c]));t.push(p)}return t})}async fit(e,t,n={}){return hU(this,e,t,n)}async fitDataset(e,t){return lU(this,e,t)}async trainOnBatch(e,t){let n=await this.standardizeUserData(e,t),r=n[0],s=n[1],o=this.makeTrainFunction()(r.concat(s)),i=[];for(let l of o){let u=await l.data();i.push(u[0])}return ne(o),ls(n[0],e),ls(n[1],t),tr(i)}getNamedWeights(e){let t=[],n=e!=null&&e.trainableOnly,r=n?this.trainableWeights:this.weights,s=this.getWeights(n);for(let a=0;a<r.length;++a)n&&!r[a].trainable||t.push({name:r[a].originalName,tensor:s[a]});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=Sf().numTensors;this.optimizer_.dispose(),e.numDisposedVariables+=t-Sf().numTensors}return e}getLossIdentifiers(){let e;if(typeof this.loss=="string")e=qs(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=>qs(t))}else{let t=Object.keys(this.loss);e={};let n=this.loss;for(let r of t)if(typeof n[r]=="string")e[r]=qs(n[r]);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[qs(Kh(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>qs(Kh(e)));{let e={};for(let t in this.metrics)e[t]=qs(Kh(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=jd(e.optimizer_config),n=hs(t),r;if(typeof e.loss=="string")r=wi(e.loss);else if(Array.isArray(e.loss))r=e.loss.map(a=>wi(a));else if(e.loss!=null){r={};for(let a in e.loss)r[a]=wi(e.loss[a])}let s;if(Array.isArray(e.metrics))s=e.metrics.map(a=>wi(a));else if(e.metrics!=null){s={};for(let a in e.metrics)s[a]=wi(e.metrics[a])}this.compile({loss:r,metrics:s,optimizer:n})}async save(e,t){if(typeof e=="string"){let l=Cn.getSaveHandlers(e);if(l.length===0)throw new j(`Cannot find any save handlers for URL '${e}'`);if(l.length>1)throw new j(`Found more than one (${l.length}) save handlers for URL '${e}'`);e=l[0]}if(e.save==null)throw new j("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");let n=await Cn.encodeWeights(this.getNamedWeights(t)),r=!1,s=null,o={modelTopology:this.toJSON(s,r),format:AU,generatedBy:`TensorFlow.js tfjs-layers v${LA}`,convertedBy:null};if((t==null?!1:t.includeOptimizer)&&this.optimizer!=null){o.trainingConfig=this.getTrainingConfig();let l="optimizer",{data:u,specs:c}=await Cn.encodeWeights(await this.optimizer.getWeights(),l);n.specs.push(...c),n.data=Cn.concatenateArrayBuffers([n.data,u])}return this.userDefinedMetadata!=null&&(cv(this.userDefinedMetadata,this.name,!0),o.userDefinedMetadata=this.userDefinedMetadata),o.weightData=n.data,o.weightSpecs=n.specs,e.save(o)}setUserDefinedMetadata(e){cv(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}};Ys.className="Model";ce.registerClass(Ys);var w6=class extends Ys{};w6.className="Functional";ce.registerClass(w6);async function xU(e,t){"modelTopology"in e||(e={modelTopology:e}),e=e;let n=e.modelTopology;n.model_config!=null&&(n=n.model_config);let r=jd(n),s=hs(r,t);if(e.weightsManifest!=null){let a=await Cn.loadWeights(e.weightsManifest,e.pathPrefix,s.weights.map(i=>i.originalName)),o={};for(let i of s.weights)o[i.originalName]=a[i.originalName];s.loadWeights(o),ne(a)}return s}async function bU(e,t){if(t==null&&(t={}),typeof e=="string"){let n=Cn.getLoadHandlers(e,t);if(n.length===0)n.push(Cn.browserHTTPRequest(e,t));else if(n.length>1)throw new j(`Found more than one (${n.length}) load handlers for URL '${e}'`);e=n[0]}return vU(e,void 0,t)}async function vU(e,t,n){if(n==null&&(n={}),e.load==null)throw new j("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let r=await e.load(),s=r.modelTopology;s.model_config!=null&&(s=s.model_config);let a=n.strict==null?!0:n.strict,o=r.weightData!=null&&r.weightSpecs!=null&&a,i=hs(jd(s),t,o),l=r.trainingConfig;if(l!=null&&i.loadTrainingConfig(l),r.userDefinedMetadata!=null&&i.setUserDefinedMetadata(r.userDefinedMetadata),r.weightData!=null){if(r.weightSpecs==null)throw new j("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");let{modelWeights:u,optimizerWeights:c}=wU(r.weightData,r.weightSpecs);i.loadWeights(u,a),i.optimizer!=null&&c.length>0&&await i.optimizer.setWeights(c),ne(u),ne(c.map(p=>p.tensor))}return i}function wU(e,t){let n=Cn.decodeWeights(e,t),r={},s=[];return t.forEach(a=>{a.group==="optimizer"?s.push({name:a.name,tensor:n[a.name]}):r[a.name]=n[a.name]}),{modelWeights:r,optimizerWeights:s}}var Fg=class extends Ys{constructor(e){if(super({inputs:[],outputs:[]}),e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:Zm("sequential_"),e.layers!=null)for(let t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some(n=>n<0))throw new j(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){let t=e instanceof Fg||e instanceof Ys,n;if(t){if(n=e,n.outputs.length!==1)throw new j("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");if(n.inputs.length!==1)throw new j("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 j("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");let r=e6({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(r)}if(t)this.outputs=n.outputs,this.inputs=n.inputs;else{if(e.inboundNodes.length!==1)throw new j(`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 j("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=Q7(this.outputs[0])}this.inboundNodes=[],new o0({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:Oi(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(r=>r.shape),outputShapes:this.outputs[0].shape})}else{let r=e.apply(this.outputs[0]);if(Array.isArray(r))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=[r],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1}pop(){if(this.layers.length===0)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),this.layers.length===0)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{let e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(e,t){return this.model==null&&this.build(),this.model.call(e,t)}build(e){if(mt(e),this.inputs.length===0||this.outputs.length===0)throw new TypeError("Sequential model cannot be built: model is empty. Add some layers first.");this.model=new Ys({inputs:this.inputs,outputs:this.outputs[0],name:this.name+"_model"}),this.model.trainable=this.trainable,this.supportsMasking=this.model.supportsMasking,this.inputLayers=this.model.inputLayers,this.inputLayersNodeIndices=this.model.inputLayersNodeIndices,this.inputLayersTensorIndices=this.model.inputLayersTensorIndices,this.outputLayers=this.model.outputLayers,this.outputLayersNodeIndices=this.model.outputLayersNodeIndices,this.outputLayersTensorIndices=this.model.outputLayersTensorIndices,this.nodesByDepth=this.model.nodesByDepth,this.containerNodes=this.model.containerNodes,this.outputNames=this.model.outputNames,this.inputNames=this.model.inputNames,this.built=!0}countParams(){return this.built||this.build(),super.countParams()}summary(e,t,n=console.log){this.built||this.build(),super.summary(e,t,n)}setWeights(e){this.model==null&&this.build(),this.model.setWeights(e)}evaluate(e,t,n={}){if(!this.built)throw new us("The model needs to be compiled before being used.");return this.model.evaluate(e,t,n)}async evaluateDataset(e,t){if(!this.built)throw new us("The model needs to be compiled before being used.");return this.model.evaluateDataset(e,t)}predict(e,t={}){return this.model==null&&this.build(),this.model.predict(e,t)}predictOnBatch(e){return this.model==null&&this.build(),this.model.predictOnBatch(e)}compile(e){this.build(),this.model.compile(e),this.optimizer_=this.model.optimizer,this.isOptimizerOwned=this.model.isOptimizerOwned,this.loss=this.model.loss,this.metrics=this.model.metrics,this.metricsTensors=this.model.metricsTensors,this.metricsNames=this.model.metricsNames}get optimizer(){return this.model==null?void 0:this.model.optimizer}set optimizer(e){this.model.optimizer=e}async fit(e,t,n={}){if(!this.built)throw new us("The model needs to be compiled before being used.");return this.model.fit(e,t,n)}async fitDataset(e,t){if(!this.built)throw new us("The model needs to be compiled before being used.");return this.model.fitDataset(e,t)}async trainOnBatch(e,t){return this.model.trainOnBatch(e,t)}static fromConfig(e,t,n={},r=!1){let s,a={};if(t instanceof Array){if(t[0].className==null||t[0].className==="Merge")throw new j("Legacy serialization format not supported yet.");s=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."),s=t.layers,delete t.layers,a=t;let o=new e(a);if(!(o instanceof Fg))throw new Ve(`Sequential.fromConfig called on non-Sequential input: ${o}`);for(let i of s){let u=hs(i,void 0,r);r&&u.setFastWeightInitDuringBuild(!0),o.add(u)}return o}set stopTraining(e){if(this.model==null)throw new j("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 j("Cannot get the stopTraining property of a sequential model before it is compiled.");return this.model.stopTraining}getConfig(){let e=[];for(let t of this.layers){let n={};n.className=t.getClassName(),n.config=t.getConfig(),e.push(n)}return{name:this.name,layers:e}}},u0=Fg;u0.className="Sequential";ce.registerClass(u0);function kU(e){return new Ys(e)}function SU(e){return new u0(e)}function IU(e,t){return t==null&&(t={}),bU(e,t)}function k6(e){return e6(e)}function CU(e,t){PA.registerCallbackConstructor(e,t)}var ir=class extends ce.Serializable{getConfig(){return{}}},S6=class extends ir{apply(e,t=1){return UL(e,t)}};S6.className="elu";ce.registerClass(S6);var I6=class extends ir{apply(e){return sA(e)}};I6.className="selu";ce.registerClass(I6);var C6=class extends ir{apply(e){return Os(e)}};C6.className="relu";ce.registerClass(C6);var T6=class extends ir{apply(e){return K(()=>Sp(6,Os(e)))}};T6.className="relu6";ce.registerClass(T6);var N6=class extends ir{apply(e){return e}};N6.className="linear";ce.registerClass(N6);var E6=class extends ir{apply(e){return Tn(e)}};E6.className="sigmoid";ce.registerClass(E6);var R6=class extends ir{apply(e){return HL(e)}};R6.className="hardSigmoid";ce.registerClass(R6);var _6=class extends ir{apply(e){return fc(e)}};_6.className="softplus";ce.registerClass(_6);var $6=class extends ir{apply(e){return GL(e)}};$6.className="softsign";ce.registerClass($6);var D6=class extends ir{apply(e){return Su(e)}};D6.className="tanh";ce.registerClass(D6);var WA=class extends ir{apply(e,t=-1){return yc(e,t)}};WA.className="softmax";ce.registerClass(WA);var P6=class extends ir{apply(e,t=-1){return qy(e,t)}};P6.className="logSoftmax";ce.registerClass(P6);var F6=class extends ir{apply(e,t=1){return K(()=>L(Tn(L(e,t)),e))}};F6.className="swish";ce.registerClass(F6);var O6=class extends ir{apply(e){return K(()=>L(e,Su(fc(e))))}};O6.className="mish";ce.registerClass(O6);function Ga(e){return e.getClassName()}function og(e,t={}){return Tp(e,ce.SerializationMap.getMap().classNameMap,t,"activation")}function Ha(e){if(e==null){let t={};return t.className="linear",t.config={},og(t)}if(typeof e=="string"){let t={};return t.className=e,t.config={},og(t)}else return e instanceof ir?e:og(e)}function VA(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 M6=class extends ce.Serializable{},$p=class extends M6{constructor(e){super(),VA(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=Ft([1]);return this.hasL1&&(t=ue(t,ke(L(this.l1,rn(e))))),this.hasL2&&(t=ue(t,ke(L(this.l2,Ep(e))))),H(t,[])})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}};$p.className="L1L2";ce.registerClass($p);function TU(e){return VA(e),new $p({l1:e!=null?e.l1:null,l2:0})}function NU(e){return VA(e),new $p({l2:e!=null?e.l2:null,l1:0})}var gv={l1l2:"L1L2"};function bt(e){return AA(e)}function yv(e,t={}){return Tp(e,ce.SerializationMap.getMap().classNameMap,t,"regularizer")}function _t(e){if(e==null)return null;if(typeof e=="string"){let n={className:e in gv?gv[e]:e,config:{}};return yv(n)}else return e instanceof M6?e:yv(e)}var UA=class extends at{constructor(e){super(e==null?{}:e),this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=He(e);let n=Os(e);return this.maxValue!=null&&(n=yr(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){let e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}};UA.className="ReLU";ce.registerClass(UA);var GA=class extends at{constructor(e){super(e==null?{}:e),this.DEFAULT_ALPHA=.3,e==null&&(e={}),this.alpha=e.alpha==null?this.DEFAULT_ALPHA:e.alpha}call(e,t){let n=He(e);return Nm(n,this.alpha)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};GA.className="LeakyReLU";ce.registerClass(GA);var HA=class extends at{constructor(e){if(super(e==null?{}:e),this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=Rt(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=_t(e.alphaRegularizer),this.alphaConstraint=un(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 j(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=mt(e);let t=e.slice(1);if(this.sharedAxes!=null)for(let r of this.sharedAxes)t[r-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);let n={};if(this.sharedAxes!=null)for(let r=1;r<e.length;++r)n[r]=e[r];this.inputSpec=[new Zt({ndim:e.length,axes:n})],this.built=!0}call(e,t){return e=He(e),Fm(e,this.alpha.read())}getConfig(){let e={alphaInitializer:Ot(this.alphaInitializer),alphaRegularizer:bt(this.alphaRegularizer),alphaConstraint:ln(this.alphaConstraint),sharedAxes:this.sharedAxes},t=super.getConfig();return Object.assign(e,t),e}};HA.className="PReLU";ce.registerClass(HA);var jA=class extends at{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 n=He(e);return wp(n)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};jA.className="ELU";ce.registerClass(jA);var qA=class extends at{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 n=He(e);return L(n,ge(Ar(n,this.theta),"float32"))}computeOutputShape(e){return e}getConfig(){let e={theta:this.theta},t=super.getConfig();return Object.assign(e,t),e}};qA.className="ThresholdedReLU";ce.registerClass(qA);var XA=class extends at{constructor(e){super(e==null?{}:e),this.DEFAULT_AXIS=1,e==null&&(e={}),this.softmax=new WA().apply,this.axis=e.axis==null?this.DEFAULT_AXIS:e.axis}call(e,t){let n=He(e);return this.softmax(n,this.axis)}computeOutputShape(e){return e}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};XA.className="Softmax";ce.registerClass(XA);function bu(e,t,n){if(typeof e=="number")return Oi(e,t);if(e.length!==t)throw new j(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${e.length} elements.`);for(let r=0;r<t;++r){let s=e[r];if(!LL(s))throw new j(`The ${n} argument must be an integer or tuple of ${t} integers. Received: ${JSON.stringify(e)} including a non-integer number ${s}`)}return e}function fs(e,t,n,r,s=1){if(e==null)return e;let a=t+(t-1)*(s-1),o;return n==="same"?o=e:o=e-a+1,Math.floor((o+r-1)/r)}function Ns(e,t,n,r){if(e==null)return null;if(r==="valid")e=e*t+Ua([n-t,0]);else if(r==="same")e=e*t;else throw new j(`Unsupport padding mode: ${r}.`);return e}function KA(e,t){return K(()=>(Ht(t),t==="channelsFirst"?et(e,[0,2,3,1]):e))}function z6(e,t){return K(()=>(Ht(t),t==="channelsFirst"?et(e,[0,2,3,4,1]):e))}function EU(e,t,n,r=1,s="valid",a,o=1){return K(()=>{if(a==null&&(a=ys()),Ht(a),e.shape.length!==3)throw new j(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(t.shape.length!==3)throw new j(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(n!=null&&n.shape.length!==1)throw new j(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(a==="channelsFirst"&&(e=et(e,[0,2,1])),s==="causal")throw new Ve("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let i=Ly(e,t,r,s==="same"?"same":"valid","NWC",o);return n!=null&&(i=bs(i,n)),i})}function Av(e,t,n,r=[1,1],s="valid",a,o,i=null){return K(()=>{if(a==null&&(a=ys()),Ht(a),e.rank!==3&&e.rank!==4)throw new j(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(t.rank!==3&&t.rank!==4)throw new j(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=KA(e,a);if(s==="causal")throw new Ve("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=Va.conv2d({x:l,filter:t,strides:r,pad:s==="same"?"same":"valid",dilations:o,dataFormat:"NHWC",bias:n,activation:i}),a==="channelsFirst"&&(l=et(l,[0,3,1,2])),l})}function RU(e,t,n,r=[1,1,1],s="valid",a,o){return K(()=>{if(a==null&&(a=ys()),Ht(a),e.rank!==4&&e.rank!==5)throw new j(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(t.rank!==4&&t.rank!==5)throw new j(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let i=z6(e,a);if(s==="causal")throw new Ve("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return i=Vy(i,t,r,s==="same"?"same":"valid","NDHWC",o),n!=null&&(i=bs(i,n)),a==="channelsFirst"&&(i=et(i,[0,4,1,2,3])),i})}var ZA=class extends at{constructor(e,t){if(super(t),this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",ZA.verifyArgs(t),this.rank=e,mn(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=bu(t.kernelSize,e,"kernelSize"),this.strides=bu(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,Lr(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,Ht(this.dataFormat),this.activation=Ha(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=Rt(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=un(t.biasConstraint),this.biasRegularizer=_t(t.biasRegularizer),this.activityRegularizer=_t(t.activityRegularizer),this.dilationRate=bu(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new j(`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 j(`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 j(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if(Ts("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!xA(e.kernelSize,"number",1,3))throw new j(`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:Ga(this.activation),useBias:this.useBias,biasInitializer:Ot(this.biasInitializer),biasRegularizer:bt(this.biasRegularizer),activityRegularizer:bt(this.activityRegularizer),biasConstraint:ln(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}},Dp=class extends ZA{constructor(e,t){super(e,t),this.kernel=null,Dp.verifyArgs(t),this.filters=t.filters,mn(this.filters,"filters"),this.kernelInitializer=Rt(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=un(t.kernelConstraint),this.kernelRegularizer=_t(t.kernelRegularizer)}build(e){e=mt(e);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new j(`The channel dimension of the input should be defined. Found ${e[t]}`);let n=e[t],r=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",r,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[t]:n}}],this.built=!0}call(e,t){return K(()=>{e=He(e);let n,r=this.bias==null?null:this.bias.read(),s=G7(this.activation.getClassName());if(s!=null&&this.rank===2)n=Av(e,this.kernel.read(),r,this.strides,this.padding,this.dataFormat,this.dilationRate,s);else{if(this.rank===1)n=EU(e,this.kernel.read(),r,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)n=Av(e,this.kernel.read(),r,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)n=RU(e,this.kernel.read(),r,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new Ve("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(n=this.activation.apply(n))}return n})}computeOutputShape(e){e=mt(e);let t=[],n=this.dataFormat==="channelsLast"?e.slice(1,e.length-1):e.slice(2);for(let s=0;s<n.length;++s){let a=fs(n[s],this.kernelSize[s],this.padding,this.strides[s],typeof this.dilationRate=="number"?this.dilationRate:this.dilationRate[s]);t.push(a)}let r=[e[0]];return this.dataFormat==="channelsLast"?(r=r.concat(t),r.push(this.filters)):(r.push(this.filters),r=r.concat(t)),r}getConfig(){let e={filters:this.filters,kernelInitializer:Ot(this.kernelInitializer),kernelRegularizer:bt(this.kernelRegularizer),kernelConstraint:ln(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 j(`Convolution layer expected config.filters to be a 'number' > 0 but got ${JSON.stringify(e.filters)}`)}},L6=class extends Dp{constructor(e){super(2,e),L6.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!xA(e.kernelSize,"number",1,2))throw new j(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}},c0=L6;c0.className="Conv2D";ce.registerClass(c0);var B6=class extends Dp{constructor(e){super(3,e),B6.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 j(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}},d0=B6;d0.className="Conv3D";ce.registerClass(d0);var YA=class extends c0{constructor(e){if(super(e),this.inputSpec=[new Zt({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new j(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=mt(e),e.length!==4)throw new j("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 j("The channel dimension of the inputs should be defined. Found `None`.");let n=e[t],r=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",r,"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 Zt({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return K(()=>{let n=He(e);if(n.shape.length!==4)throw new j(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);let r=n.shape,s=r[0],a,o;this.dataFormat==="channelsFirst"?(a=2,o=3):(a=1,o=2);let i=r[a],l=r[o],u=this.kernelSize[0],c=this.kernelSize[1],p=this.strides[0],d=this.strides[1],h=Ns(i,p,u,this.padding),f=Ns(l,d,c,this.padding),m=[s,h,f,this.filters];this.dataFormat!=="channelsLast"&&(n=et(n,[0,2,3,1]));let g=Wy(n,this.kernel.read(),m,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(g=et(g,[0,3,1,2])),this.bias!=null&&(g=bs(g,this.bias.read(),this.dataFormat)),this.activation!=null&&(g=this.activation.apply(g)),g})}computeOutputShape(e){e=mt(e);let t=e.slice(),n,r,s;this.dataFormat==="channelsFirst"?(n=1,r=2,s=3):(n=3,r=1,s=2);let a=this.kernelSize[0],o=this.kernelSize[1],i=this.strides[0],l=this.strides[1];return t[n]=this.filters,t[r]=Ns(t[r],i,a,this.padding),t[s]=Ns(t[s],l,o,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};YA.className="Conv2DTranspose";ce.registerClass(YA);var JA=class extends d0{constructor(e){if(super(e),this.inputSpec=[new Zt({ndim:5})],this.padding!=="same"&&this.padding!=="valid")throw new j(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=mt(e),e.length!==5)throw new j("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 j("The channel dimension of the inputs should be defined. Found `None`.");let n=e[t],r=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",r,"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 Zt({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return K(()=>{let n=He(e);if(n.shape.length!==5)throw new j(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);let r=n.shape,s=r[0],a,o,i;this.dataFormat==="channelsFirst"?(i=2,a=3,o=4):(i=1,a=2,o=3);let l=r[i],u=r[a],c=r[o],p=this.kernelSize[0],d=this.kernelSize[1],h=this.kernelSize[2],f=this.strides[0],m=this.strides[1],g=this.strides[2],y=Ns(l,f,p,this.padding),x=Ns(u,m,d,this.padding),A=Ns(c,g,h,this.padding),b=[s,y,x,A,this.filters];this.dataFormat!=="channelsLast"&&(n=et(n,[0,2,3,4,1]));let v=Xw(n,this.kernel.read(),b,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(v=et(v,[0,4,1,2,3])),this.bias!==null&&(v=bs(v,this.bias.read(),this.dataFormat)),this.activation!==null&&(v=this.activation.apply(v)),v})}computeOutputShape(e){e=mt(e);let t=e.slice(),n,r,s,a;this.dataFormat==="channelsFirst"?(n=1,r=2,s=3,a=4):(n=4,r=1,s=2,a=3);let o=this.kernelSize[0],i=this.kernelSize[1],l=this.kernelSize[2],u=this.strides[0],c=this.strides[1],p=this.strides[2];return t[n]=this.filters,t[r]=Ns(t[r],u,o,this.padding),t[s]=Ns(t[s],c,i,this.padding),t[a]=Ns(t[a],p,l,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};JA.className="Conv3DTranspose";ce.registerClass(JA);var W6=class extends Dp{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 j("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new j("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 j(`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=Rt(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=_t(t.depthwiseRegularizer),this.depthwiseConstraint=un(t.depthwiseConstraint),this.pointwiseInitializer=Rt(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=_t(t.pointwiseRegularizer),this.pointwiseConstraint=un(t.pointwiseConstraint)}build(e){if(e=mt(e),e.length<this.rank+2)throw new j(`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 j(`The channel dimension of the inputs should be defined, but found ${JSON.stringify(e[t])}`);let n=e[t],r=this.kernelSize.concat([n,this.depthMultiplier]),s=[];for(let o=0;o<this.rank;++o)s.push(1);s.push(n*this.depthMultiplier,this.filters);let a=!0;this.depthwiseKernel=this.addWeight("depthwise_kernel",r,"float32",this.depthwiseInitializer,this.depthwiseRegularizer,a,this.depthwiseConstraint),this.pointwiseKernel=this.addWeight("pointwise_kernel",s,"float32",this.pointwiseInitializer,this.pointwiseRegularizer,a,this.pointwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,a,this.biasConstraint):this.bias=null,this.inputSpec=[new Zt({ndim:this.rank+2,axes:{[t]:n}})],this.built=!0}call(e,t){return K(()=>{e=He(e);let n;if(this.rank===1)throw new Ve("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=et(e,[0,2,3,1])),n=m7(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(n=bs(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),this.dataFormat==="channelsFirst"&&(n=et(n,[0,3,1,2])),n})}getConfig(){let e=super.getConfig();return delete e.rank,delete e.kernelInitializer,delete e.kernelRegularizer,delete e.kernelConstraint,e.depthwiseInitializer=Ot(this.depthwiseInitializer),e.pointwiseInitializer=Ot(this.pointwiseInitializer),e.depthwiseRegularizer=bt(this.depthwiseRegularizer),e.pointwiseRegularizer=bt(this.pointwiseRegularizer),e.depthwiseConstraint=ln(this.depthwiseConstraint),e.pointwiseConstraint=ln(this.pointwiseConstraint),e}};W6.className="SeparableConv";var QA=class extends W6{constructor(e){super(2,e)}};QA.className="SeparableConv2D";ce.registerClass(QA);var V6=class extends Dp{constructor(e){super(1,e),V6.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"&&!xA(e.kernelSize,"number",1,1))throw new j(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}},ex=V6;ex.className="Conv1D";ce.registerClass(ex);var tx=class extends at{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=He(e),this.dataFormat==="channelsLast"){let n=Xh(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Xh(n,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{let n=Xh(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Xh(n,this.cropping[1][0],e.shape[3]-this.cropping[1][1]-this.cropping[1][0],4)}})}getConfig(){let e={cropping:this.cropping,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};tx.className="Cropping2D";ce.registerClass(tx);var nx=class extends at{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,Ht(this.dataFormat),this.interpolation=e.interpolation==null?"nearest":e.interpolation,OL(this.interpolation)}computeOutputShape(e){if(this.dataFormat==="channelsFirst"){let t=e[2]==null?null:this.size[0]*e[2],n=e[3]==null?null:this.size[1]*e[3];return[e[0],e[1],t,n]}else{let t=e[1]==null?null:this.size[0]*e[1],n=e[2]==null?null:this.size[1]*e[2];return[e[0],t,n,e[3]]}}call(e,t){return K(()=>{let n=He(e),r=n.shape;if(this.dataFormat==="channelsFirst"){n=et(n,[0,2,3,1]);let s=this.size[0]*r[2],a=this.size[1]*r[3],o=this.interpolation==="nearest"?Se.resizeNearestNeighbor(n,[s,a]):Se.resizeBilinear(n,[s,a]);return et(o,[0,3,1,2])}else{let s=this.size[0]*r[1],a=this.size[1]*r[2];return this.interpolation==="nearest"?Se.resizeNearestNeighbor(n,[s,a]):Se.resizeBilinear(n,[s,a])}})}getConfig(){let e={size:this.size,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};nx.className="UpSampling2D";ce.registerClass(nx);function _U(e,t,n=[1,1],r="valid",s,a){return K(()=>{s==null&&(s=ys()),Ht(s);let o=KA(e,s);if(e.rank!==4)throw new j(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(t.rank!==4)throw new j(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return o=vp(o,t,n,r==="same"?"same":"valid","NHWC",a),s==="channelsFirst"&&(o=et(o,[0,3,1,2])),o})}var rx=class extends ZA{constructor(e){super(2,e),this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=Rt(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=un(e.depthwiseConstraint),this.depthwiseRegularizer=_t(e.depthwiseRegularizer)}build(e){if(e=mt(e),e.length<4)throw new j(`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 j(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);let n=e[t],r=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",r,null,this.depthwiseInitializer,this.depthwiseRegularizer,!0,this.depthwiseConstraint),this.useBias?this.bias=this.addWeight("bias",[n*this.depthMultiplier],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return K(()=>{e=He(e);let n=_U(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(n=bs(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),n})}computeOutputShape(e){e=mt(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],r=this.dataFormat==="channelsFirst"?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,s=fs(t,this.kernelSize[0],this.padding,this.strides[0]),a=fs(n,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[e[0],r,s,a]:[e[0],s,a,r]}getConfig(){let e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=Ot(this.depthwiseInitializer),e.depthwiseRegularizer=bt(this.depthwiseRegularizer),e.depthwiseConstraint=ln(this.depthwiseRegularizer),e}};rx.className="DepthwiseConv2D";ce.registerClass(rx);function U6(e,t,n,r){if(Array.isArray(e)){if(t!=null||n!=null)throw new j("When inputs is an array, neither initialState or constants should be provided");r!=null&&(n=e.slice(e.length-r,e.length),e=e.slice(0,e.length-r)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function s(a){return a==null||Array.isArray(a)?a:[a]}return t=s(t),n=s(n),{inputs:e,initialState:t,constants:n}}function G6(e,t,n,r=!1,s,a,o=!1,i=!1){return K(()=>{let l=t.shape.length;if(l<3)throw new j(`Input should be at least 3D, but is ${l}D.`);let u=[1,0].concat(gs(2,l));if(t=et(t,u),a!=null)throw new Ve("The rnn() functoin of the deeplearn.js backend does not support constants yet.");o&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),s!=null&&(s=ge(ge(s,"bool"),"float32"),s.rank===l-1&&(s=Kt(s,-1)),s=et(s,u)),r&&(t=Fr(t,0),s!=null&&(s=Fr(s,0)));let c=[],p,d=n,h=t.shape[0],f=rr(t),m;s!=null&&(m=rr(s));for(let y=0;y<h;++y){let x=f[y],A=K(()=>e(x,d));if(s==null)p=A[0],d=A[1];else{let b=K(()=>{let v=m[y],S=he(Pr(v),v),I=ue(L(A[0],v),L(d[0],S)),E=d.map((R,P)=>ue(L(A[1][P],v),L(R,S)));return{output:I,newStates:E}});p=b.output,d=b.newStates}i&&c.push(p)}let g;return i&&(g=cn(c,1)),[p,g,d]})}var H6=class extends at{constructor(e){super(e);let t;if(e.cell==null)throw new j("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new f0({cells:e.cell}):t=e.cell,t.stateSize==null)throw new j("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 Zt({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 gs(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){Ng(e)&&(e=e[0]),e=e;let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);let n=t[0],r;if(this.returnSequences?r=[e[0],e[1],n]:r=[e[0],n],this.returnState){let s=[];for(let a of t)s.push([e[0],a]);return[r].concat(s)}else return r}computeMask(e,t){return K(()=>{Array.isArray(t)&&(t=t[0]);let n=this.returnSequences?t:null;if(this.returnState){let r=this.states.map(s=>null);return[n].concat(r)}else return n})}get states(){if(this.states_==null){let e=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1,t=[];for(let n=0;n<e;++n)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.");Ng(e)&&(e=e[0]),e=e;let n=this.stateful?e[0]:null,r=e.slice(2);this.inputSpec[0]=new Zt({shape:[n,null,...r]});let s=[e[0]].concat(e.slice(2));this.cell.build(s);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(o=>o.shape[o.shape.length-1]),a))throw new j(`An initialState was passed that is not compatible with cell.stateSize. Received stateSpec=${this.stateSpec}; However cell.stateSize is ${this.cell.stateSize}`)}else this.stateSpec=a.map(o=>new Zt({shape:[null,o]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){K(()=>{if(!this.stateful)throw new js("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape[0];if(n==null)throw new j("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(r=>Ft([n,r])):this.states_=[Ft([n,this.cell.stateSize])];else if(e==null)ne(this.states_),this.keptStates!=null&&(ne(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(r=>Ft([n,r])):this.states_[0]=Ft([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new j(`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()):ne(this.states_);for(let r=0;r<this.states_.length;++r){let s=e[r],a=Array.isArray(this.cell.stateSize)?this.cell.stateSize[r]:this.cell.stateSize,o=[n,a];if(!w.arraysEqual(s.shape,o))throw new j(`State ${r} is incompatible with layer ${this.name}: expected shape=${o}, received shape=${s.shape}`);this.states_[r]=s}}this.states_=this.states_.map(r=>fn(r.clone()))})}apply(e,t){let n=t==null?null:t.initialState,r=t==null?null:t.constants;t==null&&(t={});let s=U6(e,n,r,this.numConstants);e=s.inputs,n=s.initialState,r=s.constants;let a=[],o=[];if(n!=null){t.initialState=n,a=a.concat(n),this.stateSpec=[];for(let l of n)this.stateSpec.push(new Zt({shape:l.shape}));o=o.concat(this.stateSpec)}if(r!=null&&(t.constants=r,a=a.concat(r),this.numConstants=r.length),a[0]instanceof cs){let l=[e].concat(a),u=this.inputSpec.concat(o),c=this.inputSpec;this.inputSpec=u;let p=super.apply(l,t);return this.inputSpec=c,p}else return super.apply(e,t)}call(e,t){return K(()=>{let n=t==null?null:t.mask,r=t==null?null:t.training,s=t==null?null:t.initialState;e=He(e),s==null&&(this.stateful?s=this.states_:s=this.getInitialState(e));let a=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(s.length!==a)throw new j(`RNN Layer has ${a} state(s) but was passed ${s.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");let o={training:r},l=G6((h,f)=>{let m=this.cell.call([h].concat(f),o);return[m[0],m.slice(1)]},e,s,this.goBackwards,n,null,this.unroll,this.returnSequences),u=l[0],c=l[1],p=l[2];this.stateful&&this.resetStates(p,r);let d=this.returnSequences?c:u;return this.returnState?[d].concat(p):d})}getInitialState(e){return K(()=>{let t=Ft(e.shape);return t=ke(t,[1,2]),t=Np(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(n=>n>1?Cg(t,[1,n]):t):this.cell.stateSize>1?[Cg(t,[1,this.cell.stateSize])]:[t]})}get trainableWeights(){return this.trainable?this.cell.trainableWeights:[]}get nonTrainableWeights(){return this.trainable?this.cell.nonTrainableWeights:this.cell.weights}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.cell!=null&&this.cell.setFastWeightInitDuringBuild(e)}getConfig(){let e=super.getConfig(),t={returnSequences:this.returnSequences,returnState:this.returnState,goBackwards:this.goBackwards,stateful:this.stateful,unroll:this.unroll};this.numConstants!=null&&(t.numConstants=this.numConstants);let n=this.cell.getConfig();return this.getClassName()===H6.className&&(t.cell={className:this.cell.getClassName(),config:n}),{...n,...e,...t}}static fromConfig(e,t,n={}){let r=t.cell,s=hs(r,n);return new e(Object.assign(t,{cell:s}))}},oa=H6;oa.className="RNN";ce.registerClass(oa);var Pp=class extends at{},p0=class extends Pp{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,mn(this.units,"units"),this.activation=Ha(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Rt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Rt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Rt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=_t(e.kernelRegularizer),this.recurrentRegularizer=_t(e.recurrentRegularizer),this.biasRegularizer=_t(e.biasRegularizer),this.kernelConstraint=un(e.kernelConstraint),this.recurrentConstraint=un(e.recurrentConstraint),this.biasConstraint=un(e.biasConstraint),this.dropout=Eu([1,Ua([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Eu([1,Ua([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=mt(e),this.kernel=this.addWeight("kernel",[e[e.length-1],this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return K(()=>{if(e=e,e.length!==2)throw new j(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];let r=t.training==null?!1:t.training;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=ja({ones:()=>Pr(e),rate:this.dropout,training:r,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=ja({ones:()=>Pr(n),rate:this.recurrentDropout,training:r,dropoutFunc:this.dropoutFunc}));let s,a=this.dropoutMask,o=this.recurrentDropoutMask;a!=null?s=Rs(L(e,a),this.kernel.read()):s=Rs(e,this.kernel.read()),this.bias!=null&&(s=bs(s,this.bias.read())),o!=null&&(n=L(n,o));let i=ue(s,Rs(n,this.recurrentKernel.read()));return this.activation!=null&&(i=this.activation.apply(i)),[i,i]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:Ga(this.activation),useBias:this.useBias,kernelInitializer:Ot(this.kernelInitializer),recurrentInitializer:Ot(this.recurrentInitializer),biasInitializer:Ot(this.biasInitializer),kernelRegularizer:bt(this.kernelRegularizer),recurrentRegularizer:bt(this.recurrentRegularizer),biasRegularizer:bt(this.biasRegularizer),activityRegularizer:bt(this.activityRegularizer),kernelConstraint:ln(this.kernelConstraint),recurrentConstraint:ln(this.recurrentConstraint),biasConstraint:ln(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return{...e,...t}}};p0.className="SimpleRNNCell";ce.registerClass(p0);var sx=class extends oa{constructor(e){e.cell=new p0(e),super(e)}call(e,t){return K(()=>{this.cell.dropoutMask!=null&&(ne(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(ne(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,r=t==null?null:t.training,s=t==null?null:t.initialState;return super.call(e,{mask:n,training:r,initialState:s})})}static fromConfig(e,t){return new e(t)}};sx.className="SimpleRNN";ce.registerClass(sx);var h0=class extends Pp{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 j("GRUCell does not support reset_after parameter set to true.");this.units=e.units,mn(this.units,"units"),this.activation=Ha(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Ha(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Rt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Rt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Rt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=_t(e.kernelRegularizer),this.recurrentRegularizer=_t(e.recurrentRegularizer),this.biasRegularizer=_t(e.biasRegularizer),this.kernelConstraint=un(e.kernelConstraint),this.recurrentConstraint=un(e.recurrentConstraint),this.biasConstraint=un(e.biasConstraint),this.dropout=Eu([1,Ua([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Eu([1,Ua([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=mt(e);let t=e[e.length-1];this.kernel=this.addWeight("kernel",[t,this.units*3],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*3],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias?this.bias=this.addWeight("bias",[this.units*3],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint):this.bias=null,this.built=!0}call(e,t){return K(()=>{if(e=e,e.length!==2)throw new j(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);let n=t.training==null?!1:t.training,r=e[1];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=ja({ones:()=>Pr(e),rate:this.dropout,training:n,count:3,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=ja({ones:()=>Pr(r),rate:this.recurrentDropout,training:n,count:3,dropoutFunc:this.dropoutFunc}));let s=this.dropoutMask,a=this.recurrentDropoutMask,o,i,l;0<this.dropout&&this.dropout<1&&(e=L(e,s[0]));let u=Rs(e,this.kernel.read());this.useBias&&(u=bs(u,this.bias.read())),0<this.recurrentDropout&&this.recurrentDropout<1&&(r=L(r,a[0]));let c=this.recurrentKernel.read(),[p,d]=Yt(c,[2*this.units,this.units],c.rank-1),h=Rs(r,p),[f,m,g]=Yt(u,3,u.rank-1),[y,x]=Yt(h,2,h.rank-1);o=this.recurrentActivation.apply(ue(f,y)),i=this.recurrentActivation.apply(ue(m,x));let A=Rs(L(i,r),d);l=this.activation.apply(ue(g,A));let b=ue(L(o,r),L(ue(1,zt(o)),l));return[b,b]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:Ga(this.activation),recurrentActivation:Ga(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Ot(this.kernelInitializer),recurrentInitializer:Ot(this.recurrentInitializer),biasInitializer:Ot(this.biasInitializer),kernelRegularizer:bt(this.kernelRegularizer),recurrentRegularizer:bt(this.recurrentRegularizer),biasRegularizer:bt(this.biasRegularizer),activityRegularizer:bt(this.activityRegularizer),kernelConstraint:ln(this.kernelConstraint),recurrentConstraint:ln(this.recurrentConstraint),biasConstraint:ln(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation,resetAfter:!1};return{...e,...t}}};h0.className="GRUCell";ce.registerClass(h0);var ax=class extends oa{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 h0(e),super(e)}call(e,t){return K(()=>{this.cell.dropoutMask!=null&&(ne(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(ne(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,r=t==null?null:t.training,s=t==null?null:t.initialState;return super.call(e,{mask:n,training:r,initialState:s})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};ax.className="GRU";ce.registerClass(ax);var Fp=class extends Pp{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,mn(this.units,"units"),this.activation=Ha(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Ha(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Rt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Rt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Rt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=_t(e.kernelRegularizer),this.recurrentRegularizer=_t(e.recurrentRegularizer),this.biasRegularizer=_t(e.biasRegularizer),this.kernelConstraint=un(e.kernelConstraint),this.recurrentConstraint=un(e.recurrentConstraint),this.biasConstraint=un(e.biasConstraint),this.dropout=Eu([1,Ua([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=Eu([1,Ua([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.dropoutFunc=e.dropoutFunc,this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;e=mt(e);let n=e[e.length-1];this.kernel=this.addWeight("kernel",[n,this.units*4],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.recurrentKernel=this.addWeight("recurrent_kernel",[this.units,this.units*4],null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint);let r;if(this.useBias){if(this.unitForgetBias){let s=this.biasInitializer,a=this.units;r=new(t=class extends Zr{apply(o,i){let l=s.apply([a]),u=new Qm().apply([a]),c=s.apply([a*2]);return Zb(Zb(l,u),c)}},t.className="CustomInit",t)}else r=this.biasInitializer;this.bias=this.addWeight("bias",[this.units*4],null,r,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return K(()=>{let n=t.training==null?!1:t.training;if(e=e,e.length!==3)throw new j(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let r=e[1],s=e[2];e=e[0],0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=ja({ones:()=>Pr(e),rate:this.dropout,training:n,count:4,dropoutFunc:this.dropoutFunc})),0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=ja({ones:()=>Pr(r),rate:this.recurrentDropout,training:n,count:4,dropoutFunc:this.dropoutFunc}));let a=this.dropoutMask,o=this.recurrentDropoutMask,i,l,u,c;0<this.dropout&&this.dropout<1&&(e=L(e,a[0]));let p=Rs(e,this.kernel.read());0<this.recurrentDropout&&this.recurrentDropout<1&&(r=L(r,o[0])),p=ue(p,Rs(r,this.recurrentKernel.read())),this.useBias&&(p=bs(p,this.bias.read()));let[d,h,f,m]=Yt(p,4,p.rank-1);i=this.recurrentActivation.apply(d),l=this.recurrentActivation.apply(h),u=ue(L(l,s),L(i,this.activation.apply(f))),c=this.recurrentActivation.apply(m);let g=L(c,this.activation.apply(u));return[g,g,u]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:Ga(this.activation),recurrentActivation:Ga(this.recurrentActivation),useBias:this.useBias,kernelInitializer:Ot(this.kernelInitializer),recurrentInitializer:Ot(this.recurrentInitializer),biasInitializer:Ot(this.biasInitializer),unitForgetBias:this.unitForgetBias,kernelRegularizer:bt(this.kernelRegularizer),recurrentRegularizer:bt(this.recurrentRegularizer),biasRegularizer:bt(this.biasRegularizer),activityRegularizer:bt(this.activityRegularizer),kernelConstraint:ln(this.kernelConstraint),recurrentConstraint:ln(this.recurrentConstraint),biasConstraint:ln(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout,implementation:this.implementation};return{...e,...t}}};Fp.className="LSTMCell";ce.registerClass(Fp);var ox=class extends oa{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 Fp(e),super(e)}call(e,t){return K(()=>{this.cell.dropoutMask!=null&&(ne(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(ne(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,r=t==null?null:t.training,s=t==null?null:t.initialState;return super.call(e,{mask:n,training:r,initialState:s})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};ox.className="LSTM";ce.registerClass(ox);var f0=class extends Pp{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 n=e.slice(1),r=[];for(let o of this.cells.slice().reverse())Array.isArray(o.stateSize)?r.push(n.splice(0,o.stateSize.length)):r.push(n.splice(0,1));r.reverse();let s=[],a;for(let o=0;o<this.cells.length;++o){let i=this.cells[o];n=r[o],o===0?a=[e[0]].concat(n):a=[a[0]].concat(n),a=i.call(a,t),s.push(a.slice(1))}n=[];for(let o of s.slice().reverse())n.push(...o);return[a[0]].concat(n)})}build(e){Ng(e)&&(e=e[0]),e=e;let t;this.cells.forEach((n,r)=>{Ni(`RNNCell_${r}`,()=>{n.build(e),Array.isArray(n.stateSize)?t=n.stateSize[0]:t=n.stateSize,e=[e[0],t]})}),this.built=!0}getConfig(){let e=super.getConfig(),t=s=>({className:s.getClassName(),config:s.getConfig()}),r={cells:this.cells.map(t)};return{...e,...r}}static fromConfig(e,t,n={}){let r=[];for(let s of t.cells)r.push(hs(s,n));return new e({cells:r})}get trainableWeights(){if(!this.trainable)return[];let e=[];for(let t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){let e=[];for(let t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){let t=[];for(let n of this.cells)t.push(...n.trainableWeights);return t.concat(e)}return e}getWeights(){let e=[];for(let t of this.cells)e.push(...t.weights);return Eg(e)}setWeights(e){let t=[];for(let n of this.cells){let r=n.weights.length,s=e.splice(r);for(let a=0;a<n.weights.length;++a)t.push([n.weights[a],s[a]])}NA(t)}};f0.className="StackedRNNCells";ce.registerClass(f0);function ja(e){let{ones:t,rate:n,training:r=!1,count:s=1,dropoutFunc:a}=e,o=()=>a!=null?a(t(),n):Y7(t(),n),i=()=>Rp(o,t,r);return!s||s<=1?fn(i().clone()):Array(s).fill(void 0).map(i).map(u=>fn(u.clone()))}var j6=class extends oa{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 Zt({ndim:5})]}call(e,t){return K(()=>{if(this.cell.dropoutMask!=null&&(ne(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(ne(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new j("ConvRNN2D cell does not support constants");let n=t==null?null:t.mask,r=t==null?null:t.training,s=t==null?null:t.initialState;return super.call(e,{mask:n,training:r,initialState:s})})}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,n=e.shape,r=this.computeSingleOutputShape(n),s=[r[0],...r.slice(2)],a=Ft(s);return Array.isArray(t)?Array(t.length).fill(a):[a]})}resetStates(e,t=!1){K(()=>{if(!this.stateful)throw new js("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape,r=this.computeSingleOutputShape(n),s=[r[0],...r.slice(2)];if(n[0]==null)throw new j("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(()=>Ft(s)):this.states_=[Ft(s)];else if(e==null)ne(this.states_),this.keptStates!=null&&(ne(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>Ft(s)):this.states_[0]=Ft(s);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new j(`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()):ne(this.states_);for(let o=0;o<this.states_.length;++o){let i=e[o],l=s;if(!w.arraysEqual(i.shape,l))throw new j(`State ${o} is incompatible with layer ${this.name}: expected shape=${l}, received shape=${i.shape}`);this.states_[o]=i}}this.states_=this.states_.map(o=>fn(o.clone()))})}computeSingleOutputShape(e){let{dataFormat:t,filters:n,kernelSize:r,padding:s,strides:a,dilationRate:o}=this.cell,i=t==="channelsFirst",l=e[i?3:2],u=e[i?4:3],c=fs(l,r[0],s,a[0],o[0]),p=fs(u,r[1],s,a[1],o[1]);return[...e.slice(0,2),...i?[n,c,p]:[c,p,n]]}};j6.className="ConvRNN2D";var m0=class extends Fp{constructor(e){let{filters:t,kernelSize:n,strides:r,padding:s,dataFormat:a,dilationRate:o}=e;super({...e,units:t}),this.filters=t,mn(this.filters,"filters"),this.kernelSize=bu(n,2,"kernelSize"),this.kernelSize.forEach(i=>mn(i,"kernelSize")),this.strides=bu(r||1,2,"strides"),this.strides.forEach(i=>mn(i,"strides")),this.padding=s||"valid",Lr(this.padding),this.dataFormat=a||"channelsLast",Ht(this.dataFormat),this.dilationRate=bu(o||1,2,"dilationRate"),this.dilationRate.forEach(i=>mn(i,"dilationRate"))}build(e){var t;e=mt(e);let n=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[n]==null)throw new j(`The channel dimension of the input should be defined. Found ${e[n]}`);let r=e[n],s=4,a=this.kernelSize.concat([r,this.filters*s]);this.kernel=this.addWeight("kernel",a,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);let o=this.kernelSize.concat([this.filters,this.filters*s]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",o,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let i;if(this.unitForgetBias){let l=this.biasInitializer,u=this.filters;i=new(t=class extends Zr{apply(c,p){let d=l.apply([u]),h=gr([u]),f=l.apply([u*2]);return bA([d,h,f])}},t.className="CustomInit",t)}else i=this.biasInitializer;this.bias=this.addWeight("bias",[this.filters*s],null,i,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return K(()=>{if(e.length!==3)throw new j(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let n=t.training||!1,r=e[0],s=e[1],a=e[2],o=4;0<this.dropout&&this.dropout<1&&this.dropoutMask==null&&(this.dropoutMask=ja({ones:()=>Pr(r),rate:this.dropout,training:n,count:o,dropoutFunc:this.dropoutFunc}));let i=this.dropoutMask,l=(W,ee,Q)=>!ee||!ee[Q]?W:L(ee[Q],W),u=l(r,i,0),c=l(r,i,1),p=l(r,i,2),d=l(r,i,3);0<this.recurrentDropout&&this.recurrentDropout<1&&this.recurrentDropoutMask==null&&(this.recurrentDropoutMask=ja({ones:()=>Pr(s),rate:this.recurrentDropout,training:n,count:o,dropoutFunc:this.dropoutFunc}));let h=this.recurrentDropoutMask,f=l(s,h,0),m=l(s,h,1),g=l(s,h,2),y=l(s,h,3),x=3,[A,b,v,S]=Yt(this.kernel.read(),o,x),[I,E,R,P]=this.useBias?Yt(this.bias.read(),o):[null,null,null,null];u=this.inputConv(u,A,I,this.padding),c=this.inputConv(c,b,E,this.padding),p=this.inputConv(p,v,R,this.padding),d=this.inputConv(d,S,P,this.padding);let[_,D,T,F]=Yt(this.recurrentKernel.read(),o,x);f=this.recurrentConv(f,_),m=this.recurrentConv(m,D),g=this.recurrentConv(g,T),y=this.recurrentConv(y,F);let U=this.recurrentActivation.apply(ue(u,f)),X=this.recurrentActivation.apply(ue(c,m)),z=ue(L(X,a),L(U,this.activation.apply(ue(p,g)))),Z=L(this.recurrentActivation.apply(ue(d,y)),this.activation.apply(z));return[Z,Z,z]})}getConfig(){let{units:e,...t}=super.getConfig(),n={filters:this.filters,kernelSize:this.kernelSize,padding:this.padding,dataFormat:this.dataFormat,dilationRate:this.dilationRate,strides:this.strides};return{...t,...n}}inputConv(e,t,n,r){let s=La(e,t,this.strides,r||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return n?bs(s,n,this.dataFormat):s}recurrentConv(e,t){return La(e,t,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}};m0.className="ConvLSTM2DCell";ce.registerClass(m0);var ix=class extends j6{constructor(e){let t=new m0(e);super({...e,cell:t})}static fromConfig(e,t){return new e(t)}};ix.className="ConvLSTM2D";ce.registerClass(ix);var g0=class extends at{constructor(e){super(e),this.rate=Math.max(Math.min(e.rate,1),0),this.noiseShape=e.noiseShape,this.seed=e.seed,this.supportsMasking=!0}getNoiseShape(e){if(this.noiseShape==null)return this.noiseShape;let t=e.shape,n=[];for(let r=0;r<this.noiseShape.length;++r)n.push(this.noiseShape[r]==null?t[r]:this.noiseShape[r]);return n}call(e,t){return K(()=>{this.invokeCallHook(e,t);let n=He(e);if(0<this.rate&&this.rate<1){let r=t.training==null?!1:t.training,s=this.getNoiseShape(n);return Rp(()=>Y7(n,this.rate,s,this.seed),()=>n,r)}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()}};g0.className="Dropout";ce.registerClass(g0);var lx=class extends g0{constructor(e){super(e),this.inputSpec=[{ndim:3}]}getNoiseShape(e){let t=e.shape;return[t[0],1,t[2]]}};lx.className="SpatialDropout1D";ce.registerClass(lx);var ux=class extends at{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,mn(this.units,"units"),this.activation=Ha(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=Rt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=Rt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=un(e.kernelConstraint),this.biasConstraint=un(e.biasConstraint),this.kernelRegularizer=_t(e.kernelRegularizer),this.biasRegularizer=_t(e.biasRegularizer),this.activityRegularizer=_t(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=mt(e);let t=e[e.length-1];this.kernel==null&&(this.kernel=this.addWeight("kernel",[t,this.units],null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.units],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint))),this.inputSpec=[{minNDim:2,axes:{[-1]:t}}],this.built=!0}computeOutputShape(e){e=mt(e);let t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return K(()=>{this.invokeCallHook(e,t);let n=He(e),r=G7(this.activation.getClassName()),s;return r!=null?s=Rs(n,this.kernel.read(),r,this.bias?this.bias.read():null):(s=Rs(n,this.kernel.read()),this.bias!=null&&(s=bs(s,this.bias.read())),this.activation!=null&&(s=this.activation.apply(s))),s})}getConfig(){let e={units:this.units,activation:Ga(this.activation),useBias:this.useBias,kernelInitializer:Ot(this.kernelInitializer),biasInitializer:Ot(this.biasInitializer),kernelRegularizer:bt(this.kernelRegularizer),biasRegularizer:bt(this.biasRegularizer),activityRegularizer:bt(this.activityRegularizer),kernelConstraint:ln(this.kernelConstraint),biasConstraint:ln(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}};ux.className="Dense";ce.registerClass(ux);var cx=class extends at{constructor(e){e=e||{},super(e),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=mt(e);for(let t of e.slice(1))if(t==null)throw new j(`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],$a(e,1)]}call(e,t){return K(()=>{this.invokeCallHook(e,t);let n=He(e);if(this.dataFormat==="channelsFirst"&&n.rank>1){let r=[0];for(let s=2;s<n.rank;++s)r.push(s);r.push(1),n=et(n,r)}return VL(n)})}getConfig(){let e={};this.dataFormat!=null&&(e.dataFormat=this.dataFormat);let t=super.getConfig();return Object.assign(e,t),e}};cx.className="Flatten";ce.registerClass(cx);var dx=class extends at{constructor(e){super(e),this.supportsMasking=!0,this.activation=Ha(e.activation)}call(e,t){return K(()=>{this.invokeCallHook(e,t);let n=He(e);return this.activation.apply(n)})}getConfig(){let e={activation:Ga(this.activation)},t=super.getConfig();return Object.assign(e,t),e}};dx.className="Activation";ce.registerClass(dx);var px=class extends at{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=He(e),BL(e,this.n)))}getConfig(){let e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}};px.className="RepeatVector";ce.registerClass(px);var hx=class extends at{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 n="Total size of new array must be unchanged.",r=t.slice(),s=1,a=null;for(let i=0;i<r.length;++i){let l=r[i];if(this.isUnknown(l))if(a===null)a=i;else throw new j("Can only specifiy one unknown dimension.");else s*=l}let o=$a(e);if(a!==null){if(s===0||o%s!==0)throw new j(n);r[a]=o/s}else if(o!==s)throw new j(n);return r}computeOutputShape(e){let t=!1;for(let n=0;n<e.length;++n)if(this.isUnknown(e[n])){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 n=He(e),r=n.shape,s=r.slice(0,1).concat(this.fixUnknownDimension(r.slice(1),this.targetShape));return H(n,s)})}getConfig(){let e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}};hx.className="Reshape";ce.registerClass(hx);var fx=class extends at{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=gs(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 Zt({ndim:this.dims.length+1})]}computeOutputShape(e){e=mt(e);let t=e.slice();return this.dims.forEach((n,r)=>{t[r+1]=e[n]}),t}call(e,t){return et(He(e),this.dimsIncludingBatch)}getConfig(){let e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}};fx.className="Permute";ce.registerClass(fx);var mx=class extends at{constructor(e){super(e==null?{}:e),this.supportsMasking=!0,e!=null?this.maskValue=e.maskValue==null?0:e.maskValue:this.maskValue=0}computeOutputShape(e){return e}getConfig(){let e=super.getConfig(),t={maskValue:this.maskValue};return Object.assign(t,e),t}computeMask(e,t){let n=He(e),r=-1;return If(Tu(n,this.maskValue),r)}call(e,t){return K(()=>{this.invokeCallHook(e,t);let n=He(e),r=-1,s=!0,a=If(Tu(n,this.maskValue),r,s);return L(n,ge(a,n.dtype))})}};mx.className="Masking";ce.registerClass(mx);var gx=class extends at{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,mn(this.inputDim,"inputDim"),this.outputDim=e.outputDim,mn(this.outputDim,"outputDim"),this.embeddingsInitializer=Rt(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=_t(e.embeddingsRegularizer),this.activityRegularizer=_t(e.activityRegularizer),this.embeddingsConstraint=un(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=He(e),Tu(e,st(e))):null)}computeOutputShape(e){if(e=mt(e),this.inputLength==null)return[...e,this.outputDim];let t=It(this.inputLength);if(t.length!==e.length-1)throw new j(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let n=0;for(let r=0;r<t.length;++r){let s=t[r],a=e[r+1];if(s!=null&&a!=null&&s!==a)throw new j(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);s==null&&(t[n]=a),n++}}return[e[0],...t,this.outputDim]}call(e,t){return K(()=>{this.invokeCallHook(e,t);let n=He(e);n.dtype!=="int32"&&(n=Ym(n,"int32"));let r=Z7(this.embeddings.read(),H(n,[n.size]));return H(r,mt(this.computeOutputShape(n.shape)))})}getConfig(){let e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:Ot(this.embeddingsInitializer),embeddingsRegularizer:bt(this.embeddingsRegularizer),activityRegularizer:bt(this.activityRegularizer),embeddingsConstraint:ln(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}};gx.className="Embedding";ce.registerClass(gx);var Ol=class extends at{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 n=e.slice(0,e.length-t.length);for(let r=0;r<t.length;++r){let s=e[e.length-t.length+r],a=t[r];if(s==null||a==null||s<0||a<0)n.push(null);else if(s===1)n.push(a);else if(a===1)n.push(s);else{if(s!==a)throw new j("Operands could not be broadcast together with shapes "+JSON.stringify(e)+" "+JSON.stringify(t));n.push(s)}}return n}build(e){if(Array.isArray(e)&&!Array.isArray(e[0])&&(e=[mt(e)]),e=e,e.length<2)throw new j(`A merge layer should be called on an Array of at least 2 inputs. Got ${e.length} input(s).`);let t=[];for(let s of e)s!=null&&s[0]!==null&&t.push(s[0]);if(t=_a(t),t.length>1)throw new j(`Can not merge tensors with different batch sizes. Got tensors with shapes: ${JSON.stringify(e)}.`);let n=e[0]==null?null:e[0].slice(1);for(let s=1;s<e.length;++s){let a=e[s]==null?null:e[s].slice(1);n=this.computeElementwiseOpOutputShape(n,a)}let r=e.map(s=>s.length);e.indexOf(null)===-1&&_a(r).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return K(()=>{if(e=e,this.reshapeRequired){let n=[],r=e.map(s=>s.rank);if(r.indexOf(null)===-1){let s=Ua(r);for(let a of e){let o=a.rank;for(let i=0;i<s-o;++i)a=Np(a,1);n.push(a)}return this.mergeFunction(n)}else{let s=!1;for(let i of e){let l=i.rank;if(l==null){let u=i.shape,c=u[0],p=u.slice(1).concat([c]),d=H(i,[c].concat($a(u.slice(1))));d=et(d,[1,0]),d=H(d,p),n.push(d),s=!0}else if(l>1){let u=gs(1,l).concat([0]);n.push(et(i,u)),s=!0}else n.push(i)}let a=this.mergeFunction(n),o=a.rank;if(s){if(o==null){let i=a.shape,l=i.length,u=i[l-1],c=[u].concat(i.slice(0,i.length-1));a=H(et(H(a,[-1,u]),[1,0]),c)}else if(o>1){let i=[o-1].concat(gs(0,o-1));a=et(a,i)}}return a}}else return this.mergeFunction(e)})}computeOutputShape(e){e=e;let t;e[0]==null?t=null:t=e[0].slice(1);for(let r=1;r<e.length;++r){let s=e[r]==null?null:e[r].slice(1);t=this.computeElementwiseOpOutputShape(t,s)}let n=[];for(let r of e)r!=null&&r[0]!==null&&n.push(r[0]);return n=_a(n),n.length===1?t=n.concat(t):t=[null].concat(t),t}computeMask(e,t){return K(()=>{if(t==null)return null;if(!Array.isArray(t))throw new j("`mask` should be an Array");if(!Array.isArray(e))throw new j("`inputs` should be an Array");if(t.length!==e.length)throw new j(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every(r=>r==null))return null;t=t.map(r=>r==null?r:Kt(r,0));let n=t[0];for(let r=1;r<t.length-1;++r)n=ms(n,t[r]);return n})}},yx=class extends Ol{constructor(e){super(e)}mergeFunction(e){return K(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=ue(t,e[n]);return t})}};yx.className="Add";ce.registerClass(yx);var Ax=class extends Ol{constructor(e){super(e)}mergeFunction(e){return K(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=L(t,e[n]);return t})}};Ax.className="Multiply";ce.registerClass(Ax);var xx=class extends Ol{constructor(e){super(e)}mergeFunction(e){return K(()=>{let t=e[0].clone();for(let n=1;n<e.length;++n)t=ue(t,e[n]);return L(1/e.length,t)})}};xx.className="Average";ce.registerClass(xx);var bx=class extends Ol{constructor(e){super(e)}mergeFunction(e){return K(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=ra(t,e[n]);return t})}};bx.className="Maximum";ce.registerClass(bx);var vx=class extends Ol{constructor(e){super(e)}mergeFunction(e){return K(()=>{let t=e[0];for(let n=1;n<e.length;++n)t=Sp(t,e[n]);return t})}};vx.className="Minimum";ce.registerClass(vx);var wx=class extends Ol{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 j("A `Concatenate` layer should be called on a list of at least 2 inputs");e=e;let t=!0;for(let r of e)if(r!=null){t=!1;break}if(t)return;let n=[];for(let r=0;r<e.length;++r){let s=e[r].slice();s.splice(this.axis,1);let a=!1;for(let o of n)if(w.arraysEqual(o,s)){a=!0;break}a||n.push(s)}if(n.length>1)throw new j("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return K(()=>bA(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new j("A `Concatenate` layer should be called on a list of inputs.");let t=e,n=t[0].slice(),r=this.axis<0?n.length+this.axis:this.axis;for(let s of t.slice(1)){if(n[r]==null||s[r]==null){n[r]=null;break}n[r]+=s[r]}return n}computeMask(e,t){if(t==null)return null;if(!Array.isArray(t))throw new j("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new j("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new j(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return K(()=>{let n=!0;if(t.forEach(a=>{if(a!=null){n=!1;return}}),n)return null;let r=[];for(let a=0;a<e.length;++a)t[a]==null?r.push(ge(Pr(e[a]),"bool")):t[a].rank<e[a].rank?r.push(Kt(t[a],-1)):r.push(t[a]);let s=St(r,this.axis);return Fy(s,-1,!1)})}getConfig(){let e={axis:this.axis},t=super.getConfig();return Object.assign(e,t),e}};wx.className="Concatenate";ce.registerClass(wx);function Ad(e,t){for(;e<0;)e+=t;return e}function $U(e,t,n){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 n=="number"&&(n=[n,n]),e.dtype==="complex64"||t.dtype==="complex64")throw new Ve("batchDot is not implemented for complex64-type Tensors yet.");let r=e.shape.length,s=t.shape.length;n==null&&(n=[r-1,s-2]);let a=n;return K(()=>{let o;if(r>s){o=r-s;let l=[];for(let u=0;u<o;++u)l.push(1);t=H(t,t.shape.concat(l))}else if(s>r){o=s-r;let l=[];for(let u=0;u<o;++u)l.push(1);e=H(e,e.shape.concat(l))}else o=0;let i;if(e.shape.length===2&&t.shape.length===2)a[0]===a[1]?i=ke(L(e,t),a[0]):i=ke(L(et(e,[1,0]),t),a[1]);else{let l=a[0]!==e.shape.length-1,u=a[1]===t.shape.length-1;i=Ye(e,t,l,u)}if(o>0){let l;r>s?l=r+s-3:l=r-1;let u=[];for(let c=l;c<l+o;++c)u.push(c);i=tt(i,u)}return i.shape.length===1&&(i=Kt(i,1)),i})}var kx=class extends Ol{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],n=e[1];if(t.length>3||n.length>3)throw new Ve("Dot layer does not support tensors of 4D or higher rank yet.");let r=this.interpretAxes(t,n);if(t[r[0]]!==n[r[1]])throw new j(`Dimension incompatibility: ${t[r[0]]} !== ${n[r[1]]}`)}mergeFunction(e){if(e.length!==2)throw new j(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t=e[0],n=e[1],r;return Array.isArray(this.axes)?r=this.axes.map((s,a)=>Ad(s,e[a].shape.length)):r=[Ad(this.axes,t.shape.length),Ad(this.axes,n.shape.length)],this.normalize&&(t=$f(t,r[0]),n=$f(n,r[1])),$U(t,n,r)}interpretAxes(e,t){let n;return Array.isArray(this.axes)?n=this.axes:n=[Ad(this.axes,e.length),Ad(this.axes,t.length)],n}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(),n=e[1].slice();if(t.length>3||n.length>3)throw new Ve("Dot layer does not support tensors of 4D or higher rank yet.");let r=this.interpretAxes(t,n);t.splice(r[0],1),n.splice(r[1],1),n.splice(0,1);let s=t.concat(n);return s.length===1&&s.push(1),s}computeMask(e,t){return null}getConfig(){let e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}};kx.className="Dot";ce.registerClass(kx);var Sx=class extends at{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 n=He(e);return Rp(()=>ue(Jm(n.shape,0,this.stddev),n),()=>n,t.training||!1)})}};Sx.className="GaussianNoise";ce.registerClass(Sx);var Ix=class extends at{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 n=He(e);return this.rate>0&&this.rate<1?Rp(()=>{let s=Math.sqrt(this.rate/(1-this.rate));return L(n,Jm(n.shape,1,s))},()=>n,t.training||!1):n})}};Ix.className="GaussianDropout";ce.registerClass(Ix);var Cx=class extends at{constructor(e){super(e),this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||He(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 n=this._getNoiseShape(e);return Rp(()=>{let s=He(e),a=1.6732632423543772,o=1.0507009873554805,i=-a*o,l=_l(gc(n),this.rate);l=Ym(l,"float32");let u=((1-this.rate)*(1+this.rate*i**2))**-.5,c=-u*i*this.rate,p=ue(L(s,l),L(ue(l,-1),i));return ue(L(p,u),c)},()=>He(e),t.training||!1)}return e})}};Cx.className="AlphaDropout";ce.registerClass(Cx);function qd(e,t,n,r,s,a=.001){let o;if(e.rank===2)o=Lw(e,t,n,r,s,a);else if(e.rank===3)o=Bw(e,t,n,r,s,a);else if(e.rank===4)o=Ww(e,t,n,r,s,a);else throw new Ve(`batchNormalization is not implemented for array of rank ${e.rank} yet`);return o}function DU(e,t,n,r,s=.001){return K(()=>{let a=Dm(e,r),o=a.mean,i=a.variance;return[qd(e,o,i,n,t,s),o,i]})}function PU(e,t,n,r,s=.001){return K(()=>{let a=Dm(e,r),o=a.mean,i=a.variance,l=[];for(let f of gs(0,e.rank))r.indexOf(f)!==-1?l.push(1):l.push(e.shape[f]);let u=H(o,l),c=H(i,l),p=t==null?null:H(t,l),d=n==null?null:H(n,l);return[qd(e,u,c,d,p,s),o,i]})}function FU(e,t,n,r,s=.001){return w.arraysEqual(r.slice().sort(),gs(0,e.rank-1))?DU(e,t,n,r,s):PU(e,t,n,r,s)}var Tx=class extends at{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=Rt(e.betaInitializer||"zeros"),this.gammaInitializer=Rt(e.gammaInitializer||"ones"),this.movingMeanInitializer=Rt(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=Rt(e.movingVarianceInitializer||"ones"),this.betaConstraint=un(e.betaConstraint),this.gammaConstraint=un(e.gammaConstraint),this.betaRegularizer=_t(e.betaRegularizer),this.gammaRegularizer=_t(e.gammaRegularizer)}build(e){e=mt(e);let t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(n==null)throw new j(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new Zt({ndim:e.length,axes:{[t]:n}})];let r=[n];this.scale&&(this.gamma=this.addWeight("gamma",r,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",r,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",r,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",r,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return K(()=>{let n=t.training==null?!1:t.training,r=He(e),s=r.shape,a=s.length,o=gs(0,a),i=this.axis>=0?this.axis:this.axis+a;o.splice(i,1);let l=Oi(1,a);l[i]=s[i];let u=o.slice();u.sort();let c=!w.arraysEqual(u,gs(0,a).slice(0,a-1)),p=()=>{if(c){let y=H(this.movingMean.read(),l),x=H(this.movingVariance.read(),l),A=this.center?H(this.beta.read(),l):null,b=this.scale?H(this.gamma.read(),l):null;return qd(r,y,x,A,b,this.epsilon)}else return qd(r,this.movingMean.read(),this.movingVariance.read(),this.beta==null?null:this.beta.read(),this.gamma==null?null:this.gamma.read(),this.epsilon)};if(!n)return p();let[d,h,f]=FU(r,this.gamma.read(),this.beta.read(),o,this.epsilon),m=(y,x,A)=>{K(()=>{let b=1-A,v=y.read(),S=L(he(v,x),b);y.write(he(v,S))})};return(()=>{m(this.movingMean,h,this.momentum),m(this.movingVariance,f,this.momentum)})(),d})}getConfig(){let e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Ot(this.betaInitializer),gammaInitializer:Ot(this.gammaInitializer),movingMeanInitializer:Ot(this.movingMeanInitializer),movingVarianceInitializer:Ot(this.movingVarianceInitializer),betaRegularizer:bt(this.betaRegularizer),gammaRegularizer:bt(this.gammaRegularizer),betaConstraint:ln(this.betaConstraint),gammaConstraint:ln(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}};Tx.className="BatchNormalization";ce.registerClass(Tx);var Nx=class extends at{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=Rt(e.betaInitializer||"zeros"),this.gammaInitializer=Rt(e.gammaInitializer||"ones"),this.betaRegularizer=_t(e.betaRegularizer),this.gammaRegularizer=_t(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=mt(e);let t=e.length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let s=0;s<this.axis.length;++s)this.axis[s]<0&&(this.axis[s]+=t);for(let s of this.axis)if(s<0||s>=t)throw new Error(`Invalid axis: ${s}`);if(this.axis.length!==_a(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);let n=this.axis.map(s=>e[s]),r=!0;this.scale?this.gamma=this.addWeight("gamma",n,"float32",this.gammaInitializer,this.gammaRegularizer,r):this.gamma=null,this.center?this.beta=this.addWeight("beta",n,"float32",this.betaInitializer,this.betaRegularizer,r):this.beta=null,this.built=!0}call(e,t){let n=He(e),r=n.shape,s=r.length;return K(()=>{let{mean:o,variance:i}=Dm(n,this.axis,!0),l=Oi(1,s);for(let f of this.axis)l[f]=r[f];let u=f=>f!=null&&f.shape.length!==s?H(f,l):f,c=u(this.gamma.read()),p=u(this.beta.read()),d=[],h=[];for(let f=0;f<s;++f)this.axis.indexOf(f)!==-1?(d.push(r[f]),h.push(1)):(d.push(1),h.push(r[f]));return o=Gr(o,d),i=Gr(i,d),c=Gr(c,h),p=Gr(p,h),qd(n,o,i,p,c,this.epsilon)})}getConfig(){let e={axis:this.axis,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:Ot(this.betaInitializer),gammaInitializer:Ot(this.gammaInitializer),betaRegularizer:bt(this.betaRegularizer),gammaRegularizer:bt(this.gammaRegularizer)},t=super.getConfig();return Object.assign(e,t),e}};Nx.className="LayerNormalization";ce.registerClass(Nx);function OU(e,t,n){return K(()=>{if(e.rank!==4)throw new j(`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 j("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(n==null&&(n=ys()),n!=="channelsLast"&&n!=="channelsFirst")throw new j(`Unknown data format: ${n}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let r;return n==="channelsFirst"?r=[[0,0],[0,0],t[0],t[1]]:r=[[0,0],t[0],t[1],[0,0]],Xr(e,r)})}var Ex=class extends at{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?ys():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 j(`ZeroPadding2D expects padding to be a length-2 array, but received a length-${e.padding.length} array.`);let t,n;if(typeof e.padding[0]=="number")t=[e.padding[0],e.padding[0]],n=[e.padding[1],e.padding[1]];else{if(e.padding=e.padding,e.padding[0].length!==2)throw new j(`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 j(`ZeroPadding2D expects width padding to be a length-2 array, but received a length-${e.padding[1].length} array.`);n=e.padding[1]}this.padding=[t,n]}this.inputSpec=[new Zt({ndim:4})]}computeOutputShape(e){e=mt(e);let t,n;return this.dataFormat==="channelsFirst"?(e[2]!=null&&e[2]>=0?t=e[2]+this.padding[0][0]+this.padding[0][1]:t=null,e[3]!=null&&e[3]>=0?n=e[3]+this.padding[1][0]+this.padding[1][1]:n=null,[e[0],e[1],t,n]):(e[1]!=null&&e[1]>=0?t=e[1]+this.padding[0][0]+this.padding[0][1]:t=null,e[2]!=null&&e[2]>=0?n=e[2]+this.padding[1][0]+this.padding[1][1]:n=null,[e[0],t,n,e[3]])}call(e,t){return K(()=>OU(He(e),this.padding,this.dataFormat))}getConfig(){let e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};Ex.className="ZeroPadding2D";ce.registerClass(Ex);function y0(e,t,n,r,s,a){return K(()=>{Ht(s),j7(a),Lr(r),n==null&&(n=[1,1]),r==null&&(r="valid"),s==null&&(s=ys()),a==null&&(a="max"),e=KA(e,s);let o,i=r==="same"?"same":"valid";return a==="max"?o=$m(e,t,n,i):o=Sm(e,t,n,i),s==="channelsFirst"&&(o=et(o,[0,3,1,2])),o})}function q6(e,t,n,r,s,a){return K(()=>{Ht(s),j7(a),Lr(r),n==null&&(n=[1,1,1]),r==null&&(r="valid"),s==null&&(s=ys()),a==null&&(a="max"),e=z6(e,s);let o,i=r==="same"?"same":"valid";return a==="max"?o=Yy(e,t,n,i):o=My(e,t,n,i),s==="channelsFirst"&&(o=et(o,[0,4,1,2,3])),o})}var X6=class extends at{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 j(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(mn(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 j(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);mn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,Lr(this.padding),this.inputSpec=[new Zt({ndim:3})]}computeOutputShape(e){e=mt(e);let t=fs(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=Np(He(e),2);let n=this.poolingFunction(He(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return tt(n,[2])})}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}},Rx=class extends X6{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return Ht(s),Lr(r),y0(e,t,n,r,s,"max")}};Rx.className="MaxPooling1D";ce.registerClass(Rx);var _x=class extends X6{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return Ht(s),Lr(r),y0(e,t,n,r,s,"avg")}};_x.className="AveragePooling1D";ce.registerClass(_x);var K6=class extends at{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 j(`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];mn(this.poolSize,"poolSize"),mn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Ht(this.dataFormat),Lr(this.padding),this.inputSpec=[new Zt({ndim:4})]}computeOutputShape(e){e=mt(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=fs(t,this.poolSize[0],this.padding,this.strides[0]),n=fs(n,this.poolSize[1],this.padding,this.strides[1]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,n]:[e[0],t,n,e[3]]}call(e,t){return K(()=>(this.invokeCallHook(e,t),this.poolingFunction(He(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}},$x=class extends K6{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return Ht(s),Lr(r),y0(e,t,n,r,s,"max")}};$x.className="MaxPooling2D";ce.registerClass($x);var Dx=class extends K6{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return Ht(s),Lr(r),y0(e,t,n,r,s,"avg")}};Dx.className="AveragePooling2D";ce.registerClass(Dx);var Z6=class extends at{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 j(`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];mn(this.poolSize,"poolSize"),mn(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Ht(this.dataFormat),Lr(this.padding),this.inputSpec=[new Zt({ndim:5})]}computeOutputShape(e){e=mt(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],r=this.dataFormat==="channelsFirst"?e[4]:e[3];return t=fs(t,this.poolSize[0],this.padding,this.strides[0]),n=fs(n,this.poolSize[1],this.padding,this.strides[1]),r=fs(r,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,n,r]:[e[0],t,n,r,e[4]]}call(e,t){return K(()=>(this.invokeCallHook(e,t),this.poolingFunction(He(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}},Px=class extends Z6{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return Ht(s),Lr(r),q6(e,t,n,r,s,"max")}};Px.className="MaxPooling3D";ce.registerClass(Px);var Fx=class extends Z6{constructor(e){super(e)}poolingFunction(e,t,n,r,s){return Ht(s),Lr(r),q6(e,t,n,r,s,"avg")}};Fx.className="AveragePooling3D";ce.registerClass(Fx);var Y6=class extends at{constructor(e){super(e),this.inputSpec=[new Zt({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new Ve}},Ox=class extends Y6{constructor(e){super(e||{})}call(e,t){return K(()=>{let n=He(e);return Vt(n,1)})}};Ox.className="GlobalAveragePooling1D";ce.registerClass(Ox);var Mx=class extends Y6{constructor(e){super(e||{})}call(e,t){return K(()=>{let n=He(e);return gn(n,1)})}};Mx.className="GlobalMaxPooling1D";ce.registerClass(Mx);var J6=class extends at{constructor(e){super(e),this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Ht(this.dataFormat),this.inputSpec=[new Zt({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 J6{call(e,t){return K(()=>{let n=He(e);return this.dataFormat==="channelsLast"?Vt(n,[1,2]):Vt(n,[2,3])})}};zx.className="GlobalAveragePooling2D";ce.registerClass(zx);var Lx=class extends J6{call(e,t){return K(()=>{let n=He(e);return this.dataFormat==="channelsLast"?gn(n,[1,2]):gn(n,[2,3])})}};Lx.className="GlobalMaxPooling2D";ce.registerClass(Lx);var Q6=class extends at{constructor(e){super(e),this.layer=e.layer}build(e){this.built=!0}get trainable(){return this.layer!=null?this.layer.trainable:!1}set trainable(e){this.layer!=null&&(this.layer.trainable=e)}get trainableWeights(){return this.layer.trainableWeights}get nonTrainableWeights(){return this.layer.nonTrainableWeights}get updates(){return this.layer._updates}get losses(){return this.layer.losses}getWeights(){return this.layer.getWeights()}setWeights(e){this.layer.setWeights(e)}getConfig(){let e={layer:{className:this.layer.getClassName(),config:this.layer.getConfig()}},t=super.getConfig();return Object.assign(e,t),e}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.layer!=null&&this.layer.setFastWeightInitDuringBuild(e)}static fromConfig(e,t,n={}){let r=t.layer,s=hs(r,n);delete t.layer;let a={layer:s};return Object.assign(a,t),new e(a)}},Bx=class extends Q6{constructor(e){super(e),this.supportsMasking=!0}build(e){if(e=mt(e),e.length<3)throw new j(`TimeDistributed layer expects an input shape >= 3D, but received input shape ${JSON.stringify(e)}`);this.inputSpec=[{shape:e}];let t=[e[0]].concat(e.slice(2));this.layer.built||(this.layer.build(t),this.layer.built=!0),super.build(e)}computeOutputShape(e){e=mt(e);let t=[e[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),r=e[1];return[n[0],r].concat(n.slice(1))}call(e,t){return K(()=>(e=He(e),G6((a,o)=>[He(this.layer.call(a,t)),[]],e,[],!1,null,null,!1,!0)[1]))}};Bx.className="TimeDistributed";ce.registerClass(Bx);function MU(e){Pl(FL,"BidirectionalMergeMode",e)}var zU="concat",Wx=class extends Q6{constructor(e){super(e);let t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=hs(n),t.goBackwards=t.goBackwards!==!0;let r={};if(r.className=e.layer.getClassName(),r.config=t,this.backwardLayer=hs(r),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?zU:e.mergeMode,MU(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,n=Math.floor(t/2);this.forwardLayer.setWeights(e.slice(0,n)),this.backwardLayer.setWeights(e.slice(n))}computeOutputShape(e){let t=this.forwardLayer.computeOutputShape(e);Array.isArray(t)&&Array.isArray(t[0])||(t=[t]),t=t;let n,r,s;return this.returnState&&(s=t.slice(1)),n=t[0],n=n,this.mergeMode==="concat"?(n[n.length-1]*=2,r=[n]):this.mergeMode==null?r=[n,n.slice()]:r=[n],this.returnState?this.mergeMode==null?r.concat(s).concat(s.slice()):[n].concat(s).concat(s.slice()):tr(r)}apply(e,t){let n=t==null?null:t.initialState,r=t==null?null:t.constants;t==null&&(t={});let s=U6(e,n,r,this.numConstants);if(e=s.inputs,n=s.initialState,r=s.constants,Array.isArray(e)&&(n=e.slice(1),e=e[0]),(n==null||n.length===0)&&r==null)return super.apply(e,t);let a=[],o=[];if(n!=null){let l=n.length;if(l%2>0)throw new j("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=n,a.push(...n);let u=n.map(c=>new Zt({shape:c.shape}));this.forwardLayer.stateSpec=u.slice(0,l/2),this.backwardLayer.stateSpec=u.slice(l/2),o.push(...u)}if(r!=null)throw new Ve("Support for constants in Bidirectional layers is not implemented yet.");let i=a[0]instanceof cs;for(let l of a)if(l instanceof cs!==i)throw new j("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(i){let l=[e].concat(a),u=this.inputSpec.concat(o),c=this.inputSpec;this.inputSpec=u;let p=super.apply(l,t);return this.inputSpec=c,p}else return super.apply(e,t)}call(e,t){return K(()=>{let n=t.initialState,r,s;if(n==null)r=this.forwardLayer.call(e,t),s=this.backwardLayer.call(e,t);else{let i=n.slice(0,n.length/2),l=n.slice(n.length/2);r=this.forwardLayer.call(e,Object.assign(t,{initialState:i})),s=this.backwardLayer.call(e,Object.assign(t,{initialState:l}))}let a;this.returnState&&(Array.isArray(r)&&(a=r.slice(1).concat(s.slice(1))),r=r[0],s=s[0]),this.returnSequences&&(s=Fr(s,1));let o;return this.mergeMode==="concat"?o=bA([r,s]):this.mergeMode==="sum"?o=ue(r,s):this.mergeMode==="ave"?o=L(.5,ue(r,s)):this.mergeMode==="mul"?o=L(r,s):this.mergeMode==null&&(o=[r,s]),this.returnState?this.mergeMode==null?o.concat(a):[o].concat(a):o})}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){Ni(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),Ni(this.backwardLayer.name,()=>{this.backwardLayer.build(e)}),this.built=!0}computeMask(e,t){Array.isArray(t)&&(t=t[0]);let n;if(this.returnSequences?this.mergeMode==null?n=[t,t]:n=t:this.mergeMode==null?n=[null,null]:n=null,this.returnState){let s=this.forwardLayer.states.map(a=>null);return Array.isArray(n)?n.concat(s).concat(s):[n].concat(s).concat(s)}else return n}get trainableWeights(){return this.forwardLayer.trainableWeights.concat(this.backwardLayer.trainableWeights)}get nonTrainableWeights(){return this.forwardLayer.nonTrainableWeights.concat(this.backwardLayer.nonTrainableWeights)}setFastWeightInitDuringBuild(e){super.setFastWeightInitDuringBuild(e),this.forwardLayer!=null&&this.forwardLayer.setFastWeightInitDuringBuild(e),this.backwardLayer!=null&&this.backwardLayer.setFastWeightInitDuringBuild(e)}getConfig(){let e={mergeMode:this.mergeMode},t=super.getConfig();return Object.assign(e,t),e}static fromConfig(e,t){let n=hs(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 r=t;return r.layer=n,new e(r)}};Wx.className="Bidirectional";ce.registerClass(Wx);function LU(e){return new xc(e)}function BU(e){return new jA(e)}function WU(e){return new UA(e)}function VU(e){return new GA(e)}function UU(e){return new HA(e)}function GU(e){return new XA(e)}function HU(e){return new qA(e)}function jU(e){return new ex(e)}function qU(e){return new c0(e)}function XU(e){return new YA(e)}function KU(e){return new d0(e)}function ZU(e){return new JA(e)}function YU(e){return new QA(e)}function JU(e){return new tx(e)}function QU(e){return new nx(e)}function eG(e){return new rx(e)}function tG(e){return new dx(e)}function nG(e){return new ux(e)}function rG(e){return new g0(e)}function sG(e){return new lx(e)}function aG(e){return new cx(e)}function oG(e){return new px(e)}function iG(e){return new hx(e)}function lG(e){return new fx(e)}function uG(e){return new gx(e)}function cG(e){return new yx(e)}function dG(e){return new xx(e)}function pG(e){return new wx(e)}function hG(e){return new bx(e)}function fG(e){return new vx(e)}function mG(e){return new Ax(e)}function gG(e){return new kx(e)}function yG(e){return new Tx(e)}function AG(e){return new Nx(e)}function xG(e){return new Ex(e)}function Vx(e){return new _x(e)}function bG(e){return Vx(e)}function vG(e){return Vx(e)}function Ux(e){return new Dx(e)}function wG(e){return Ux(e)}function kG(e){return Ux(e)}function Gx(e){return new Fx(e)}function SG(e){return Gx(e)}function IG(e){return Gx(e)}function CG(e){return new Ox(e)}function TG(e){return new zx(e)}function ek(e){return new Mx(e)}function tk(e){return new Lx(e)}function nk(e){return new Rx(e)}function rk(e){return new $x(e)}function NG(e){return new Px(e)}function EG(e){return new ax(e)}function RG(e){return new h0(e)}function _G(e){return new ox(e)}function $G(e){return new Fp(e)}function DG(e){return new sx(e)}function PG(e){return new p0(e)}function FG(e){return new ix(e)}function OG(e){return new m0(e)}function MG(e){return new oa(e)}function zG(e){return new f0(e)}function LG(e){return new Wx(e)}function BG(e){return new Bx(e)}var WG=ek,VG=tk,UG=nk,GG=rk;function HG(e){return new Sx(e)}function jG(e){return new Ix(e)}function qG(e){return new Cx(e)}function XG(e){return new mx(e)}var sk={};Le(sk,{MAPE:()=>aH,MSE:()=>lH,binaryAccuracy:()=>KG,binaryCrossentropy:()=>ZG,categoricalAccuracy:()=>JG,categoricalCrossentropy:()=>QG,cosineProximity:()=>nH,mape:()=>oH,meanAbsoluteError:()=>rH,meanAbsolutePercentageError:()=>sH,meanSquaredError:()=>iH,mse:()=>uH,precision:()=>eH,recall:()=>tH,sparseCategoricalAccuracy:()=>YG});function KG(e,t){return OA(e,t)}function ZG(e,t){return f6(e,t)}function YG(e,t){return m6(e,t)}function JG(e,t){return MA(e,t)}function QG(e,t){return zA(e,t)}function eH(e,t){return h6(e,t)}function tH(e,t){return UV(e,t)}function nH(e,t){return FA(e,t)}function rH(e,t){return i0(e,t)}function sH(e,t){return bc(e,t)}function aH(e,t){return bc(e,t)}function oH(e,t){return bc(e,t)}function iH(e,t){return Fl(e,t)}function lH(e,t){return Fl(e,t)}function uH(e,t){return Fl(e,t)}var ak={};Le(ak,{modelFromJSON:()=>xU});var ok={};Le(ok,{l1:()=>dH,l1l2:()=>cH,l2:()=>pH});function cH(e){return new $p(e)}function dH(e){return TU(e)}function pH(e){return NU(e)}var ik=class extends Ru{constructor(){super(...arguments),this.model=null}setModel(e){if(!(e instanceof Ys))throw new Error("model must be a LayersModel, not some other Container");this.model=e}};function Zh(e,t){return e<t}function xv(e,t){return e>t}var lk=class extends ik{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=Zh:this.mode==="max"?this.monitorFunc=xv:this.monitor.indexOf("acc")!==-1?this.monitorFunc=xv:this.monitorFunc=Zh,this.monitorFunc===Zh&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===Zh?1/0:-1/0}async onEpochEnd(e,t){await Ca(t);let n=this.getMonitorValue(t);n!=null&&(this.monitorFunc(n-this.minDelta,this.best)?(this.best=n,this.wait=0):(this.wait++,this.wait>=this.patience&&(this.stoppedEpoch=e,this.model.stopTraining=!0)))}async onTrainEnd(e){this.stoppedEpoch>0&&this.verbose&&console.log(`Epoch ${this.stoppedEpoch}: early stopping.`)}getMonitorValue(e){e==null&&(e={});let t=e[this.monitor];return t==null&&console.warn(`Metric for EarlyStopping ${this.monitor} is not available. Available metrics are: ${Object.keys(e)}`),t}};function hH(e){return new lk(e)}var fH={earlyStopping:hH},mH=Y();mH.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 uk=(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))(uk||{}),bv;(e=>{let t;(n=>{n[n.LEGACY=0]="LEGACY",n[n.V1=1]="V1",n[n.V2=2]="V2"})(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))})(bv||(bv={}));var Hx={};function gH(e,t){let n={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};Hx[e]=n}function ck(e){return Hx[e]}function yH(e){delete Hx[e]}function k(e,t,n,r,s){let a=t.inputParams[e];if(a&&a.inputIndexStart!==void 0){let i=a.inputIndexStart,l=a.inputIndexEnd===0?void 0:a.inputIndexEnd===void 0?i+1:a.inputIndexEnd;if(a.type==="tensor")return Vn(t.inputNames[a.inputIndexStart],n,r,s);if(a.type==="tensors")return t.inputNames.slice(i,l).map(d=>Vn(d,n,r,s));let u=Vn(t.inputNames.slice(i)[0],n,r,s),c=u.dataSync();return a.type==="number"?c[0]:w.toNestedArray(u.shape,c)}let o=t.attrParams[e];return o&&o.value}function Vn(e,t,n,r){let[s,a]=fr(e);if(r!=null){let i=r.getHashTableHandleByName(s);if(i!=null)return i}let o=n.currentContextIds.find(i=>!!t[Mf(s,i)]);return o!==void 0?t[Mf(s,o)][a]:void 0}function AH(e,t,n){return t[Mf(e,n.currentContextId)]}function Es(e,t){let[n,r,s]=fr(e);return[Mf(n,t&&t.currentContextId),r,s]}function Mf(e,t){return t?`${e}-${t}`:e}function fr(e){let t=e.split(":");if(t.length===1)return[e,0,void 0];let n=t[0],r=t.length===3?t[1]:void 0,s=Number(t[t.length-1]);return[n,s,r]}function of(e,t,n){let r=k("pad",e,t,n);if(r==="explicit"){r=k("explicitPaddings",e,t,n);let s=[[0,0],[0,0],[0,0],[0,0]];for(let a=0;a<4;a++)s[a][0]=r[a*2],s[a][1]=r[a*2+1];return s}return r}function Xs(e){return e.kept?e:Gn(e)}var dk={};Le(dk,{json:()=>xH});var xH=[{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}]}],pk={};Le(pk,{json:()=>bH});var bH=[{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}]}],hk={};Le(hk,{json:()=>vH});var vH=[{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"}]}],fk={};Le(fk,{json:()=>wH});var wH=[{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"}]}],mk={};Le(mk,{json:()=>kH});var kH=[{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"}]}],gk={};Le(gk,{json:()=>SH});var SH=[{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}]}],yk={};Le(yk,{json:()=>IH});var IH=[{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"}]}],Ak={};Le(Ak,{json:()=>CH});var CH=[{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"}]}],xk={};Le(xk,{json:()=>TH});var TH=[{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"}]}],bk={};Le(bk,{json:()=>NH});var NH=[{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"}]}],vk={};Le(vk,{json:()=>EH});var EH=[{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}]}],wk={};Le(wk,{json:()=>RH});var RH=[{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"}]}],kk={};Le(kk,{json:()=>_H});var _H=[{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}]}],Sk={};Le(Sk,{json:()=>$H});var $H=[{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"}]}],Ik={};Le(Ik,{json:()=>DH});var DH=[{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}]}],Ck={};Le(Ck,{json:()=>PH});var PH=[{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"}]}],Tk={};Le(Tk,{json:()=>FH});var FH=[{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}]}],Nk={};Le(Nk,{json:()=>OH});var OH=[{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"}]}],Ek={};Le(Ek,{json:()=>MH});var MH=[{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:[]}],vv=class{static get Instance(){return this._instance||(this._instance=new this)}constructor(){let e=[dk,pk,hk,fk,mk,gk,yk,Ak,xk,bk,vk,wk,kk,Sk,Ik,Ck,Tk,Nk,Ek],t=[].concat(...e.map(n=>n.json));this.opMappers=t.reduce((n,r)=>(n[r.tfOpName]=r,n),{})}transformGraph(e,t={}){let n=e.node,r=[],s=[],a=[],o=n.reduce((f,m)=>(f[m.name]=this.mapNode(m),m.op.startsWith("Placeholder")?r.push(f[m.name]):m.op==="Const"?s.push(f[m.name]):(m.input==null||m.input.length===0)&&a.push(f[m.name]),f),{}),i=[],l=[],u={},c={};t!=null&&(u=this.mapSignatureEntries(t.inputs),c=this.mapSignatureEntries(t.outputs));let p=Object.keys(o);p.forEach(f=>{let m=o[f];m.inputNames.forEach((g,y)=>{let[x,,A]=Es(g),b=o[x];if(b.outputs!=null){let v=b.outputs.indexOf(A);if(v!==-1){let S=`${x}:${v}`;m.inputNames[y]=S}}m.inputs.push(b),b.children.push(m)})}),Object.keys(c).length===0?p.forEach(f=>{let m=o[f];m.children.length===0&&l.push(m)}):Object.keys(c).forEach(f=>{let[m]=Es(f),g=o[m];g!=null&&(g.signatureKey=c[f],l.push(g))}),Object.keys(u).length>0?Object.keys(u).forEach(f=>{let[m]=Es(f),g=o[m];g&&(g.signatureKey=u[f],i.push(g))}):i=r;let d={};e.library!=null&&e.library.function!=null&&(d=e.library.function.reduce((f,m)=>(f[m.signature.name]=this.mapFunction(m),f),{}));let h={nodes:o,inputs:i,outputs:l,weights:s,placeholders:r,signature:t,functions:d};return a.length>0&&(h.initNodes=a),h}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,n)=>(t[e[n].name]=n,t),{})}mapNode(e){let t=ck(e.op)||this.opMappers[e.op]||{};e.attr==null&&(e.attr={});let n={name:e.name,op:e.op,category:t.category,inputNames:(e.input||[]).map(r=>r.startsWith("^")?r.slice(1):r),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return t.inputs!=null&&(n.inputParams=t.inputs.reduce((r,s)=>(r[s.name]={type:s.type,inputIndexStart:s.start,inputIndexEnd:s.end},r),{})),t.attrs!=null&&(n.attrParams=t.attrs.reduce((r,s)=>{let a=s.type,o;switch(s.type){case"string":o=Og(e.attr,s.tfName,s.defaultValue),o===void 0&&!!s.tfDeprecatedName&&(o=Og(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"string[]":o=Ug(e.attr,s.tfName,s.defaultValue),o===void 0&&!!s.tfDeprecatedName&&(o=Ug(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"number":o=zg(e.attr,s.tfName,s.defaultValue||0),o===void 0&&!!s.tfDeprecatedName&&(o=zg(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"number[]":o=Vg(e.attr,s.tfName,s.defaultValue),o===void 0&&!!s.tfDeprecatedName&&(o=Vg(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"bool":o=Mg(e.attr,s.tfName,s.defaultValue),o===void 0&&!!s.tfDeprecatedName&&(o=Mg(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"bool[]":o=Hg(e.attr,s.tfName,s.defaultValue),o===void 0&&!!s.tfDeprecatedName&&(o=Hg(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"shape":o=Wg(e.attr,s.tfName,s.defaultValue),o===void 0&&!!s.tfDeprecatedName&&(o=Wg(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"shape[]":o=Gg(e.attr,s.tfName,s.defaultValue),o===void 0&&!!s.tfDeprecatedName&&(o=Gg(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"dtype":o=Lg(e.attr,s.tfName,s.defaultValue),o===void 0&&!!s.tfDeprecatedName&&(o=Lg(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"dtype[]":o=Bg(e.attr,s.tfName,s.defaultValue),o===void 0&&!!s.tfDeprecatedName&&(o=Bg(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"func":o=wv(e.attr,s.tfName,s.defaultValue),o===void 0&&!!s.tfDeprecatedName&&(o=wv(e.attr,s.tfDeprecatedName,s.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${s.type} for op: ${e.op}`)}return r[s.name]={value:o,type:a},r},{})),n}mapFunction(e){let t=e.nodeDef,n=[],r=[],s={};t!=null&&(s=t.reduce((c,p)=>(c[p.name]=this.mapNode(p),p.op==="Const"&&r.push(c[p.name]),c),{}));let a=[],o=[];e.signature.inputArg.forEach(c=>{let[p]=Es(c.name),d={name:p,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:jx(c.type),type:"dtype"}},children:[]};d.signatureKey=c.name,a.push(d),s[p]=d}),Object.keys(s).forEach(c=>{let p=s[c];p.inputNames.forEach((d,h)=>{let[f,,m]=Es(d),g=s[f];if(g.outputs!=null){let y=g.outputs.indexOf(m);if(y!==-1){let x=`${f}:${y}`;p.inputNames[h]=x}}p.inputs.push(g),g.children.push(p)})});let l=e.ret;e.signature.outputArg.forEach(c=>{let[p,d]=Es(l[c.name]),h=s[p];h!=null&&(h.defaultOutput=d,o.push(h))});let u=this.mapArgsToSignature(e);return{nodes:s,inputs:a,outputs:o,weights:r,placeholders:n,signature:u}}mapArgsToSignature(e){return{methodName:e.signature.name,inputs:e.signature.inputArg.reduce((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n),t),{}),outputs:e.signature.outputArg.reduce((t,n)=>(t[n.name]=this.mapArgToTensorInfo(n,e.ret),t),{})}}mapArgToTensorInfo(e,t){let n=e.name;return t!=null&&(n=t[n]),{name:n,dtype:e.type}}};function zH(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 Rk(e,t){let n=Array.isArray(e)?String.fromCharCode.apply(null,e):zH(e);return t?n:n.toLowerCase()}function Og(e,t,n,r=!1){let s=e[t];return s!=null?Rk(s.s,r):n}function Mg(e,t,n){let r=e[t];return r?r.b:n}function zg(e,t,n){let r=e[t]||{},s=r.i!=null?r.i:r.f!=null?r.f:n;return typeof s=="number"?s:parseInt(s,10)}function jx(e){switch(typeof e=="string"&&(e=uk[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 wv(e,t,n){let r=e[t];return r&&r.func?r.func.name:n}function Lg(e,t,n){let r=e[t];return r&&r.type?jx(r.type):n}function Bg(e,t,n){let r=e[t];return r&&r.list&&r.list.type?r.list.type.map(s=>jx(s)):n}function _k(e){if(!e.unknownRank)return e.dim!=null?e.dim.map(t=>typeof t.size=="number"?t.size:parseInt(t.size,10)):[]}function Wg(e,t,n){let r=e[t];return r&&r.shape?_k(r.shape):n}function Vg(e,t,n){let r=e[t];return r?((r.list.f&&r.list.f.length?r.list.f:r.list.i)||[]).map(s=>typeof s=="number"?s:parseInt(s,10)):n}function Ug(e,t,n,r=!1){let s=e[t];return s&&s.list&&s.list.s?s.list.s.map(a=>Rk(a,r)):n}function Gg(e,t,n){let r=e[t];return r&&r.list&&r.list.shape?r.list.shape.map(s=>_k(s)):n}function Hg(e,t,n){let r=e[t];return r&&r.list&&r.list.b?r.list.b:n}var LH=class{constructor(e,t,n){this.node=e,this.tensorMap=t,this.context=n,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(r=>this.getInput(r)),e.rawAttrs!=null&&(this.attrs=Object.keys(e.rawAttrs).reduce((r,s)=>(r[s]=this.getAttr(s),r),{}))}getInput(e){return Vn(e,this.tensorMap,this.context)}getAttr(e,t){let n=this.node.rawAttrs[e];if(n.tensor!=null)return Vn(e,this.tensorMap,this.context);if(n.i!=null||n.f!=null)return zg(this.node.rawAttrs,e,t);if(n.s!=null)return Og(this.node.rawAttrs,e,t);if(n.b!=null)return Mg(this.node.rawAttrs,e,t);if(n.shape!=null)return Wg(this.node.rawAttrs,e,t);if(n.type!=null)return Lg(this.node.rawAttrs,e,t);if(n.list!=null){if(n.list.i!=null||n.list.f!=null)return Vg(this.node.rawAttrs,e,t);if(n.list.s!=null)return Ug(this.node.rawAttrs,e,t);if(n.list.shape!=null)return Gg(this.node.rawAttrs,e,t);if(n.list.b!=null)return Hg(this.node.rawAttrs,e,t);if(n.list.type!=null)return Bg(this.node.rawAttrs,e,t)}return t}},BH=(e,t,n)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[ue(k("a",e,t,n),k("b",e,t,n))];case"AddN":return[km(k("tensors",e,t,n))];case"FloorMod":case"Mod":return[mc(k("a",e,t,n),k("b",e,t,n))];case"Mul":return[L(k("a",e,t,n),k("b",e,t,n))];case"RealDiv":case"Div":return[de(k("a",e,t,n),k("b",e,t,n))];case"DivNoNan":return[Jw(k("a",e,t,n),k("b",e,t,n))];case"FloorDiv":return[xp(k("a",e,t,n),k("b",e,t,n))];case"Sub":return[he(k("a",e,t,n),k("b",e,t,n))];case"Minimum":return[Sp(k("a",e,t,n),k("b",e,t,n))];case"Maximum":return[ra(k("a",e,t,n),k("b",e,t,n))];case"Pow":return[Wa(k("a",e,t,n),k("b",e,t,n))];case"SquaredDifference":return[uA(k("a",e,t,n),k("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},WH=(e,t,n)=>{switch(e.op){case"Abs":case"ComplexAbs":return[rn(k("x",e,t,n))];case"Acos":return[Nw(k("x",e,t,n))];case"Acosh":return[Ew(k("x",e,t,n))];case"Asin":return[_w(k("x",e,t,n))];case"Asinh":return[$w(k("x",e,t,n))];case"Atan":return[Dw(k("x",e,t,n))];case"Atan2":return[Pw(k("x",e,t,n),k("y",e,t,n))];case"Atanh":return[Fw(k("x",e,t,n))];case"Ceil":return[Uw(k("x",e,t,n))];case"Complex":return[Ma(k("real",e,t,n),k("imag",e,t,n))];case"Cos":return[Cm(k("x",e,t,n))];case"Cosh":return[Uy(k("x",e,t,n))];case"Elu":return[wp(k("x",e,t,n))];case"Erf":return[e7(k("x",e,t,n))];case"Exp":return[$r(k("x",e,t,n))];case"Expm1":return[t7(k("x",e,t,n))];case"Floor":return[kp(k("x",e,t,n))];case"Log":return[Dr(k("x",e,t,n))];case"Log1p":return[Em(k("x",e,t,n))];case"Imag":return[Tm(k("x",e,t,n))];case"Neg":return[zt(k("x",e,t,n))];case"Reciprocal":return[f7(k("x",e,t,n))];case"Real":return[Ud(k("x",e,t,n))];case"Relu":return[Os(k("x",e,t,n))];case"Round":return[nA(k("x",e,t,n))];case"Selu":return[sA(k("x",e,t,n))];case"Sigmoid":return[Tn(k("x",e,t,n))];case"Sin":return[aA(k("x",e,t,n))];case"Sign":return[y7(k("x",e,t,n))];case"Sinh":return[oA(k("x",e,t,n))];case"Softplus":return[fc(k("x",e,t,n))];case"Sqrt":return[En(k("x",e,t,n))];case"Square":return[xt(k("x",e,t,n))];case"Tanh":return[Su(k("x",e,t,n))];case"Tan":return[x7(k("x",e,t,n))];case"ClipByValue":return[yr(k("x",e,t,n),k("clipValueMin",e,t,n),k("clipValueMax",e,t,n))];case"Relu6":return[tA(k("x",e,t,n))];case"Rsqrt":return[rA(Vn(e.inputNames[0],t,n))];case"Prod":return[Jy(k("x",e,t,n),k("axes",e,t,n))];case"LeakyRelu":return[Nm(k("x",e,t,n),k("alpha",e,t,n))];case"Prelu":return[Fm(k("x",e,t,n),k("alpha",e,t,n))];case"IsNan":return[n7(Vn(e.inputNames[0],t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function Ur(e,t,n=""){if(!(typeof e=="number"||typeof t=="number")){w.assert(e.length===t.length,()=>n+` Shapes ${e} and ${t} must match`);for(let r=0;r<e.length;r++){let s=e[r],a=t[r];w.assert(s<0||a<0||s===a,()=>n+` Shapes ${e} and ${t} must match`)}}}function kv(e){return!(typeof e=="number"||e.some(t=>t<0))}function xd(e,t,n){let r=jg(e,n),s=!kv(r);if(s&&t.length===0)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${r}`);if(s&&t.forEach(a=>{r=jg(a.shape,r)}),!kv(r))throw new Error(`Non-fully-defined elementShape: ${r}`);return r}function jg(e,t){if(typeof e=="number")return t;if(typeof t=="number")return e;if(e.length!==t.length)throw new Error(`Incompatible ranks during merge: ${e} vs. ${t}`);let n=[];for(let r=0;r<e.length;++r){let s=e[r],a=t[r];if(s>=0&&a>=0&&s!==a)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);n[r]=s>=0?s:a}return n}var VH=class{constructor(e,t,n,r,s,a,o){this.name=e,this.dtype=t,this.maxSize=n,this.elementShape=r,this.identicalElementShapes=s,this.dynamicSize=a,this.clearAfterRead=o,this.tensors=[],this.closed_=!1,this.idTensor=Ie(0),fn(this.idTensor)}get id(){return this.idTensor.id}get closed(){return this.closed_}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.tensor.id))&&t.tensor.dispose()}),this.tensors=[],this.closed_=!0,this.idTensor.dispose()}size(){return this.tensors.length}read(e){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||e>=this.size())throw new Error(`Tried to read from index ${e}, but array size is: ${this.size()}`);let t=this.tensors[e];if(t.cleared)throw new Error(`TensorArray ${this.name}: Could not read index ${e} twice because it was cleared after a previous read (perhaps try setting clear_after_read = false?).`);return this.clearAfterRead&&(t.cleared=!0),t.read=!0,t.tensor}readMany(e){return e.map(t=>this.read(t))}write(e,t){if(this.closed_)throw new Error(`TensorArray ${this.name} has already been closed.`);if(e<0||!this.dynamicSize&&e>=this.maxSize)throw new Error(`Tried to write to index ${e}, but array is not resizeable and size is: ${this.maxSize}`);let n=this.tensors[e]||{};if(t.dtype!==this.dtype)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e},
|
|
because the value dtype is ${t.dtype}, but TensorArray dtype is ${this.dtype}.`);if(this.size()===0&&(this.elementShape==null||this.elementShape.length===0)&&(this.elementShape=t.shape),Ur(this.elementShape,t.shape,`TensorArray ${this.name}: Could not write to TensorArray index ${e}.`),n.read)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been read.`);if(n.written)throw new Error(`TensorArray ${this.name}: Could not write to TensorArray index ${e}, because it has already been written.`);n.tensor=t,fn(t),n.written=!0,this.tensors[e]=n}writeMany(e,t){if(e.length!==t.length)throw new Error(`TensorArray ${this.name}: could not write multiple tensors,because the index size: ${e.length} is not the same as tensors size: ${t.length}.`);e.forEach((n,r)=>this.write(n,t[r]))}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 r=0;r<this.size();r++)e.push(r)}if(e.length===0)return pt([],[0].concat(this.elementShape));let n=this.readMany(e);return Ur(this.elementShape,n[0].shape,"TensorArray shape mismatch: "),cn(n,0)}concat(e){if(!!e&&e!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but concat requested dtype ${e}`);if(this.size()===0)return pt([],[0].concat(this.elementShape));let t=[];for(let r=0;r<this.size();r++)t.push(r);let n=this.readMany(t);return Ur(this.elementShape,n[0].shape,`TensorArray shape mismatch: tensor array shape (${this.elementShape}) vs first tensor shape (${n[0].shape})`),St(n,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 n=Math.max(...e);if(!this.dynamicSize&&n>=this.maxSize)throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);this.writeMany(e,rr(t,0))}split(e,t){if(t.dtype!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but tensor has dtype ${t.dtype}`);let n=0,r=e.map(i=>(n+=i,n));if(n!==t.shape[0])throw new Error(`Expected sum of lengths to be equal to
|
|
tensor.shape[0], but sum of lengths is
|
|
${n}, and tensor's shape is: ${t.shape}`);if(!this.dynamicSize&&e.length!==this.maxSize)throw new Error(`TensorArray's size is not equal to the size of lengths (${this.maxSize} vs. ${e.length}), and the TensorArray is not marked as dynamically resizeable`);let s=n===0?0:t.size/n,a=[];K(()=>{t=H(t,[1,n,s]);for(let i=0;i<e.length;++i){let l=i===0?0:r[i-1],u=[0,l,0],c=[1,e[i],s];a[i]=H(Pe(t,u,c),this.elementShape)}return a});let o=[];for(let i=0;i<e.length;i++)o[i]=i;this.writeMany(o,a)}},_u=class{constructor(e,t,n,r=-1){this.tensors=e,this.elementShape=t,this.elementDtype=n,e!=null&&e.forEach(s=>{if(n!==s.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${s.dtype}`);Ur(t,s.shape,"TensorList shape mismatch: "),fn(s)}),this.idTensor=Ie(0),this.maxNumElements=r,fn(this.idTensor)}get id(){return this.idTensor.id}copy(){return new _u([...this.tensors],this.elementShape,this.elementDtype)}clearAndClose(e){this.tensors.forEach(t=>{(e==null||!e.has(t.id))&&t.dispose()}),this.tensors.length=0,this.idTensor.dispose()}size(){return this.tensors.length}stack(e,t,n=-1){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(n!==-1&&this.tensors.length!==n)throw new Error(`Operation expected a list with ${n} elements but got a list with ${this.tensors.length} elements.`);Ur(e,this.elementShape,"TensorList shape mismatch: ");let r=xd(this.elementShape,this.tensors,e);return K(()=>{let s=this.tensors.map(a=>H(a,r));return cn(s,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");let n=xd(this.elementShape,this.tensors,e),r=this.tensors.pop();return Ur(r.shape,e,"TensorList shape mismatch: "),H(r,n)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(Ur(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");fn(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 _u([],this.elementShape,this.elementDtype,this.maxNumElements);t.tensors.length=e;for(let n=0;n<Math.min(this.tensors.length,e);++n)t.tensors[n]=this.tensors[n];return t}getItem(e,t,n){if(n!==this.elementDtype)throw new Error(`Invalid data types; op elements ${n}, 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.`);Ur(this.tensors[e].shape,t,"TensorList shape mismatch: ");let r=xd(this.elementShape,this.tensors,t);return H(this.tensors[e],r)}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.`);Ur(this.elementShape,t.shape,"TensorList shape mismatch: "),fn(t),this.tensors[e]=t}gather(e,t,n){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);Ur(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());let r=xd(this.elementShape,this.tensors,n);return e.length===0?pt([],[0].concat(r)):K(()=>{let s=e.map(a=>H(this.tensors[a],r));return cn(s,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);Ur(this.elementShape,t,"TensorList shape mismatch: ");let n=xd(this.elementShape,this.tensors,t);return this.size()===0?pt([],[0].concat(n)):K(()=>{let r=this.tensors.map(s=>H(s,n));return St(r,0)})}};function UH(e,t,n){let r=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==n)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${n}`);let s=e.shape.slice(1);Ur(s,t,"TensorList shape mismatch: ");let a=rr(e);return new _u(a,t,r)}function GH(e,t,n){return new _u([],e,t,n)}function HH(e,t,n,r){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);let s=Math.max(...t);if(r!=null&&r!==-1&&s>=r)throw new Error(`Max index must be < array size (${s} vs. ${r})`);let a=new _u([],n,e.dtype,r),o=rr(e,0);return t.forEach((i,l)=>{a.setItem(i,o[l])}),a}function jH(e,t,n){let r=0,s=t.map(c=>(r+=c,r));if(r!==e.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: ${e.shape}`);let a=e.shape.slice(1),o=jg(a,n),i=r===0?0:e.size/r,l=K(()=>{let c=[];e=H(e,[1,r,i]);for(let p=0;p<t.length;++p){let d=p===0?0:s[p-1],h=[0,d,0],f=[1,t[p],i];c[p]=H(Pe(e,h,f),o)}return e.dispose(),c}),u=new _u([],n,e.dtype,t.length);for(let c=0;c<l.length;c++)u.setItem(c,l[c]);return u}var qH=async(e,t,n)=>{switch(e.op){case"If":case"StatelessIf":{let r=k("thenBranch",e,t,n),s=k("elseBranch",e,t,n),a=k("cond",e,t,n),o=k("args",e,t,n);return(await a.data())[0]?n.functionMap[r].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap):n.functionMap[s].executeFunctionAsync(o,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{let r=k("body",e,t,n),s=k("cond",e,t,n),a=k("args",e,t,n),o=await n.functionMap[s].executeFunctionAsync(a,n.tensorArrayMap,n.tensorListMap),i=a.map(c=>c.id),l=await o[0].data();o.forEach(c=>{!c.kept&&i.indexOf(c.id)===-1&&c.dispose()});let u=a;for(;l[0];){let c=u;u=await n.functionMap[r].executeFunctionAsync(u,n.tensorArrayMap,n.tensorListMap);let p=u.map(h=>h.id);c.forEach(h=>{!h.kept&&i.indexOf(h.id)===-1&&p.indexOf(h.id)===-1&&h.dispose()});let d=await n.functionMap[s].executeFunctionAsync(u,n.tensorArrayMap,n.tensorListMap);l=await d[0].data(),d.forEach(h=>{!h.kept&&i.indexOf(h.id)===-1&&p.indexOf(h.id)===-1&&h.dispose()})}return u}case"LoopCond":{let r=k("pred",e,t,n);return[Xs(r)]}case"Switch":{let r=k("pred",e,t,n),s=k("data",e,t,n);return s.kept||(s=Xs(s)),(await r.data())[0]?[void 0,s]:[s,void 0]}case"Merge":{let r=e.inputNames.find(s=>Vn(s,t,n)!==void 0);if(r){let s=Vn(r,t,n);return[Xs(s)]}return}case"Enter":{let r=k("frameName",e,t,n),s=k("tensor",e,t,n);return n.enterFrame(r),[Xs(s)]}case"Exit":{let r=k("tensor",e,t,n);return n.exitFrame(),[Xs(r)]}case"NextIteration":{let r=k("tensor",e,t,n);return n.nextIteration(),[Xs(r)]}case"TensorArrayV3":{let r=k("size",e,t,n),s=k("dtype",e,t,n),a=k("elementShape",e,t,n),o=k("dynamicSize",e,t,n),i=k("clearAfterRead",e,t,n),l=k("identicalElementShapes",e,t,n),u=k("name",e,t,n),c=new VH(u,s,r,a,l,o,i);return n.addTensorArray(c),[c.idTensor,Ie(1)]}case"TensorArrayWriteV3":{let r=k("tensorArrayId",e,t,n),s=k("index",e,t,n),a=k("tensor",e,t,n),o=n.getTensorArray(r.id);return o.write(s,a),[o.idTensor]}case"TensorArrayReadV3":{let r=k("tensorArrayId",e,t,n),s=k("index",e,t,n);return[n.getTensorArray(r.id).read(s)]}case"TensorArrayGatherV3":{let r=k("tensorArrayId",e,t,n),s=k("indices",e,t,n),a=k("dtype",e,t,n);return[n.getTensorArray(r.id).gather(s,a)]}case"TensorArrayScatterV3":{let r=k("tensorArrayId",e,t,n),s=k("indices",e,t,n),a=k("tensor",e,t,n),o=n.getTensorArray(r.id);return o.scatter(s,a),[o.idTensor]}case"TensorArrayConcatV3":{let r=k("tensorArrayId",e,t,n),s=n.getTensorArray(r.id),a=k("dtype",e,t,n);return[s.concat(a)]}case"TensorArraySplitV3":{let r=k("tensorArrayId",e,t,n),s=k("tensor",e,t,n),a=k("lengths",e,t,n),o=n.getTensorArray(r.id);return o.split(a,s),[o.idTensor]}case"TensorArraySizeV3":{let r=k("tensorArrayId",e,t,n),s=n.getTensorArray(r.id);return[Ie(s.size(),"int32")]}case"TensorArrayCloseV3":{let r=k("tensorArrayId",e,t,n),s=n.getTensorArray(r.id);return s.clearAndClose(),[s.idTensor]}case"TensorListSetItem":{let r=k("tensorListId",e,t,n),s=k("index",e,t,n),a=k("tensor",e,t,n),o=n.getTensorList(r.id);return o.setItem(s,a),[o.idTensor]}case"TensorListGetItem":{let r=k("tensorListId",e,t,n),s=k("index",e,t,n),a=k("elementShape",e,t,n),o=k("elementDType",e,t,n);return[n.getTensorList(r.id).getItem(s,a,o)]}case"TensorListScatterV2":case"TensorListScatter":{let r=k("indices",e,t,n),s=k("tensor",e,t,n),a=k("elementShape",e,t,n),o=k("numElements",e,t,n),i=HH(s,r,a,o);return n.addTensorList(i),[i.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let r=k("elementShape",e,t,n),s=k("elementDType",e,t,n),a;e.op==="TensorListReserve"?a="numElements":a="maxNumElements";let o=k(a,e,t,n),i=GH(r,s,o);return n.addTensorList(i),[i.idTensor]}case"TensorListGather":{let r=k("tensorListId",e,t,n),s=k("indices",e,t,n),a=k("elementShape",e,t,n),o=k("elementDType",e,t,n);return[n.getTensorList(r.id).gather(s,o,a)]}case"TensorListStack":{let r=k("tensorListId",e,t,n),s=k("elementShape",e,t,n),a=k("elementDType",e,t,n),o=k("numElements",e,t,n);return[n.getTensorList(r.id).stack(s,a,o)]}case"TensorListFromTensor":{let r=k("tensor",e,t,n),s=k("elementShape",e,t,n),a=k("elementDType",e,t,n),o=UH(r,s,a);return n.addTensorList(o),[o.idTensor]}case"TensorListConcat":{let r=k("tensorListId",e,t,n),s=n.getTensorList(r.id),a=k("dtype",e,t,n),o=k("elementShape",e,t,n);return[s.concat(a,o)]}case"TensorListPushBack":{let r=k("tensorListId",e,t,n),s=k("tensor",e,t,n),a=n.getTensorList(r.id);return a.pushBack(s),[a.idTensor]}case"TensorListPopBack":{let r=k("tensorListId",e,t,n),s=k("elementShape",e,t,n),a=k("elementDType",e,t,n);return[n.getTensorList(r.id).popBack(s,a)]}case"TensorListSplit":{let r=k("tensor",e,t,n),s=k("elementShape",e,t,n),a=k("lengths",e,t,n),o=jH(r,a,s);return n.addTensorList(o),[o.idTensor]}case"TensorListLength":{let r=k("tensorListId",e,t,n),s=n.getTensorList(r.id);return[Ie(s.size(),"int32")]}case"TensorListResize":{let r=k("tensorListId",e,t,n),s=k("size",e,t,n),o=n.getTensorList(r.id).resize(s);return n.addTensorList(o),[o.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};function Sv(e,t,n){let[r,s]=k("fusedOps",e,t,n),a=r==="biasadd",o=!a,i=s==="prelu",l=r==="fusedbatchnorm",u=k("numArgs",e,t,n);if(a){if(i&&u!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&a&&u!==1)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(l)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");let c=k("strides",e,t,n),p=of(e,t,n),d=k("dataFormat",e,t,n).toUpperCase(),h=k("dilations",e,t,n),[f,m]=k("args",e,t,n);o&&(m=f,f=void 0);let g=k("leakyreluAlpha",e,t,n);return{stride:c,pad:p,dataFormat:d,dilations:h,biasArg:f,preluArg:m,activationFunc:s,leakyreluAlpha:g}}var XH=(e,t,n)=>{switch(e.op){case"Conv1D":{let r=k("stride",e,t,n),s=k("pad",e,t,n),a=k("dataFormat",e,t,n).toUpperCase(),o=k("dilation",e,t,n);return[Ly(k("x",e,t,n),k("filter",e,t,n),r,s,a,o)]}case"Conv2D":{let r=k("strides",e,t,n),s=of(e,t,n),a=k("dataFormat",e,t,n).toUpperCase(),o=k("dilations",e,t,n);return[La(k("x",e,t,n),k("filter",e,t,n),[r[1],r[2]],s,a,[o[1],o[2]])]}case"_FusedConv2D":{let{stride:r,pad:s,dataFormat:a,dilations:o,biasArg:i,preluArg:l,activationFunc:u,leakyreluAlpha:c}=Sv(e,t,n);return[Va.conv2d({x:k("x",e,t,n),filter:k("filter",e,t,n),strides:[r[1],r[2]],pad:s,dataFormat:a,dilations:[o[1],o[2]],bias:i,activation:u,preluActivationWeights:l,leakyreluAlpha:c})]}case"FusedDepthwiseConv2dNative":{let{stride:r,pad:s,dataFormat:a,dilations:o,biasArg:i,preluArg:l,activationFunc:u,leakyreluAlpha:c}=Sv(e,t,n);return[Va.depthwiseConv2d({x:k("x",e,t,n),filter:k("filter",e,t,n),strides:[r[1],r[2]],pad:s,dataFormat:a,dilations:[o[1],o[2]],bias:i,activation:u,preluActivationWeights:l,leakyreluAlpha:c})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{let r=k("outputShape",e,t,n),s=k("strides",e,t,n),a=of(e,t,n);return[Wy(k("x",e,t,n),k("filter",e,t,n),r,[s[1],s[2]],a)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{let r=k("strides",e,t,n),s=of(e,t,n),a=k("dilations",e,t,n),o=k("dataFormat",e,t,n).toUpperCase();return[vp(k("input",e,t,n),k("filter",e,t,n),[r[1],r[2]],s,o,[a[1],a[2]])]}case"Conv3D":{let r=k("strides",e,t,n),s=k("pad",e,t,n),a=k("dataFormat",e,t,n).toUpperCase(),o=k("dilations",e,t,n);return[Vy(k("x",e,t,n),k("filter",e,t,n),[r[1],r[2],r[3]],s,a,[o[1],o[2],o[3]])]}case"AvgPool":{let r=k("strides",e,t,n),s=k("pad",e,t,n),a=k("kernelSize",e,t,n);return[Sm(k("x",e,t,n),[a[1],a[2]],[r[1],r[2]],s)]}case"MaxPool":{let r=k("strides",e,t,n),s=k("pad",e,t,n),a=k("kernelSize",e,t,n);return[$m(k("x",e,t,n),[a[1],a[2]],[r[1],r[2]],s)]}case"MaxPoolWithArgmax":{let r=k("strides",e,t,n),s=k("pad",e,t,n),a=k("kernelSize",e,t,n),o=k("includeBatchInIndex",e,t,n),{result:i,indexes:l}=c7(k("x",e,t,n),[a[1],a[2]],[r[1],r[2]],s,o);return[i,l]}case"AvgPool3D":{let r=k("strides",e,t,n),s=k("pad",e,t,n),a=k("kernelSize",e,t,n);return[My(k("x",e,t,n),[a[1],a[2],a[3]],[r[1],r[2],r[3]],s)]}case"MaxPool3D":{let r=k("strides",e,t,n),s=k("pad",e,t,n),a=k("kernelSize",e,t,n);return[Yy(k("x",e,t,n),[a[1],a[2],a[3]],[r[1],r[2],r[3]],s)]}case"Dilation2D":{let r=k("strides",e,t,n),s=k("pad",e,t,n),a=k("dilations",e,t,n),o=r[1],i=r[2],l=a[1],u=a[2];return[Yw(k("x",e,t,n),k("filter",e,t,n),[o,i],s,[l,u],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},KH=(e,t,n)=>{switch(e.op){case"Fill":{let r=k("shape",e,t,n),s=k("dtype",e,t,n),a=k("value",e,t,n);return[hc(r,a,s)]}case"LinSpace":{let r=k("start",e,t,n),s=k("stop",e,t,n),a=k("num",e,t,n);return[r7(r,s,a)]}case"Multinomial":{let r=k("logits",e,t,n),s=k("numSamples",e,t,n),a=k("seed",e,t,n);return[p7(r,s,a)]}case"OneHot":{let r=k("indices",e,t,n),s=k("depth",e,t,n),a=k("onValue",e,t,n),o=k("offValue",e,t,n);return[Vd(r,s,a,o)]}case"Ones":return[gr(k("shape",e,t,n),k("dtype",e,t,n))];case"OnesLike":return[Pr(k("x",e,t,n))];case"RandomUniform":return[gc(k("shape",e,t,n),k("minval",e,t,n),k("maxval",e,t,n),k("dtype",e,t,n))];case"Range":{let r=k("start",e,t,n),s=k("stop",e,t,n),a=k("step",e,t,n);return[Nu(r,s,a,k("dtype",e,t,n))]}case"TruncatedNormal":{let r=k("shape",e,t,n),s=k("mean",e,t,n),a=k("stdDev",e,t,n),o=k("seed",e,t,n);return[Lm(r,s,a,k("dtype",e,t,n),o)]}case"Zeros":return[Ft(k("shape",e,t,n),k("dtype",e,t,n))];case"ZerosLike":return[st(k("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function ig(e,t,n){let r=k("boxes",e,t,n),s=k("scores",e,t,n),a=k("maxOutputSize",e,t,n),o=k("iouThreshold",e,t,n),i=k("scoreThreshold",e,t,n),l=k("softNmsSigma",e,t,n);return{boxes:r,scores:s,maxOutputSize:a,iouThreshold:o,scoreThreshold:i,softNmsSigma:l}}var ZH=async(e,t,n)=>{switch(e.op){case"NonMaxSuppressionV5":{let{boxes:r,scores:s,maxOutputSize:a,iouThreshold:o,scoreThreshold:i,softNmsSigma:l}=ig(e,t,n),u=await Se.nonMaxSuppressionWithScoreAsync(r,s,a,o,i,l);return[u.selectedIndices,u.selectedScores]}case"NonMaxSuppressionV4":{let{boxes:r,scores:s,maxOutputSize:a,iouThreshold:o,scoreThreshold:i}=ig(e,t,n),l=k("padToMaxOutputSize",e,t,n),u=await Se.nonMaxSuppressionPaddedAsync(r,s,a,o,i,l);return[u.selectedIndices,u.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{let{boxes:r,scores:s,maxOutputSize:a,iouThreshold:o,scoreThreshold:i}=ig(e,t,n);return[await Se.nonMaxSuppressionAsync(r,s,a,o,i)]}case"Where":{let r=ge(k("condition",e,t,n),"bool"),s=[await cA(r)];return r.dispose(),s}case"ListDiff":return g7(k("x",e,t,n),k("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}},YH=(e,t,n)=>{switch(e.op){case"TopKV2":{let r=k("x",e,t,n),s=k("k",e,t,n),a=k("sorted",e,t,n),o=b7(r,s,a);return[o.values,o.indices]}case"Unique":{let r=k("x",e,t,n),s=Sg(r);return[s.values,s.indices]}case"UniqueV2":{let r=k("x",e,t,n),s=k("axis",e,t,n),a=Sg(r,s);return[a.values,a.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},JH=(e,t,n)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":let r=k("default",e,t,n);return[Vn(e.name,t,n)||r];case"Placeholder":return[Vn(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{let u=k("x",e,t,n);return[Xs(u)]}case"IdentityN":return k("x",e,t,n).map(u=>Xs(u));case"Snapshot":let s=k("x",e,t,n);return[Xs(s)];case"Shape":return[Ct(k("x",e,t,n).shape,"int32")];case"ShapeN":return k("x",e,t,n).map(u=>Ct(u.shape));case"Size":return[Ie(k("x",e,t,n).size,"int32")];case"Rank":return[Ie(k("x",e,t,n).rank,"int32")];case"NoOp":return[Ie(1)];case"Print":let a=k("x",e,t,n),o=k("data",e,t,n),i=k("message",e,t,n),l=k("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(i);for(let u=0;u<o.length;u++)console.log(Array.prototype.slice.call(o[u].dataSync()).slice(0,l));return[a];default:throw TypeError(`Node type ${e.op} is not implemented`)}},QH=class{constructor(e,t){this.keyDType=e,this.valueDType=t,this.handle=Ie(0),this.tensorMap=new Map,fn(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 Ie(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);let n=await e.data();return this.tensorMap.forEach(r=>r.dispose()),this.tensorMap.clear(),K(()=>{let r=rr(t),s=n.length,a=r.length;w.assert(s===a,()=>`The number of elements doesn't match, keys has ${s} elements, the values has ${a} elements.`);for(let o=0;o<s;o++){let i=n[o],l=r[o];fn(l),this.tensorMap.set(i,l)}return this.handle})}async find(e,t){this.checkKeyAndValueTensor(e,t);let n=await e.data();return K(()=>{let r=[];for(let s=0;s<n.length;s++){let a=n[s],o=this.findWithDefault(a,t);r.push(o)}return cn(r)})}findWithDefault(e,t){let n=this.tensorMap.get(e);return n!=null?n: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}`)}},ej=async(e,t,n,r)=>{switch(e.op){case"HashTable":case"HashTableV2":{let s=k("keyDType",e,t,n),a=k("valueDType",e,t,n),o=new QH(s,a);return r.addHashTable(e.name,o),[o.handle]}case"LookupTableImport":case"LookupTableImportV2":{let s=k("tableHandle",e,t,n,r),a=k("keys",e,t,n),o=k("values",e,t,n);return[await r.getHashTableById(s.id).import(a,o)]}case"LookupTableFind":case"LookupTableFindV2":{let s=k("tableHandle",e,t,n,r),a=k("keys",e,t,n),o=k("defaultValue",e,t,n);return[await r.getHashTableById(s.id).find(a,o)]}case"LookupTableSize":case"LookupTableSizeV2":{let s=k("tableHandle",e,t,n,r);return[r.getHashTableById(s.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},tj=(e,t,n)=>{switch(e.op){case"ResizeBilinear":{let r=k("images",e,t,n),s=k("size",e,t,n),a=k("alignCorners",e,t,n),o=k("halfPixelCenters",e,t,n);return[Se.resizeBilinear(r,[s[0],s[1]],a,o)]}case"ResizeNearestNeighbor":{let r=k("images",e,t,n),s=k("size",e,t,n),a=k("alignCorners",e,t,n),o=k("halfPixelCenters",e,t,n);return[Se.resizeNearestNeighbor(r,[s[0],s[1]],a,o)]}case"CropAndResize":{let r=k("image",e,t,n),s=k("boxes",e,t,n),a=k("boxInd",e,t,n),o=k("cropSize",e,t,n),i=k("method",e,t,n),l=k("extrapolationValue",e,t,n);return[Se.cropAndResize(r,s,a,o,i,l)]}case"ImageProjectiveTransformV3":{let r=k("images",e,t,n),s=k("transforms",e,t,n),a=k("outputShape",e,t,n),o=k("fillValue",e,t,n),i=k("interpolation",e,t,n),l=k("fillMode",e,t,n);return[Se.transform(r,s,i.toLowerCase(),l.toLowerCase(),o,a)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},nj=(e,t,n)=>{switch(e.op){case"Equal":return[_r(k("a",e,t,n),k("b",e,t,n))];case"NotEqual":return[Tu(k("a",e,t,n),k("b",e,t,n))];case"Greater":return[Ar(k("a",e,t,n),k("b",e,t,n))];case"GreaterEqual":return[_l(k("a",e,t,n),k("b",e,t,n))];case"Less":return[jy(k("a",e,t,n),k("b",e,t,n))];case"LessEqual":return[$l(k("a",e,t,n),k("b",e,t,n))];case"LogicalAnd":return[ms(k("a",e,t,n),k("b",e,t,n))];case"LogicalNot":return[_m(k("a",e,t,n))];case"LogicalOr":return[Zy(k("a",e,t,n),k("b",e,t,n))];case"Select":case"SelectV2":return[Hn(k("condition",e,t,n),k("a",e,t,n),k("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},rj=(e,t,n)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[Ye(k("a",e,t,n),k("b",e,t,n),k("transposeA",e,t,n),k("transposeB",e,t,n))];case"Einsum":return[Qw(k("equation",e,t,n),...k("tensors",e,t,n))];case"Transpose":return[et(k("x",e,t,n),k("perm",e,t,n))];case"_FusedMatMul":let[r,s]=k("fusedOps",e,t,n),a=r==="biasadd",o=s==="prelu",i=k("numArgs",e,t,n),l=k("leakyreluAlpha",e,t,n);if(a){if(o&&i!==2)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&i!==1)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}let[u,c]=k("args",e,t,n);return[Va.matMul({a:k("a",e,t,n),b:k("b",e,t,n),transposeA:k("transposeA",e,t,n),transposeB:k("transposeB",e,t,n),bias:u,activation:s,preluActivationWeights:c,leakyreluAlpha:l})];default:throw TypeError(`Node type ${e.op} is not implemented`)}},sj=(e,t,n)=>{switch(e.op){case"FusedBatchNorm":case"FusedBatchNormV2":return[Iu(k("x",e,t,n),k("mean",e,t,n),k("variance",e,t,n),k("offset",e,t,n),k("scale",e,t,n),k("epsilon",e,t,n))];case"FusedBatchNormV3":return[Iu(k("x",e,t,n),k("mean",e,t,n),k("variance",e,t,n),k("offset",e,t,n),k("scale",e,t,n),k("epsilon",e,t,n))];case"LRN":return[s7(k("x",e,t,n),k("radius",e,t,n),k("bias",e,t,n),k("alpha",e,t,n),k("beta",e,t,n))];case"Softmax":return[yc(k("x",e,t,n))];case"LogSoftmax":return[qy(k("x",e,t,n))];case"SparseToDense":return[pA(k("sparseIndices",e,t,n),k("outputShape",e,t,n),k("sparseValues",e,t,n),k("defaultValue",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},aj=(e,t,n)=>{switch(e.op){case"Max":{let o=k("axis",e,t,n),i=k("keepDims",e,t,n);return[gn(k("x",e,t,n),o,i)]}case"Mean":{let o=k("axis",e,t,n),i=k("keepDims",e,t,n);return[Vt(k("x",e,t,n),o,i)]}case"Min":{let o=k("axis",e,t,n),i=k("keepDims",e,t,n);return[Ba(k("x",e,t,n),o,i)]}case"Sum":{let o=k("axis",e,t,n),i=k("keepDims",e,t,n);return[ke(k("x",e,t,n),o,i)]}case"All":{let o=k("axis",e,t,n),i=k("keepDims",e,t,n);return[Fy(k("x",e,t,n),o,i)]}case"Any":{let o=k("axis",e,t,n),i=k("keepDims",e,t,n);return[If(k("x",e,t,n),o,i)]}case"ArgMax":{let o=k("axis",e,t,n);return[Rr(k("x",e,t,n),o)]}case"ArgMin":{let o=k("axis",e,t,n);return[Rw(k("x",e,t,n),o)]}case"Prod":{let o=k("axis",e,t,n),i=k("keepDims",e,t,n);return[Jy(k("x",e,t,n),o,i)]}case"Cumprod":{let o=k("axis",e,t,n),i=k("exclusive",e,t,n),l=k("reverse",e,t,n);return[Tf(k("x",e,t,n),o,i,l)]}case"Cumsum":{let o=k("axis",e,t,n),i=k("exclusive",e,t,n),l=k("reverse",e,t,n);return[Gy(k("x",e,t,n),o,i,l)]}case"Bincount":let r=k("x",e,t,n),s=k("weights",e,t,n),a=k("size",e,t,n);return[zy(r,s,a)];case"DenseBincount":{let o=k("x",e,t,n),i=k("weights",e,t,n),l=k("size",e,t,n),u=k("binaryOutput",e,t,n);return[Kw(o,i,l,u)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},oj=(e,t,n)=>{switch(e.op){case"ConcatV2":case"Concat":{let r=k("n",e,t,n),s=k("axis",e,t,n),a=k("tensors",e,t,n);return a=a.slice(0,r),[St(a,s)]}case"Gather":{let r=k("x",e,t,n),s=k("indices",e,t,n);return[Cu(r,ge(s,"int32"),0)]}case"GatherV2":{let r=k("axis",e,t,n),s=k("batchDims",e,t,n),a=k("x",e,t,n),o=k("indices",e,t,n);return[Cu(a,ge(o,"int32"),r,s)]}case"Reverse":{let r=k("dims",e,t,n),s=[];for(let o=0;o<r.length;o++)r[o]&&s.push(o);let a=k("x",e,t,n);return[Fr(a,s)]}case"ReverseV2":{let r=k("axis",e,t,n),s=k("x",e,t,n);return[Fr(s,r)]}case"Slice":{let r=k("begin",e,t,n),s=k("size",e,t,n);return[Pe(k("x",e,t,n),r,s)]}case"StridedSlice":{let r=k("begin",e,t,n),s=k("end",e,t,n),a=k("strides",e,t,n),o=k("beginMask",e,t,n),i=k("endMask",e,t,n),l=k("ellipsisMask",e,t,n),u=k("newAxisMask",e,t,n),c=k("shrinkAxisMask",e,t,n),p=k("x",e,t,n);return[A7(p,r,s,a,o,i,l,u,c)]}case"Pack":return K(()=>{let r=k("axis",e,t,n),s=k("tensors",e,t,n),a=s[0].shape,o=tt(s[0]).shape,i=s.map(l=>{let u=w.arraysEqual(l.shape,a);if(!u&&!w.arraysEqual(tt(l).shape,o))throw new Error("the input tensors shape does not match");return u?l:H(l,a)});return[cn(i,r)]});case"Unpack":{let r=k("axis",e,t,n),s=k("tensor",e,t,n);return rr(s,r)}case"Tile":{let r=k("reps",e,t,n);return[Gr(k("x",e,t,n),r)]}case"Split":case"SplitV":{let r=k("axis",e,t,n),s=k("numOrSizeSplits",e,t,n),a=k("x",e,t,n);return Yt(a,s,r)}case"ScatterNd":{let r=k("indices",e,t,n),s=k("values",e,t,n),a=k("shape",e,t,n);return[I7(r,s,a)]}case"GatherNd":{let r=k("x",e,t,n),s=k("indices",e,t,n);return[C7(r,s)]}case"SparseToDense":{let r=k("sparseIndices",e,t,n),s=k("outputShape",e,t,n),a=k("sparseValues",e,t,n),o=k("defaultValue",e,t,n);return[pA(r,a,s,a.dtype===o.dtype?o:ge(o,a.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},ij=(e,t,n)=>{switch(e.op){case"SparseFillEmptyRows":{let{outputIndices:r,outputValues:s,emptyRowIndicator:a,reverseIndexMap:o}=kd.sparseFillEmptyRows(k("indices",e,t,n),k("values",e,t,n),k("denseShape",e,t,n),k("defaultValue",e,t,n));return[r,s,a,o]}case"SparseReshape":{let{outputIndices:r,outputShape:s}=kd.sparseReshape(k("inputIndices",e,t,n),k("inputShape",e,t,n),k("newShape",e,t,n));return[r,s]}case"SparseSegmentMean":return[kd.sparseSegmentMean(k("data",e,t,n),k("indices",e,t,n),k("segmentIds",e,t,n))];case"SparseSegmentSum":return[kd.sparseSegmentSum(k("data",e,t,n),k("indices",e,t,n),k("segmentIds",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},lj=(e,t,n)=>{switch(e.op){case"FFT":return[Mm(k("x",e,t,n))];case"IFFT":return[Gd(k("x",e,t,n))];case"RFFT":return[zm(k("x",e,t,n))];case"IRFFT":return[lA(k("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},uj=(e,t,n)=>{switch(e.op){case"StringNGrams":{let{nGrams:r,nGramsSplits:s}=af.stringNGrams(k("data",e,t,n),k("dataSplits",e,t,n),k("separator",e,t,n),k("nGramWidths",e,t,n),k("leftPad",e,t,n),k("rightPad",e,t,n),k("padWidth",e,t,n),k("preserveShortSequences",e,t,n));return[r,s]}case"StringSplit":{let{indices:r,values:s,shape:a}=af.stringSplit(k("input",e,t,n),k("delimiter",e,t,n),k("skipEmpty",e,t,n));return[r,s,a]}case"StringToHashBucketFast":return[af.stringToHashBucketFast(k("input",e,t,n),k("numBuckets",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},cj=(e,t,n)=>{switch(e.op){case"Cast":return[ge(k("x",e,t,n),k("dtype",e,t,n))];case"ExpandDims":{let r=k("axis",e,t,n);return[Kt(k("x",e,t,n),r)]}case"Squeeze":{let r=k("axis",e,t,n);return[tt(k("x",e,t,n),r)]}case"Reshape":return[H(k("x",e,t,n),k("shape",e,t,n))];case"MirrorPad":return[d7(k("x",e,t,n),k("padding",e,t,n),k("mode",e,t,n))];case"PadV2":case"Pad":return[Xr(k("x",e,t,n),k("padding",e,t,n),k("constantValue",e,t,n))];case"SpaceToBatchND":{let r=k("blockShape",e,t,n),s=k("paddings",e,t,n);return[Pm(k("x",e,t,n),r,s)]}case"BatchToSpaceND":{let r=k("blockShape",e,t,n),s=k("crops",e,t,n);return[Im(k("x",e,t,n),r,s)]}case"DepthToSpace":{let r=k("blockSize",e,t,n),s=k("dataFormat",e,t,n).toUpperCase();return[Zw(k("x",e,t,n),r,s)]}case"BroadcastTo":return[$d(k("x",e,t,n),k("shape",e,t,n))];case"BroadcastArgs":return[Vw(k("s0",e,t,n),k("s1",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function Iv(e,t,n,r){let s=((a,o,i)=>{switch(a.category){case"arithmetic":return K(()=>BH(a,o,i));case"basic_math":return K(()=>WH(a,o,i));case"control":return qH(a,o,i);case"convolution":return K(()=>XH(a,o,i));case"creation":return K(()=>KH(a,o,i));case"dynamic":return ZH(a,o,i);case"evaluation":return K(()=>YH(a,o,i));case"image":return K(()=>tj(a,o,i));case"graph":return K(()=>JH(a,o,i));case"logical":return K(()=>nj(a,o,i));case"matrices":return K(()=>rj(a,o,i));case"normalization":return K(()=>sj(a,o,i));case"reduction":return K(()=>aj(a,o,i));case"slice_join":return K(()=>oj(a,o,i));case"sparse":return K(()=>ij(a,o,i));case"spectral":return K(()=>lj(a,o,i));case"string":return K(()=>uj(a,o,i));case"transformation":return K(()=>cj(a,o,i));case"hash_table":return ej(a,o,i,r);case"custom":let l=ck(a.op);if(l&&l.customExecutor)return l.customExecutor(new LH(a,o,i));throw TypeError(`Custom op ${a.op} is not registered.`);default:throw TypeError(`Unknown op '${a.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(e,t,n);return w.isPromise(s)?s.then(a=>[].concat(a)):[].concat(s)}var Cv=class{constructor(e={},t={},n={},r={}){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=n,this.functionMap=r,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){let e=[];for(let t=0;t<this.contexts.length-1;t++){let n=this.contexts.slice(0,this.contexts.length-t);e.push(this.contextIdforContexts(n))}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 Tv(e,t,n,r){let s=new Set,a=[],o=null,i=null,l=new Set,u=Object.keys(e).map(d=>fr(d)[0]),c=[];r!=null&&(c=r.map(d=>fr(d.name)[0]));let p=[...t];for(;p.length>0;){let d=p.pop();if(($k(d)||mj(d)||gj(d))&&o==null&&(o=d,i=o.children.map(h=>h.name).filter(h=>s.has(h))),s.add(d.name),n[d.name]==null&&u.indexOf(d.name)===-1&&c.indexOf(d.name)===-1){if(d.inputs.length===0){a.push(d.name);continue}d.inputs.forEach(h=>{l.has(h.name)||(l.add(h.name),p.push(h))})}}return{inputs:e,outputs:t,usedNodes:s,missingInputs:a,dynamicNode:o,syncInputs:i}}function dj(e,t,n){let{usedNodes:r,inputs:s}=n,a=[],o=Object.keys(s).map(c=>fr(c)[0]).map(c=>e.nodes[c]),i=e.initNodes;o.forEach(c=>{r.has(c.name)&&a.push(c)}),e.weights.forEach(c=>{r.has(c.name)&&a.push(c)}),i!=null&&i.forEach(c=>{r.has(c.name)&&a.push(c)});let l=new Set,u=[];for(;a.length>0;){let c=a.pop();l.add(c.name),t[c.name]||u.push(c),c.children.forEach(p=>{!l.has(p.name)&&r.has(p.name)&&p.inputs.every(d=>l.has(d.name))&&a.push(p)})}return u}var pj=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],hj=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],fj=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"];function $k(e){return pj.indexOf(e.op)>=0}function mj(e){return hj.indexOf(e.op)>=0}function gj(e){return fj.indexOf(e.op)>=0}var qg=class{constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this._functions={},this._functionExecutorMap={},this.intermediateTensors={},this.keepTensorForDebug=!1,this._outputs=e.outputs,this._inputs=e.inputs,this._initNodes=e.initNodes,this._signature=e.signature,this._functions=e.functions,e.functions!=null&&Object.keys(e.functions).forEach(n=>{this._functionExecutorMap[n]=new qg(e.functions[n],this)})}get weightIds(){return this.parent?this.parent.weightIds:this._weightIds}get functionExecutorMap(){return this.parent?this.parent.functionExecutorMap:this._functionExecutorMap}get weightMap(){return this.parent?this.parent.weightMap:this._weightMap}set weightMap(e){let t=Object.keys(e).map(n=>e[n].map(r=>r.id));this._weightIds=[].concat(...t),this._weightMap=e}set resourceManager(e){this._resourceManager=e}get inputs(){return this._inputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get outputs(){return this._outputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get inputNodes(){return this._inputs.map(e=>e.signatureKey||e.name)}get outputNodes(){return this._outputs.map(e=>{let t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t})}get functions(){return Object.keys(this._functions).reduce((e,t)=>(e[t]=this._functions[t].signature,e),{})}getCompilationKey(e,t){let n=e.map(s=>s.name).sort(),r=t.map(s=>s.name).sort();return n.join(this.SEPERATOR)+"--"+r.join(this.SEPERATOR)}compile(e,t){let n=Tv(e,t,this.weightMap,this._initNodes),{missingInputs:r,dynamicNode:s,syncInputs:a}=n;if(s!=null)throw new Error(`This execution contains the node '${s.name}', which has the dynamic op '${s.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${a}]`);if(r.length>0){let o=t.map(l=>l.name),i=Object.keys(e);throw new Error(`Cannot compute the outputs [${o}] from the provided inputs [${i}]. Missing the following inputs: [${r}]`)}return dj(this.graph,this.weightMap,n)}execute(e,t){e=this.mapInputs(e);let n=Object.keys(e).sort();this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t);let r=n.map(c=>this.graph.nodes[fr(c)[0]]),s=t.map(c=>fr(c)[0]),a=s.map(c=>this.graph.nodes[c]);this.resetIntermediateTensors(),a.length===0&&(a=this._outputs);let o=this.getCompilationKey(r,a),i=this.compiledMap.get(o);i==null&&(i=this.compile(e,a),this.compiledMap.set(o,i));let l={},u={};return K(()=>{let c=new Cv(this.weightMap,l,u,this.functionExecutorMap),p={...this.weightMap};Object.keys(e).forEach(f=>{let[m,g]=fr(f),y=[];y[g]=e[f],p[m]=y});let d=this.getFrozenTensorIds(p),h={};for(let f=0;f<i.length;f++){let m=i[f];if(!p[m.name]){let g=Iv(m,p,c,this._resourceManager);if(w.isPromise(g))throw new Error(`The execution of the op '${m.op}' returned a promise. Please use model.executeAsync() instead.`);p[m.name]=g,this.checkTensorForDisposal(m.name,m,p,c,d,s,h)}}return this.parent==null&&c.dispose(d),t.map(f=>Vn(f,p,c))})}getFrozenTensorIds(e){let t=[].concat.apply([],Object.keys(e).map(n=>e[n]).map(n=>n.map(r=>r.id)));return new Set(t)}checkTensorForDisposal(e,t,n,r,s,a,o){t.category==="control"||a.indexOf(e)!==-1||(n[e].forEach(i=>{i!=null&&(o[i.id]=(o[i.id]||0)+t.children.length)}),t.inputs.forEach(i=>{if(i.category!=="control"){let l=AH(i.name,n,r);l!=null&&l.forEach(u=>{if(u&&!u.kept&&!s.has(u.id)){let c=o[u.id];if(c===1){if(!this.keepTensorForDebug)u.dispose();else{let[p,d]=Es(t.name,r);this.intermediateTensors[p]?this.intermediateTensors[p][d]=u:(this.intermediateTensors[p]=[],this.intermediateTensors[p][d]=u)}delete o[u.id]}else c!=null&&o[u.id]--}})}}))}async executeAsync(e,t){return this._executeAsync(e,t)}disposeIntermediateTensors(){!this.intermediateTensors||(Object.keys(this.intermediateTensors).forEach(e=>this.intermediateTensors[e].forEach(t=>t.dispose())),this.disposeTensorsMap())}disposeTensorsMap(){!this.tensorsMap||Object.keys(this.tensorsMap).forEach(e=>{this.tensorsMap[e].forEach(n=>{n&&!n.kept&&!n.isDisposed&&!this.keepIds.has(n.id)&&n.dispose()})})}getIntermediateTensors(){return this.tensorsMap}resetIntermediateTensors(){for(let e in this.intermediateTensors)this.intermediateTensors[e].forEach(t=>t.dispose()),delete this.intermediateTensors[e]}async _executeAsync(e,t,n=!1,r={},s={}){n||(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 a=new Cv(this.weightMap,r,s,this.functionExecutorMap);this.tensorsMap=await this.executeWithControlFlow(e,a,t,n);let o=t.map(u=>Vn(u,this.tensorsMap,a)),i=o.map(u=>u.id),l=Object.keys(e).map(u=>e[u].id);return this.keepIds=new Set([...i,...l,...this.weightIds]),this.keepTensorForDebug||this.disposeTensorsMap(),this.parent==null&&a.dispose(this.keepIds),o}async executeFunctionAsync(e,t,n){let r=e.reduce((s,a,o)=>(s[this.inputs[o].name]=a,s),{});return this._executeAsync(r,this.outputNodes,!0,t,n)}async executeWithControlFlow(e,t,n,r){let s=Object.keys(e),a=s.map(x=>this.graph.nodes[fr(x)[0]]),o=n.map(x=>fr(x)[0]),i=o.map(x=>this.graph.nodes[x]);i.length===0&&(i=this._outputs);let{usedNodes:l,missingInputs:u,dynamicNode:c,syncInputs:p}=Tv(e,i,this.weightMap,this._initNodes),d=[...a,...this.graph.weights,...this._initNodes||[]].map(x=>({node:x,contexts:t.currentContext})),h={...this.weightMap};Object.keys(e).forEach(x=>{let[A,b]=fr(x),v=[];v[b]=e[x],h[A]=v});let f={},m=this.getFrozenTensorIds(h),g={};for(;d.length>0;){let x=this.processStack(a,d,t,h,g,m,o,f,l);await Promise.all(x)}c==null&&!r&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");let y=i.filter(x=>!$k(x)&&!Vn(x.name,h,t)).map(x=>x.name);if(y.length>0){let x="";throw c!=null&&(x=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${p}]`),new Error(`Cannot compute the outputs [${y}] from the provided inputs [${s}]. Consider providing the following inputs: [${u}]. ${x}`)}return h}processStack(e,t,n,r,s,a,o,i,l){let u=[];for(;t.length>0;){let c=t.pop();n.currentContext=c.contexts;let p="";if(c.node.op==="Enter"&&k("isConstant",c.node,r,n)&&([p]=Es(c.node.name,n)),r[c.node.name]==null){let d=Iv(c.node,r,n,this._resourceManager);p||([p]=Es(c.node.name,n));let h=n.currentContext;w.isPromise(d)?u.push(d.then(f=>(r[p]=f,n.currentContext=h,this.checkTensorForDisposal(p,c.node,r,n,a,o,i),this.processChildNodes(c.node,t,n,r,s,l),f))):(r[p]=d,this.checkTensorForDisposal(p,c.node,r,n,a,o,i),this.processChildNodes(c.node,t,n,r,s,l))}else this.processChildNodes(c.node,t,n,r,s,l)}return u}processChildNodes(e,t,n,r,s,a){e.children.forEach(o=>{let[i]=Es(o.name,n);s[i]||!a.has(o.name)||(o.op==="Merge"?o.inputNames.some(l=>!!Vn(l,r,n))&&(s[i]=!0,t.push({contexts:n.currentContext,node:o})):o.inputNames.every(l=>!!Vn(l,r,n))&&(s[i]=!0,t.push({contexts:n.currentContext,node:o})))})}dispose(){Object.keys(this.weightMap).forEach(e=>this.weightMap[e].forEach(t=>t.dispose()))}checkInputShapeAndType(e){Object.keys(e).forEach(t=>{let n=e[t],[r]=fr(t),s=this.graph.nodes[r];if(s.attrParams.shape&&s.attrParams.shape.value){let a=s.attrParams.shape.value,o=a.length===n.shape.length&&n.shape.every((i,l)=>a[l]===-1||a[l]===i);w.assert(o,()=>`The shape of dict['${s.name}'] provided in model.execute(dict) must be [${a}], but was [${n.shape}]`)}s.attrParams.dtype&&s.attrParams.dtype.value&&w.assert(n.dtype===s.attrParams.dtype.value,()=>`The dtype of dict['${s.name}'] provided in model.execute(dict) must be ${s.attrParams.dtype.value}, but was ${n.dtype}`)})}mapInputs(e){let t={};for(let n in e)if(this._signature!=null&&this._signature.inputs!=null&&this._signature.inputs[n]!=null){let r=this._signature.inputs[n];t[r.name]=e[n]}else t[n]=e[n];return t}checkInputs(e){let t=Object.keys(e).filter(n=>{let[r]=fr(n);return this.graph.nodes[r]==null});if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map(t=>this._signature!=null&&this._signature.outputs!=null&&this._signature.outputs[t]!=null?this._signature.outputs[t].name:t,{})}checkOutputs(e){e.forEach(t=>{let[n]=fr(t);if(!this.graph.nodes[n])throw new Error(`The output '${t}' is not found in the graph`)})}},yj=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]}},Aj="?tfjs-format=file",xj="model.json",A0=class{constructor(e,t={}){this.modelUrl=e,this.loadOptions=t,this.version="n/a",t==null&&(this.loadOptions={}),this.resourceManager=new yj}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=Cn.browserHTTPRequest(e,this.loadOptions);else{let t=Cn.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(Cn.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,n;this.artifacts.userDefinedMetadata!=null&&this.artifacts.userDefinedMetadata.signature!=null?n=this.artifacts.userDefinedMetadata.signature:n=this.artifacts.signature,this.signature=n,this.version=`${t.versions.producer}.${t.versions.minConsumer}`;let r=Cn.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new qg(vv.Instance.transformGraph(t,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(r),this.executor.resourceManager=this.resourceManager,e.modelInitializer!=null&&e.modelInitializer.node!=null){let s=vv.Instance.transformGraph(e.modelInitializer);this.initializer=new qg(s),this.initializer.weightMap=this.executor.weightMap,this.initializer.resourceManager=this.resourceManager,this.initializer.executeAsync({},[])}return!0}async save(e,t){if(typeof e=="string"){let n=Cn.getSaveHandlers(e);if(n.length===0)throw new Error(`Cannot find any save handlers for URL '${e}'`);if(n.length>1)throw new Error(`Found more than one (${n.length}) save handlers for URL '${e}'`);e=n[0]}if(e.save==null)throw new Error("GraphModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");return e.save(this.artifacts)}predict(e,t){return this.execute(e,this.outputNodes)}normalizeInputs(e){if(!(e instanceof rt)&&!Array.isArray(e))return e;if(e=Array.isArray(e)?e:[e],e.length!==this.inputNodes.length)throw new Error(`Input tensor count mismatch,the graph model has ${this.inputNodes.length} placeholders, while there are ${e.length} input tensors.`);return this.inputNodes.reduce((t,n,r)=>(t[n]=e[r],t),{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}execute(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let n=this.executor.execute(e,t);return n.length>1?n:n[0]}async executeAsync(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let n=await this.executor.executeAsync(e,t);return n.length>1?n:n[0]}getIntermediateTensors(){return this.executor.getIntermediateTensors()}disposeIntermediateTensors(){this.executor.disposeIntermediateTensors()}convertTensorMapToTensorsMap(e){return Object.keys(e).reduce((t,n)=>(t[n]=[e[n]],t),{})}dispose(){this.executor.dispose(),this.initializer&&this.initializer.dispose(),this.resourceManager.dispose()}};async function bj(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}${xj}${Aj}`);let n=new A0(e,t);return await n.load(),n}var vj="0.0.0",Dk={};Le(Dk,{CSVDataset:()=>Hk,Dataset:()=>vc,FileDataSource:()=>Jk,TextLineDataset:()=>Gk,URLDataSource:()=>Qk,array:()=>Gj,csv:()=>tq,func:()=>nq,generator:()=>rq,microphone:()=>aq,version_data:()=>oq,webcam:()=>sq,zip:()=>Hj});var wj=Vi(Xf()),kj=Vi(Xf());function Sj(e,t){return zf(e,t)}function zf(e,t,n=new Map,r=new Set){if(e==null)return null;if(typeof Blob=="function"&&e instanceof Blob)return e.slice();if(r.has(e))throw new Error("Circular references are not supported.");if(n.has(e))return n.get(e);let s=t(e);if(s.recurse&&s.value!==null)throw new Error("A deep map function may not return both a value and recurse=true.");if(s.recurse)if($u(e)){let a=Array.isArray(e)?[]:{};r.add(e);for(let o in e){let i=e[o],l=zf(i,t,n,r);a[o]=l}return r.delete(e),e.__proto__&&(a.__proto__=e.__proto__),a}else throw new Error(`Can't recurse into non-iterable type: ${e}`);else return n.set(e,s.value),s.value}function Ij(e,t=Fk){return Pk(e,t)}function Pk(e,t,n=new Set){let r=e[0];if(n.has(r))throw new Error("Circular references are not supported.");let s=t(e);if(s.recurse&&s.value!==null)throw new Error("A deep zip function may not return both a value and recurse=true.");if(s.recurse)if($u(r)){let a=Array.isArray(r)?[]:{};n.add(r);for(let o in r){let i=e.map(u=>u[o]),l=Pk(i,t,n);a[o]=l}return n.delete(r),a}else throw new Error(`Can't recurse into non-iterable type: ${r}`);else return s.value}function Fk(e){return e===null?null:$u(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function Ok(e,t){let n=new Map;zf(e,t,n);for(let s of Array.from(n.keys())){let a=n.get(s);if(w.isPromise(a)){let o=await a;n.set(s,o)}}return zf(e,t,n)}function $u(e){let t=!1;if(Y().get("IS_BROWSER"))t=e instanceof TextDecoder;else{let{StringDecoder:n}=b4();t=e instanceof n}return e!=null&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||typeof e=="object"&&!(e instanceof rt)&&!(e instanceof Promise)&&!t)}function Cj(e){return e==null||Tj(e)||Array.isArray(e)||typeof e=="object"&&e instanceof rt||w.isTypedArray(e)}function Tj(e){return e===null||typeof e!="object"&&typeof e!="function"}function Nj(e){return Sj(e,Ej)}function Ej(e){return e instanceof rt?{value:e.clone(),recurse:!1}:$u(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}var Mk=class{constructor(e){if(this.capacity=e,this.begin=0,this.end=0,e==null)throw new RangeError("Can't create a ring buffer of unknown capacity.");if(e<1)throw new RangeError("Can't create ring buffer of capacity < 1.");this.data=new Array(e),this.doubledCapacity=2*e}wrap(e){for(;e<0;)e+=this.doubledCapacity;return e%this.doubledCapacity}get(e){if(e<0)throw new RangeError("Can't get item at a negative index.");return this.data[e%this.capacity]}set(e,t){if(e<0)throw new RangeError("Can't set item at a negative index.");this.data[e%this.capacity]=t}length(){let e=this.end-this.begin;return e<0&&(e=this.doubledCapacity+e),e}isFull(){return this.length()===this.capacity}isEmpty(){return this.length()===0}push(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.set(this.end,e),this.end=this.wrap(this.end+1)}pushAll(e){for(let t of e)this.push(t)}pop(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");this.end=this.wrap(this.end-1);let e=this.get(this.end);return this.set(this.end,void 0),e}unshift(e){if(this.isFull())throw new RangeError("Ring buffer is full.");this.begin=this.wrap(this.begin-1),this.set(this.begin,e)}shift(){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");let e=this.get(this.begin);return this.set(this.begin,void 0),this.begin=this.wrap(this.begin+1),e}shuffleExcise(e){if(this.isEmpty())throw new RangeError("Ring buffer is empty.");let t=this.wrap(this.begin+e),n=this.get(t);return this.set(t,this.pop()),n}},zk=class extends Mk{constructor(){super(zk.INITIAL_CAPACITY)}isFull(){return!1}push(e){super.isFull()&&this.expand(),super.push(e)}unshift(e){super.isFull()&&this.expand(),super.unshift(e)}expand(){let e=this.capacity*2,t=new Array(e),n=this.length();for(let r=0;r<n;r++)t[r]=this.get(this.wrap(this.begin+r));this.data=t,this.capacity=e,this.doubledCapacity=2*this.capacity,this.begin=0,this.end=n}},Lk=zk;Lk.INITIAL_CAPACITY=32;function Bk(e){return new $j(e)}function qx(e){return new Dj(e)}function Rj(e,t){return new Wk(e,t)}function _j(e,t=Vk.FAIL){return new Vj(e,t)}var An=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=[],n=await e.next();for(;!n.done;)t.push(n.value),n=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(),n=e(t.value);for(;!t.done&&n;)t=await this.next(),n=e(t.value)}handleErrors(e){return new Bj(this,e)}filter(e){return new zj(this,e)}map(e){return new Lj(this,e)}mapAsync(e){return new Nv(this,e)}serialMapAsync(e){return new Nv(this,e).serial()}flatmap(e){return new Wj(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 Mj(this,e,t)}columnMajorBatch(e,t=!0,n=Fk){return this.rowMajorBatch(e,t).map(s=>Ij(s,n))}concatenate(e,t){return new Wk(Bk([this,e]),t)}take(e){return e<0||e==null?this:new Oj(this,e)}skip(e){return e<0||e==null?this:new Fj(this,e)}prefetch(e){return new Uk(this,e)}shuffle(e,t){return new Uj(this,e,t)}serial(){return new Pj(this)}},$j=class extends An{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:Nj(e),done:!1}}},Dj=class extends An{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}}},Pj=class extends An{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()}},Fj=class extends An{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;ne(e.value)}return this.upstream.next()}},Oj=class extends An{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()}},Mj=class extends An{constructor(e,t,n=!0){super(),this.upstream=e,this.batchSize=t,this.enableSmallLastBatch=n,this.lastRead=Promise.resolve({value:null,done:!1})}summary(){return`${this.upstream.summary()} -> RowMajorBatch`}async next(){return this.lastRead=this.lastRead.then(()=>this.serialNext()),this.lastRead}async serialNext(){let e=[];for(;e.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}}},zj=class extends An{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;ne(e.value)}}},Lj=class extends An{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=ds.getTensorsInContainer(e.value),n=this.transform(e.value),r=ds.getTensorsInContainer(n);for(let s of t)ds.isTensorInList(s,r)||s.dispose();return{value:n,done:!1}}},Bj=class extends An{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}}}},Nv=class extends An{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=ds.getTensorsInContainer(e.value),n=await this.transform(e.value),r=ds.getTensorsInContainer(n);for(let s of t)ds.isTensorInList(s,r)||s.dispose();return{value:n,done:!1}}},Xx=class extends An{constructor(){super(),this.outputQueue=new Lk,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}}},Wj=class extends Xx{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=ds.getTensorsInContainer(e.value),n=this.transform(e.value),r=ds.getTensorsInContainer(n);this.outputQueue.pushAll(n);for(let s of t)ds.isTensorInList(s,r)||s.dispose();return!0}},Wk=class extends An{constructor(e,t){super(),this.baseErrorHandler=t,this.lastRead=null,this.iterator=null,this.moreIterators=e}summary(){return"TODO: fill in upstream of chained summaries -> Chained"}async next(){return this.lastRead=this.readFromChain(this.lastRead),this.lastRead}async readFromChain(e){if(await e,this.iterator==null){let n=await this.moreIterators.next();if(n.done)return{value:null,done:!0};this.iterator=n.value,this.baseErrorHandler!=null&&(this.iterator=this.iterator.handleErrors(this.baseErrorHandler))}let t=await this.iterator.next();return t.done?(this.iterator=null,this.readFromChain(e)):t}},Vk=(e=>(e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST",e))(Vk||{}),Vj=class extends An{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,n=0;function r(a){return a instanceof An?{value:a.next().then(i=>(t++,i.done&&n++,i.value)),recurse:!1}:{value:null,recurse:!0}}let s=await Ok(this.iterators,r);if(t===n)return{value:null,done:!0};if(n>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:s,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}},Uk=class extends An{constructor(e,t){super(),this.upstream=e,this.bufferSize=t,this.buffer=new Mk(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()}},Uj=class extends Uk{constructor(e,t,n){super(e,t),this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=kj.alea(n||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}}},vc=class{constructor(){this.size=null}batch(e,t=!0){let n=this;w.assert(e>0,()=>`batchSize needs to be positive, but it is
|
|
${e}`);let r;return this.size===1/0||this.size==null?r=this.size:t?r=Math.ceil(this.size/e):r=Math.floor(this.size/e),hr(async()=>(await n.iterator()).columnMajorBatch(e,t,jj),r)}concatenate(e){let t=this,n;return this.size===1/0||e.size===1/0?n=1/0:this.size!=null&&e.size!=null?n=this.size+e.size:n=null,hr(async()=>(await t.iterator()).concatenate(await e.iterator()),n)}filter(e){let t=this,n;return this.size===1/0?n=1/0:n=null,hr(async()=>(await t.iterator()).filter(r=>K(()=>e(r))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){let t=this;return hr(async()=>(await t.iterator()).map(n=>K(()=>e(n))),this.size)}mapAsync(e){let t=this;return hr(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 hr(async()=>(await t.iterator()).prefetch(e),this.size)}repeat(e){let t=this,n;return this.size!=null&&e>0?n=this.size*e:e===0?n=0:this.size!=null&&(e===void 0||e<0)?n=1/0:n=null,hr(async()=>{let r=qx(async()=>({value:await t.iterator(),done:!1}));return Rj(r.take(e))},n)}skip(e){let t=this,n;return this.size!=null&&e>=0&&this.size>=e?n=this.size-e:this.size!=null&&(this.size<e||e===void 0||e<0)?n=0:n=null,hr(async()=>(await t.iterator()).skip(e),n)}shuffle(e,t,n=!0){if(e==null||e<0)throw this.size==null?new RangeError("`Dataset.shuffle()` requires bufferSize to be specified."):new RangeError(`\`Dataset.shuffle()\` requires bufferSize to be specified. If your data fits in main memory (for regular JS objects), and/or GPU memory (for \`tf.Tensor\`s), consider setting bufferSize to the dataset size (${this.size} elements)`);let r=this,s=wj.alea(t||w.now().toString());return hr(async()=>{let a=s.int32();return n&&(a+=s.int32()),(await r.iterator()).shuffle(e,a.toString())},this.size)}take(e){let t=this,n;return this.size!=null&&this.size>e?n=e:this.size!=null&&this.size<=e?n=this.size:n=null,hr(async()=>(await t.iterator()).take(e),n)}async toArray(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArray()}async toArrayForTest(){if(this.size===1/0)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArrayForTest()}};vc.MAX_BUFFER_SIZE=1e4;function hr(e,t=null){return new class extends vc{constructor(){super(...arguments),this.size=t}async iterator(){return e()}}}function Gj(e){return hr(async()=>Bk(e),e.length)}function Hj(e){if(!$u(e))throw new Error("The argument to zip() must be an object or array.");let t;if(Array.isArray(e))for(let n=0;n<e.length;n++)t=t==null?e[n].size:Math.min(t,e[n].size);else if(e instanceof Object)for(let n in e)t=t==null?e[n].size:Math.min(t,e[n].size);return hr(async()=>{let n=await Ok(e,r=>{if(r instanceof vc)return{value:r.iterator(),recurse:!1};if($u(r))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return _j(n,1)},t)}function jj(e){if(e===null)return null;let t=e[0];return Cj(t)?{value:qj(e),recurse:!1}:{value:null,recurse:!0}}function qj(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof rt?cn(e):pt(e)}var Gk=class extends vc{constructor(e){super(),this.input=e}async iterator(){return(await this.input.iterator()).decodeUTF8().split(`
|
|
`).map(r=>(r.endsWith("\r")&&(r=r.slice(0,-1)),r))}},Yh='"',bd=Symbol("out"),Ev=Symbol("field"),Jh=Symbol("quote"),lg=Symbol("quoteafterquote"),Rv=Symbol("quoteinquote"),Hk=class extends vc{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 Gk(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((r,s)=>(r[s]=r[s]+1||1,r),{}),n=Object.keys(t).filter(r=>t[r]>1);if(w.assert(n.length===0,()=>"Duplicate column names found: "+n.toString()),this.columnConfigs){for(let r of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(r)===-1)throw new Error('The key "'+r+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){let t=await(await this.base.iterator()).next();if(t.done)throw new Error("No data was found for CSV parsing.");let n=t.value;return this.parseRow(n,!1)}else return null}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(t=>this.makeDataElement(t))}makeDataElement(e){let t=this.parseRow(e),n={},r={};for(let s=0;s<this.fullColumnNames.length;s++){let a=this.fullColumnNames[s],o=this.columnConfigs?this.columnConfigs[a]:null;if(!(this.configuredColumnsOnly&&!o)){let i=t[s],l=null;if(i==="")if(o&&o.default!==void 0)l=o.default;else{if(o&&(o.required||o.isLabel))throw new Error(`Required column ${a} is empty in this line: ${e}`);l=void 0}else{let u=Number(i);if(isNaN(u))o&&o.dtype==="bool"?l=this.getBoolean(i):l=i;else if(!o||!o.dtype)l=u;else switch(o.dtype){case"float32":l=u;break;case"int32":l=Math.floor(u);break;case"bool":l=this.getBoolean(i);break;default:l=u}}o&&o.isLabel?r[a]=l:n[a]=l}}return Object.keys(r).length===0?n:{xs:n,ys:r}}getBoolean(e){return e==="1"||e.toLowerCase()==="true"?1:0}parseRow(e,t=!0){let n=[],r=0,s=e.length,a=bd;for(let o=0;o<s;o++)switch(a){case bd:switch(e.charAt(o)){case Yh:r=o+1,a=Jh;break;case this.delimiter:if(r=o+1,this.delimiter===" "&&this.delimWhitespace)break;n.push(""),a=bd;break;default:a=Ev,r=o;break}break;case Ev:switch(e.charAt(o)){case this.delimiter:n.push(e.substring(r,o)),a=bd,r=o+1;break;default:}break;case Jh:switch(e.charAt(o)){case Yh:a=lg;break;default:}break;case lg:switch(e.charAt(o)){case this.delimiter:n.push(e.substring(r,o-1)),a=bd,r=o+1;break;case Yh:a=Jh;break;default:a=Rv;break}break;case Rv:switch(e.charAt(o)){case Yh:a=Jh;break;default:}break;default:}if(a===lg?n.push(e.substring(r,s-1)):n.push(e.substring(r)),t&&n.length!==this.fullColumnNames.length)throw new Error(`Invalid row in csv file. Should have ${this.fullColumnNames.length} elements in a row, but got ${n}`);return n}},jk=class extends An{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 jk(e);return await t.start(),t}async start(){try{this.stream=await navigator.mediaDevices.getUserMedia({audio:this.audioTrackConstraints==null?!0:this.audioTrackConstraints,video:!1})}catch(n){throw new Error(`Error thrown while initializing video stream: ${n.message}`)}if(!this.stream)throw new Error("Could not obtain audio from microphone.");let e=window.AudioContext||window.webkitAudioContext;if(this.audioContext=new e,!this.sampleRateHz)this.sampleRateHz=this.audioContext.sampleRate;else if(this.audioContext.sampleRate!==this.sampleRateHz)throw new Error(`Mismatch in sampling rate: Expected: ${this.sampleRateHz}; Actual: ${this.audioContext.sampleRate}`);let t=this.audioContext.createMediaStreamSource(this.stream);this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=this.fftSize*2,this.analyser.smoothingTimeConstant=this.smoothingTimeConstant,t.connect(this.analyser),this.freqData=new Float32Array(this.fftSize),this.timeData=new Float32Array(this.fftSize)}async next(){if(this.isClosed)return{value:null,done:!0};let e,t,n=await this.getAudioData();if(this.includeSpectrogram){let r=this.flattenQueue(n.freqDataQueue);e=this.getTensorFromAudioDataArray(r,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){let r=this.flattenQueue(n.timeDataQueue);t=this.getTensorFromAudioDataArray(r,[this.numFrames*this.fftSize,1])}return{value:{spectrogram:e,waveform:t},done:!1}}async capture(){return(await this.next()).value}async getAudioData(){let e=[],t=[],n=0;return new Promise(r=>{let s=setInterval(()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-1/0&&r({freqDataQueue:e,timeDataQueue:t}),e.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),t.push(this.timeData.slice())),++n===this.numFrames&&(clearInterval(s),r({freqDataQueue:e,timeDataQueue:t}))},this.fftSize/this.sampleRateHz*1e3)})}stop(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),this.stream!=null&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())}toArray(){throw new Error("Can not convert infinite audio stream to array.")}getSampleRate(){return this.sampleRateHz}flattenQueue(e){let t=e[0].length,n=new Float32Array(e.length*t);return e.forEach((r,s)=>n.set(r,s*t)),n}getTensorFromAudioDataArray(e,t){let n=new Float32Array(w.sizeFromShape(t));return n.set(e,n.length-e.length),pt(n,t)}},qk=class extends An{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=Ct([0],"int32"),this.webcamConfig.centerCrop){let n=this.webcamConfig.resizeWidth*1/this.webcamVideoElement.width,r=this.webcamConfig.resizeHeight*1/this.webcamVideoElement.height,s=(1-n)/2,a=(1-r)/2,o=s+n,i=r+a;this.cropBox=ps([a,s,i,o],[1,4])}else this.cropBox=ps([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 n=new qk(e,t);return await n.start(),n}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=Mr.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=Kt(ge(e,"float32"),0),n;n=Se.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");let r=n.shape;return H(n,r.slice(1))})}async capture(){return(await this.next()).value}stop(){this.stream.getTracks().forEach(t=>t.stop());try{this.webcamVideoElement.srcObject=null}catch(t){console.log(t),this.webcamVideoElement.src=null}this.isClosed=!0}toArray(){throw new Error("Can not convert infinite video stream to array.")}},Xk=class{},Kk=class extends An{split(e){return new Xj(this,e)}},Xj=class extends Kk{constructor(e,t){super(),this.upstream=e,this.impl=new Kj(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},Kj=class extends Xx{constructor(e,t){super(),this.upstream=e,this.separator=t,this.carryover=""}summary(){return`${this.upstream.summary()} -> Split('${this.separator}')`}async pump(){let e=await this.upstream.next();if(e.done)return this.carryover===""?!1:(this.outputQueue.push(this.carryover),this.carryover="",!0);let t=e.value.split(this.separator);t[0]=this.carryover+t[0];for(let n of t.slice(0,-1))this.outputQueue.push(n);return this.carryover=t[t.length-1],!0}},Zj=class extends An{decodeUTF8(){return new Yj(this)}},Yj=class extends Kk{constructor(e){super(),this.upstream=e,this.impl=new Jj(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},Jj=class extends Xx{constructor(e){if(super(),this.upstream=e,Y().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{let{StringDecoder:t}=b4();this.decoder=new t("utf8")}}summary(){return`${this.upstream.summary()} -> Utf8`}async pump(){let e=await this.upstream.next(),t;if(e.done)return!1;t=e.value;let n;return Y().get("IS_BROWSER")?n=this.decoder.decode(t,{stream:!0}):n=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(n),!0}},Zk=class extends Zj{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((t,n)=>{let r=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)t(new Uint8Array(this.file.slice(this.offset,r)));else{let s=new FileReader;s.onload=o=>{let i=s.result;if(i instanceof ArrayBuffer&&(i=new Uint8Array(i)),!(i instanceof Uint8Array))return n(new TypeError("FileReader returned unknown type."));t(i)},s.onabort=o=>n(new Error("Aborted")),s.onerror=o=>n(new Error(o.type));let a=this.file.slice(this.offset,r);s.readAsArrayBuffer(a)}this.offset=r}),done:!1}}};async function Qj(e,t={},n){let r,s;typeof e=="string"?r=e:(r=e.url,s=eq(e));let a=await(n||w.fetch)(r,s);if(a.ok){let o=new Uint8Array(await a.arrayBuffer());return new Zk(o,t)}else throw new Error(a.statusText)}var eq=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 Yk(e){return typeof e=="string"&&e.slice(0,7)==="file://"}var Jk=class extends Xk{constructor(e,t={}){super(),this.input=e,this.options=t}async iterator(){if(Yk(this.input)&&Y().get("IS_NODE")){let e=dy();this.input=e.readFileSync(this.input.slice(7))}return new Zk(this.input,this.options)}},Qk=class extends Xk{constructor(e,t={}){super(),this.url=e,this.fileOptions=t}async iterator(){return Yk(this.url)?new Jk(this.url,this.fileOptions).iterator():Qj(this.url,this.fileOptions)}};function tq(e,t={}){return new Hk(new Qk(e),t)}function nq(e){let t=qx(e);return hr(async()=>t)}function rq(e){return hr(async()=>{let t=await e();return qx(()=>t.next())})}async function sq(e,t){return qk.create(e,t)}async function aq(e){return jk.create(e)}var oq="0.0.0";function Ce(e,t){Array.isArray(e)||(e=[e]),e.forEach(n=>{n!=null&&w.assert(n.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the CPU backend.`)})}var iq=Kr.whereImpl,eS=class extends Ou{constructor(){super(),this.blockSize=48,this.firstUse=!0,this.data=new Zd(this,sn())}nextDataId(){return eS.nextDataId++}write(e,t,n){this.firstUse&&(this.firstUse=!1,Y().get("IS_NODE")&&C.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 r={id:this.nextDataId()};return this.data.set(r,{values:e,dtype:n,refCount:1}),r}makeTensorInfo(e,t,n){let r;if(t==="string"&&n!=null&&n.length>0&&w.isString(n[0])){let s=n.map(a=>w.encodeString(a));r=this.write(s,e,t)}else r=this.write(n,e,t);return{dataId:r,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){let t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){let t=this.data.get(e);t.refCount--}}move(e,t,n,r,s){this.data.set(e,{values:t,dtype:r,refCount:s})}numDataIds(){return this.data.numDataIds()}async read(e){return this.readSync(e)}readSync(e){let{dtype:t,complexTensorInfos:n}=this.data.get(e);if(t==="complex64"){let r=this.readSync(n.real.dataId),s=this.readSync(n.imag.dataId);return C.mergeRealAndImagArrays(r,s)}return this.data.get(e).values}bufferSync(e){let t=this.readSync(e.dataId),n=t;if(e.dtype==="string")try{n=t.map(r=>w.decodeString(r))}catch(r){throw new Error("Failed to decode encoded string bytes into utf-8")}return We(e.shape,e.dtype,n)}makeOutput(e,t,n){let r=this.write(e,t,n);return sn().makeTensorFromDataId(r,t,n,this)}disposeData(e,t=!1){if(this.data.has(e)){if(this.data.get(e).refCount--,!t&&this.data.get(e).refCount>0)return!1;let{complexTensorInfos:n}=this.data.get(e);n!=null&&(this.disposeData(n.real.dataId,!0),this.disposeData(n.imag.dataId,!0)),this.data.delete(e)}return!0}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}async time(e){let t=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){Ce([e],"where");let t=this.readSync(e.dataId);return iq(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}},Kx=eS;Kx.nextDataId=0;var x0={};Le(x0,{addImpl:()=>nS,bincountImpl:()=>Yx,bincountReduceImpl:()=>rS,ceilImpl:()=>sS,concatImpl:()=>Jx,equalImpl:()=>aS,expImpl:()=>iS,expm1Impl:()=>uS,floorImpl:()=>cS,gatherNdImpl:()=>dS,gatherV2Impl:()=>pS,greaterEqualImpl:()=>fS,greaterImpl:()=>hS,lessEqualImpl:()=>gS,lessImpl:()=>mS,linSpaceImpl:()=>yS,logImpl:()=>AS,maxImpl:()=>xS,maximumImpl:()=>bS,minimumImpl:()=>vS,multiplyImpl:()=>Qx,negImpl:()=>wS,notEqualImpl:()=>kS,prodImpl:()=>SS,rangeImpl:()=>t3,rsqrtImpl:()=>IS,sigmoidImpl:()=>Kq,simpleAbsImpl:()=>tS,sliceImpl:()=>Bf,sparseFillEmptyRowsImpl:()=>TS,sparseReshapeImpl:()=>NS,sparseSegmentReductionImpl:()=>n3,sqrtImpl:()=>Jq,squaredDifferenceImpl:()=>ES,stridedSliceImpl:()=>RS,stringNGramsImpl:()=>_S,stringSplitImpl:()=>$S,stringToHashBucketFastImpl:()=>DS,subImpl:()=>PS,tileImpl:()=>FS,topKImpl:()=>MS,transposeImpl:()=>e3,uniqueImpl:()=>zS});function tS(e){let t=new Float32Array(e.length);for(let n=0;n<e.length;++n)t[n]=Math.abs(e[n]);return t}var lq=e=>{let{x:t}=e.inputs,n=e.backend;Ce(t,"abs");let r=new Float32Array(w.sizeFromShape(t.shape)),s=n.data.get(t.dataId).values;return r=tS(s),n.makeOutput(r,t.shape,t.dtype)},uq={kernelName:Gi,backendName:"cpu",kernelFunc:lq};function Qt(e){return(t,n,r,s,a)=>{let o=C.assertAndGetBroadcastShape(t,n),i=o.length,l=w.computeStrides(o),u=w.sizeFromShape(o),c=w.getTypedArrayFromDType(a,u),p=t.length,d=n.length,h=w.computeStrides(t),f=w.computeStrides(n),m=C.getBroadcastDims(t,o),g=C.getBroadcastDims(n,o);if(m.length+g.length===0)for(let y=0;y<c.length;++y)c[y]=e(r[y%r.length],s[y%s.length]);else for(let y=0;y<c.length;++y){let x=w.indexToLoc(y,i,l),A=x.slice(-p);m.forEach(I=>A[I]=0);let b=w.locToIndex(A,p,h),v=x.slice(-d);g.forEach(I=>v[I]=0);let S=w.locToIndex(v,d,f);c[y]=e(r[b],s[S])}return[c,o]}}function mr(e){let{inputs:t,backend:n}=e,{real:r,imag:s}=t,a=n.data.get(r.dataId).values,o=n.data.get(s.dataId).values,i=n.makeTensorInfo(r.shape,"complex64"),l=n.data.get(i.dataId);return l.complexTensorInfos={real:n.makeTensorInfo(r.shape,"float32",a),imag:n.makeTensorInfo(s.shape,"float32",o)},i}var cq={kernelName:Jd,backendName:"cpu",kernelFunc:mr};function Lf(e,t,n="float32"){if(n==="complex64"){let s=Lf(e,t,"float32"),a=Lf(e,t,"float32");return mr({inputs:{real:s,imag:a},backend:e})}let r=w.makeZerosTypedArray(w.sizeFromShape(t),n);return e.makeTensorInfo(t,n,r)}function Ps(e){let{inputs:t,backend:n}=e,{x:r}=t;return n.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}var dq={kernelName:go,backendName:"cpu",kernelFunc:Ps};function Mi(e){let{inputs:t,backend:n}=e,{input:r}=t,s=n.data.get(r.dataId).complexTensorInfos.real,a=n.data.get(s.dataId).values;return n.makeTensorInfo(s.shape,s.dtype,a)}var pq={kernelName:ip,backendName:"cpu",kernelFunc:Mi};function qa(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dtype:a}=r;if(a==="complex64"){if(s.dtype==="complex64")return Ps({inputs:{x:s},backend:n});let o=Lf(n,s.shape,s.dtype),i=qa({inputs:{x:s},backend:n,attrs:{dtype:"float32"}}),l=mr({inputs:{real:i,imag:o},backend:n});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),l}if(s.dtype==="complex64"){let o=Mi({inputs:{input:s},backend:n}),i=qa({inputs:{x:o},backend:n,attrs:{dtype:a}});return n.disposeIntermediateTensorInfo(o),i}if(!w.hasEncodingLoss(s.dtype,a)){let o=Ps({inputs:{x:s},backend:n});return{dataId:o.dataId,shape:o.shape,dtype:a}}if(a==="int32"){let o=n.data.get(s.dataId).values,i=Int32Array.from(o);return n.makeTensorInfo(s.shape,"int32",i)}if(a==="bool"){let o=n.data.get(s.dataId).values,i=w.toTypedArray([0],s.dtype),[l,u]=Qt((c,p)=>c!==p?1:0)(s.shape,[],o,i,"bool");return n.makeTensorInfo(u,"bool",l)}throw new Error(`Error in Cast: failed to cast ${s.dtype} to ${a}`)}var hq={kernelName:eo,backendName:"cpu",kernelFunc:qa};function xn(e,t,n,r){return n==null?({inputs:s,backend:a})=>{let{a:o,b:i}=s,l=a;Ce([o,i],e);let u=l.data.get(o.dataId).values,c=l.data.get(i.dataId).values,p=o.dtype==="string"?C.fromUint8ToStringArray(u):u,d=o.dtype==="string"?C.fromUint8ToStringArray(c):c,h=r||o.dtype,[f,m]=t(o.shape,i.shape,p,d,h);return l.makeTensorInfo(m,h,f)}:({inputs:s,backend:a})=>{let{a:o,b:i}=s,l=a;if(o.dtype==="complex64"||i.dtype==="complex64"){let u=qa({inputs:{x:o},backend:l,attrs:{dtype:"complex64"}}),c=l.data.get(u.dataId),p=c.complexTensorInfos.real,d=c.complexTensorInfos.imag,h=l.data.get(p.dataId).values,f=l.data.get(d.dataId).values,m=qa({inputs:{x:i},backend:l,attrs:{dtype:"complex64"}}),g=l.data.get(m.dataId),y=g.complexTensorInfos.real,x=g.complexTensorInfos.imag,A=l.data.get(y.dataId).values,b=l.data.get(x.dataId).values,[v,S,I]=n(o.shape,i.shape,h,f,A,b),E=l.makeTensorInfo(I,"float32",v),R=l.makeTensorInfo(I,"float32",S),P=mr({inputs:{real:E,imag:R},backend:l});return l.disposeIntermediateTensorInfo(u),l.disposeIntermediateTensorInfo(m),l.disposeIntermediateTensorInfo(E),l.disposeIntermediateTensorInfo(R),P}else{let u=l.data.get(o.dataId).values,c=l.data.get(i.dataId).values,p=r||o.dtype,[d,h]=t(o.shape,i.shape,u,c,p);return l.makeTensorInfo(h,p,d)}}}function Zx(e){return(t,n,r,s,a,o)=>{let i=C.assertAndGetBroadcastShape(t,n),l=w.sizeFromShape(i),u=i.length,c=w.computeStrides(i),p=w.getTypedArrayFromDType("float32",l),d=w.getTypedArrayFromDType("float32",l),h=C.getBroadcastDims(t,i),f=C.getBroadcastDims(n,i),m=C.mergeRealAndImagArrays(r,s),g=C.mergeRealAndImagArrays(a,o),y=t.length,x=w.computeStrides(t),A=n.length,b=w.computeStrides(n);if(h.length+f.length===0)for(let v=0;v<p.length;v++){let S=v%m.length,I=v%g.length,E=e(m[S*2],m[S*2+1],g[I*2],g[I*2+1]);p[v]=E.real,d[v]=E.imag}else for(let v=0;v<p.length;v++){let S=w.indexToLoc(v,u,c),I=S.slice(-y);h.forEach(D=>I[D]=0);let E=w.locToIndex(I,y,x),R=S.slice(-A);f.forEach(D=>R[D]=0);let P=w.locToIndex(R,A,b),_=e(m[E*2],m[E*2+1],g[P*2],g[P*2+1]);p[v]=_.real,d[v]=_.imag}return[p,d,i]}}var nS=Qt((e,t)=>e+t),fq=Zx((e,t,n,r)=>({real:e+n,imag:t+r})),Op=xn(ea,nS,fq),mq={kernelName:ea,backendName:"cpu",kernelFunc:Op};function Yx(e,t,n,r,s){let a=w.sizeFromShape(r),o=w.makeZerosTypedArray(s,n);for(let i=0;i<e.length;i++){let l=e[i];if(l<0)throw new Error("Input x must be non-negative!");l>=s||(a>0?o[l]+=t[i]:o[l]+=1)}return o}function rS(e,t,n,r=!1){let s=e.shape[0],a=e.shape[1],o=We([s,n],t.dtype);for(let i=0;i<s;i++)for(let l=0;l<a;l++){let u=e.get(i,l);if(u<0)throw new Error("Input x must be non-negative!");u>=n||(r?o.set(1,i,u):t.size>0?o.set(o.get(i,u)+t.get(i,l),i,u):o.set(o.get(i,u)+1,i,u))}return o}function qo(e){return(t,n,r)=>{let s=w.getTypedArrayFromDType(n,t.length);for(let a=0;a<t.length;++a)s[a]=e(t[a],r);return s}}function gt(e,t,n){return({inputs:r,attrs:s,backend:a})=>{let{x:o}=r;if(Ce(o,e),o.dtype==="string"||n==="string")throw new Error("unaryKernelFunc does not support string input/output");let i=a,l=i.data.get(o.dataId).values,u=w.sizeFromShape(o.shape),c=n||o.dtype,p=w.getArrayFromDType(c,u);for(let d=0;d<u;++d)p[d]=t(l[d],s);return i.makeTensorInfo(o.shape,c,p)}}function wc(e,t,n){return({inputs:r,attrs:s,backend:a})=>{let{x:o}=r;if(Ce(o,e),o.dtype==="string"||n==="string")throw new Error("unaryKernelFunc does not support string input/output");let i=a,l=i.data.get(o.dataId).values,u=n||o.dtype,c=t(l,u,s);return i.makeTensorInfo(o.shape,u,c)}}var sS=qo(e=>Math.ceil(e)),gq=wc(to,sS),yq={kernelName:to,backendName:"cpu",kernelFunc:gq};function Jx(e,t,n,r){let s=w.getArrayFromDType(n,w.sizeFromShape(t));if(r&&n!=="string"){let a=0;e.forEach(o=>{let i=w.sizeFromShape(o.shape);s.set(o.vals,a),a+=i})}else{let a=0;e.forEach(o=>{let i=n==="string"?C.fromUint8ToStringArray(o.vals):o.vals,l=0;for(let u=0;u<o.shape[0];++u){let c=u*t[1]+a;for(let p=0;p<o.shape[1];++p)s[c+p]=i[l++]}a+=o.shape[1]})}return s}var aS=Qt((e,t)=>e===t?1:0),oS=xn(Zi,aS,null,"bool"),Aq={kernelName:Zi,backendName:"cpu",kernelFunc:oS},iS=qo(e=>Math.exp(e)),lS=wc(co,iS,"float32"),xq={kernelName:co,backendName:"cpu",kernelFunc:lS},uS=qo(e=>Math.expm1(e)),bq=wc(Ji,uS),vq={kernelName:Ji,backendName:"cpu",kernelFunc:bq},cS=qo(e=>Math.floor(e)),wq=wc(po,cS),kq={kernelName:po,backendName:"cpu",kernelFunc:wq};function dS(e,t,n,r,s,a,o,i,l){let u=We([r,a],n);for(let c=0;c<r;c++){let p=[],d=0;for(let h=0;h<s;h++){let f=e[c*s+h];d+=f*o[h],p.push(f)}if(d<0||d>=l/a)throw new Error(`Invalid indices: ${p} does not index into ${i}`);for(let h=0;h<a;h++)u.values[c*a+h]=t.get(...t.indexToLoc(d*a+h))}return u}function pS(e,t,n){let r=We(n,e.dtype);for(let s=0;s<r.size;++s){let o=r.indexToLoc(s).slice(),i=o[0],l=o[2],u=t.locToIndex([i,l]);o[2]=t.values[u];let c=e.locToIndex(o);0<=c&&c<e.values.length&&(r.values[s]=e.values[c])}return r}var hS=Qt((e,t)=>e>t?1:0),Sq=xn(nl,hS,null,"bool"),Iq={kernelName:nl,backendName:"cpu",kernelFunc:Sq},fS=Qt((e,t)=>e>=t?1:0),Cq=xn(mo,fS,null,"bool"),Tq={kernelName:mo,backendName:"cpu",kernelFunc:Cq},mS=Qt((e,t)=>e<t?1:0),Nq=xn(rl,mS,null,"bool"),Eq={kernelName:rl,backendName:"cpu",kernelFunc:Nq},gS=Qt((e,t)=>e<=t?1:0),Rq=xn(sl,gS,null,"bool"),_q={kernelName:sl,backendName:"cpu",kernelFunc:Rq};function yS(e,t,n){let r=(t-e)/(n-1),s=w.makeZerosTypedArray(n,"float32");s[0]=e;for(let a=1;a<s.length;a++)s[a]=s[a-1]+r;return s}var AS=qo(e=>Math.log(e)),$q=wc(Ao,AS),Dq={kernelName:Ao,backendName:"cpu",kernelFunc:$q};function xS(e,t,n,r){let s=w.getTypedArrayFromDType(r,w.sizeFromShape(n));for(let a=0;a<s.length;++a){let o=a*t,i=e[o];for(let l=0;l<t;++l){let u=e[o+l];(Number.isNaN(u)||u>i)&&(i=u)}s[a]=i}return s}var bS=Qt((e,t)=>Math.max(e,t)),Pq=xn(bo,bS),Fq={kernelName:bo,backendName:"cpu",kernelFunc:Pq},vS=Qt((e,t)=>Math.min(e,t)),Oq=xn(So,vS),Mq={kernelName:So,backendName:"cpu",kernelFunc:Oq},Qx=Qt((e,t)=>e*t),zq=Zx((e,t,n,r)=>({real:e*n-t*r,imag:e*r+t*n})),b0=xn(Co,Qx,zq),Lq={kernelName:Co,backendName:"cpu",kernelFunc:b0};function wS(e,t,n){let r=w.createScalarValue(-1,n);return Qx([],t,r,e,n)}function Bq(e){let{inputs:t,backend:n}=e,{x:r}=t;Ce(r,"neg");let s=n.data.get(r.dataId).values,[a,o]=wS(s,r.shape,r.dtype);return n.makeTensorInfo(o,r.dtype,a)}var Wq={kernelName:ol,backendName:"cpu",kernelFunc:Bq},kS=Qt((e,t)=>e!==t?1:0),Vq=xn(il,kS,null,"bool"),Uq={kernelName:il,backendName:"cpu",kernelFunc:Vq};function e3(e,t,n,r,s){let a=t.length,o=w.sizeFromShape(t),i=w.computeStrides(t),l=w.computeStrides(s),u=w.getTypedArrayFromDType(n,w.sizeFromShape(s));for(let c=0;c<o;++c){let p=w.indexToLoc(c,a,i),d=new Array(p.length);for(let f=0;f<d.length;f++)d[f]=p[r[f]];let h=w.locToIndex(d,a,l);u[h]=e[c]}return u}function ar(e){let{inputs:t,attrs:n,backend:r}=e,{x:s}=t,{perm:a}=n;Ce(s,"transpose");let o=s.shape.length,i=new Array(o);for(let p=0;p<i.length;p++)i[p]=s.shape[a[p]];let l=r.data.get(s.dataId).values,u=e3(l,s.shape,s.dtype,a,i);return{dataId:r.write(u,i,s.dtype),shape:i,dtype:s.dtype}}var Gq={kernelName:Uo,backendName:"cpu",kernelFunc:ar};function SS(e,t,n,r){let[s,a]=C.computeOutAndReduceShapes(e,r),o=Nn(t,"int32"),i=w.makeZerosTypedArray(w.sizeFromShape(s),o),l=w.sizeFromShape(a);for(let u=0;u<i.length;++u){let c=u*l,p=1;for(let d=0;d<l;++d)p*=n[c+d];i[u]=p}return{outVals:i,outShape:s,outDtype:o}}function Hq(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r;Ce(s,"prod");let i=s.shape.length,l=w.parseAxisParam(a,s.shape),u=C.getAxesPermutation(l,i),c=l,p=s,d=[];u!=null&&(p=ar({inputs:{x:s},backend:n,attrs:{perm:u}}),d.push(p),c=C.getInnerMostAxes(c.length,i));let h=n.data.get(p.dataId).values,{outVals:f,outShape:m,outDtype:g}=SS(p.shape,p.dtype,h,c),y=m;return o&&(y=C.expandShapeToKeepDim(m,l)),d.forEach(x=>n.disposeIntermediateTensorInfo(x)),n.makeTensorInfo(y,g,f)}var jq={kernelName:Ro,backendName:"cpu",kernelFunc:Hq};function t3(e,t,n,r){let s=e===t,a=e<t&&n<0,o=t<e&&n>1;if(s||a||o)return w.makeZerosTypedArray(0,r);let i=Math.abs(Math.ceil((t-e)/n)),l=w.makeZerosTypedArray(i,r);t<e&&n===1&&(n=-1),l[0]=e;for(let u=1;u<l.length;u++)l[u]=l[u-1]+n;return l}var IS=qo(e=>1/Math.sqrt(e)),qq=wc(Po,IS),Xq={kernelName:Po,backendName:"cpu",kernelFunc:qq},Kq=qo(e=>1/(1+Math.exp(-e))),CS=gt(Oo,e=>1/(1+Math.exp(-e))),Zq={kernelName:Oo,backendName:"cpu",kernelFunc:CS};function Bf(e,t,n,r,s){let a=Mt.isSliceContinous(r,t,n),o=w.sizeFromShape(n),i=w.computeStrides(r);if(a){let p=Mt.computeFlatOffset(t,i);return s==="string"?e.slice(p,p+o):e.subarray(p,p+o)}let l=s==="string"?C.fromUint8ToStringArray(e):e,u=We(r,s,l),c=We(n,s);for(let p=0;p<c.size;++p){let d=c.indexToLoc(p),h=d.map((f,m)=>f+t[m]);c.set(u.get(...h),...d)}return s==="string"?C.fromStringArrayToUint8(c.values):c.values}function zi(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,size:o}=r;Ce(s,"slice");let[i,l]=Mt.parseSliceParams(s,a,o);Mt.assertParamsValid(s,i,l);let u=n.data.get(s.dataId).values,c=Bf(u,i,l,s.shape,s.dtype);return n.makeTensorInfo(l,s.dtype,c)}var Yq={kernelName:Al,backendName:"cpu",kernelFunc:zi};function TS(e,t,n,r,s,a,o){let i=t[0],l=a[0],u=new Array(l),c=new Array(i),p=t[1];if(l===0){if(i!==0)throw new Error(C.getSparseFillEmptyRowsIndicesDenseShapeMismatch(i));let g=w.getArrayFromDType(n,0),y=w.getArrayFromDType(s,0);return[g,[0,p],y,u,c]}let d=!0,h=0,f=new Array(l).fill(0);for(let g=0;g<i;++g){let y=e[g*p];if(y<0)throw new Error(C.getSparseFillEmptyRowsNegativeIndexErrorMessage(g,y));if(y>=l)throw new Error(C.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(g,y,l));++f[y],d=d&&y>=h,h=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&&d){let g=e,y=r;for(let x=0;x<i;++x)c[x]=x;return[g,[i,p],y,u,c]}else{let g=f[l-1],y=w.getArrayFromDType(n,g*p),x=w.getArrayFromDType(s,g),A=new Array(l).fill(0);for(let b=0;b<i;++b){let v=e[b*p],S=A[v],I=(v===0?0:f[v-1])+S;A[v]++;for(let E=0;E<p;++E)y[I*p+E]=e[b*p+E];x[I]=r[b],c[b]=I}for(let b=0;b<l;++b)if(A[b]===0){let S=b===0?0:f[b-1];y[S*p+0]=b;for(let I=1;I<p;++I)y[S*p+I]=0;x[S]=o}return[y,[g,p],x,u,c]}}function NS(e,t,n,r,s){let a=w.sizeFromShape(r),o=t[0],i=s.length,l=[],u=1,c=-1;for(let g=0;g<i;++g){let y=s[g];if(y===-1){if(c!==-1)throw new Error(C.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(c,g));c=g,l.push(1)}else{if(y<0)throw new Error(C.getSparseReshapeNegativeOutputDimErrorMessage(g,y));u*=y,l.push(y)}}if(c!==-1){if(u<=0)throw new Error(C.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage());let g=Math.trunc(a/u);if(u*g!==a)throw new Error(C.getSparseReshapeInputOutputMultipleErrorMessage(r,l));l[c]=g}if(w.sizeFromShape(l)!==a)throw new Error(C.getSparseReshapeInputOutputMismatchErrorMessage(r,l));let d=r.length,h=[];if(d>0){h[d-1]=1;for(let g=d-2;g>=0;--g)h[g]=h[g+1]*r[g+1]}let f=[];if(i>0){f[i-1]=1;for(let g=i-2;g>=0;--g)f[g]=f[g+1]*l[g+1]}let m=w.getArrayFromDType(n,o*i);for(let g=0;g<o;++g){let y=0;for(let x=0;x<d;++x)y+=e[g*d+x]*h[x];for(let x=0;x<i;++x)m[g*i+x]=Math.trunc(y/f[x]),y%=f[x]}return[m,[o,i],l]}function n3(e,t,n,r,s,a=!1,o=0){let i=r.length,l=[t[0],e.length/t[0]],u=l[1],p=i>0?s[i-1]+1:0;if(p<0)throw new Error(C.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let d=t.slice();d[0]=p;let h=d.reduce((A,b)=>A*b,1),f=w.getArrayFromDType(n,h);if(i===0)return p>0&&f.fill(o),[f,d];if(p<=0)throw new Error(C.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let m=0,g=1,y=0,x=s[m];for(;;){let A=0;if(g<i){if(A=s[g],x===A){++g;continue}if(x>=A)throw new Error(C.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage())}if(x<0||x>=p)throw new Error(C.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(x,p));x>y&&f.fill(o,y*u,x*u);for(let b=m;b<g;++b){let v=r[b];if(v<0||v>=l[0])throw new Error(C.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(b,r[b],l[0]));for(let S=0;S<u;S++)f[x*u+S]+=e[v*u+S]}if(a)for(let b=0;b<u;b++)f[x*u+b]/=g-m;if(m=g,++g,y=x+1,x=A,g>i)break}return y<p&&f.fill(o,y*u,p*u),[f,d]}var Jq=qo(e=>Math.sqrt(e)),Qq=gt(Mo,e=>Math.sqrt(e)),eX={kernelName:Mo,backendName:"cpu",kernelFunc:Qq},ES=Qt((e,t)=>{let n=e-t;return n*n}),tX=xn(Bo,ES),nX={kernelName:Bo,backendName:"cpu",kernelFunc:tX};function RS(e,t,n,r){let s=We(e,t.dtype);for(let a=0;a<s.size;a++){let o=s.indexToLoc(a),i=new Array(o.length);for(let l=0;l<i.length;l++)i[l]=o[l]*n[l]+r[l];s.set(t.get(...i),...o)}return s}var rX=class{constructor(e,t,n,r,s,a){this.separator=w.encodeString(e),this.nGramWidths=t,this.leftPad=w.encodeString(n),this.rightPad=w.encodeString(r),this.padWidth=s,this.preserveShort=a}getPadWidth(e){return Math.min(this.padWidth<0?e-1:this.padWidth,e-1)}getNumNGrams(e,t){let n=this.getPadWidth(t);return Math.max(0,e+2*n-t+1)}createNGrams(e,t,n,r,s,a){for(let o=0;o<s;++o){let i=this.getPadWidth(a),l=Math.max(0,i-o),u=Math.max(0,i-(s-(o+1))),c=a-(l+u),p=t+(l>0?0:o-i),d=0;d+=l*this.leftPad.length;for(let y=0;y<c;++y)d+=e[p+y].length;d+=u*this.rightPad.length,d+=(l+u+c-1)*this.separator.length,n[r+o]=new Uint8Array(d);let f=n[r+o],m=0,g=y=>y.forEach(x=>f[m++]=x);for(let y=0;y<l;++y)g(this.leftPad),g(this.separator);for(let y=0;y<c-1;++y)g(e[p+y]),g(this.separator);if(c>0){g(e[p+c-1]);for(let y=0;y<u;++y)g(this.separator),g(this.rightPad)}else{for(let y=0;y<u-1;++y)g(this.rightPad),g(this.separator);g(this.rightPad)}}}compute(e,t){let n=e.length,r=t.length;if(r>0){let i=t[0];if(i!==0)throw new Error(`First split value must be 0, got ${i}`);for(let l=1;l<r;++l){let u=t[l]>=i;if(u=u&&t[l]<=n,!u)throw new Error(`Invalid split value ${t[l]}, must be in [${i}, ${n}]`);i=t[l]}if(i!==n)throw new Error(`Last split value must be data size. Expected ${n}, got ${i}`)}let s=r-1,a=w.getArrayFromDType("int32",r);if(n===0||r===0){let i=new Array(n);for(let l=0;l<=s;++l)a[l]=0;return[i,a]}a[0]=0;for(let i=1;i<=s;++i){let l=t[i]-t[i-1],u=0;this.nGramWidths.forEach(c=>{u+=this.getNumNGrams(l,c)}),this.preserveShort&&l>0&&u===0&&(u=1),a[i]=a[i-1]+u}let o=new Array(a[s]);for(let i=0;i<s;++i){let l=t[i],u=a[i];if(this.nGramWidths.forEach(c=>{let p=t[i+1]-t[i],d=this.getNumNGrams(p,c);this.createNGrams(e,l,o,u,d,c),u+=d}),this.preserveShort&&u===a[i]){let c=t[i+1]-t[i];if(c===0)continue;let p=c+2*this.padWidth,d=1;this.createNGrams(e,l,o,u,d,p)}}return[o,a]}};function _S(e,t,n,r,s,a,o,i){return new rX(n,r,s,a,o,i).compute(e,t)}function sX(e,t,n,r){if(!e.length)return;if(t.length===0){for(let a=0;a<e.length;++a)r.push(e.subarray(a,a+1));return}if(t.length===1){let a=t[0],o=e.indexOf(a);for(;o!==-1;){let i=e.subarray(0,o);(!n||i.length!==0)&&r.push(i),e=e.subarray(o+1),o=e.indexOf(a)}(!n||e.length!==0)&&r.push(e);return}let s=0;for(let a=0;a<e.length+1;a++)if(a===e.length||t.indexOf(e[a])!==-1){let o=e.subarray(s,a);(!n||o.length!==0)&&r.push(o),s=a+1}}function $S(e,t,n){let r=e.length,s=[],a=0,o=0,i=new Array(r);for(let d=0;d<r;++d){let h=s.length;sX(e[d],t,n,s);let f=s.length-h;i[d]=f,a+=f,o=Math.max(o,f)}let l=w.getArrayFromDType("int32",a*2),u=new Array(a),c=[r,o],p=0;for(let d=0;d<r;++d)for(let h=0;h<i[d];++h)l[p*2]=d,l[p*2+1]=h,u[p]=s[p],++p;return[l,u,c]}function DS(e,t){let n=w.getArrayFromDType("int32",e.length);for(let r=0;r<e.length;++r)n[r]=w.fingerPrint64(e[r]).modulo(t).getLowBitsUnsigned();return n}var PS=Qt((e,t)=>e-t),aX=Zx((e,t,n,r)=>({real:e-n,imag:t-r})),r3=xn(Wo,PS,aX),oX={kernelName:Wo,backendName:"cpu",kernelFunc:r3};function FS(e,t){let n=new Array(e.rank);for(let s=0;s<n.length;s++)n[s]=e.shape[s]*t[s];let r=We(n,e.dtype);for(let s=0;s<r.values.length;++s){let a=r.indexToLoc(s),o=new Array(e.rank);for(let l=0;l<o.length;l++)o[l]=a[l]%e.shape[l];let i=e.locToIndex(o);r.values[s]=e.values[i]}return r}var Cd=(e,t)=>{let n=t.value-e.value;return n===0?e.index-t.index:n};function OS(e,t,n=0,r=e.length-1){for(;r>n;){if(r-n>600){let i=r-n+1,l=t-n+1,u=Math.log(i),c=.5*Math.exp(2*u/3),p=.5*Math.sqrt(u*c*(i-c)/i)*Math.sign(l-i/2),d=Math.max(n,Math.floor(t-l*c/i+p)),h=Math.min(r,Math.floor(t+(i-l)*c/i+p));OS(e,t,d,h)}let s=e[t],a=n,o=r;for(w.swap(e,n,t),Cd(e[r],s)>0&&w.swap(e,n,r);a<o;){for(w.swap(e,a,o),a++,o--;Cd(e[a],s)<0;)a=a+1;for(;Cd(e[o],s)>0;)o=o-1}Cd(e[n],s)===0?w.swap(e,n,o):(o=o+1,w.swap(e,o,r)),o<=t&&(n=o+1),t<=o&&(r=o-1)}}function MS(e,t,n,r,s){let a=t[t.length-1],[o,i]=[e.length/a,a],l=w.getTypedArrayFromDType(n,o*r),u=w.getTypedArrayFromDType("int32",o*r);for(let p=0;p<o;p++){let d=p*i,h=e.subarray(d,d+i),f=new Array(h.length);h.forEach((x,A)=>f[A]={value:x,index:A}),r<f.length&&(OS(f,r),f=f.slice(0,r)),s&&f.sort(Cd);let m=p*r,g=l.subarray(m,m+r),y=u.subarray(m,m+r);for(let x=0;x<r;x++)g[x]=f[x].value,y[x]=f[x].index}let c=t.slice();return c[c.length-1]=r,[We(c,n,l),We(c,"int32",u)]}function zS(e,t,n,r){let s=w.parseAxisParam(t,n)[0],a=[1,n[0],1];for(let f=0;f<s;f++)a[0]*=n[f];a[1]=n[s];for(let f=s+1;f<n.length;f++)a[2]*=n[f];let o={},i=new Int32Array(n[s]),l=new on(a,r,e),u=[],c=a[0]===1&&a[2]===1;for(let f=0;f<n[s];f++){let m;if(c)m=e[f].toString();else{let g=[];for(let y=0;y<a[0];y++)for(let x=0;x<a[2];x++)g.push(l.get(y,f,x));m=g.join(",")}if(o[m]!==void 0)i[f]=o[m];else{let g=Object.keys(o).length;o[m]=g,i[f]=g,u.push(f)}}let p=a.slice();p[1]=Object.keys(o).length;let d=new on(p,r);u.forEach((f,m)=>{for(let g=0;g<a[0];g++)for(let y=0;y<a[2];y++)d.set(l.get(g,f,y),g,m,y)});let h=n.slice();return h[s]=p[1],{outputValues:d.values,outputShape:h,indices:i}}var iX="0.0.0";Rl("cpu",()=>new Kx,1);var LS=gt(uo,e=>e>=0?e:Math.exp(e)-1),lX={kernelName:uo,backendName:"cpu",kernelFunc:LS};function BS(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{alpha:a}=r;Ce([s],"leakyRelu");let o=w.sizeFromShape(s.shape),i=n.data.get(s.dataId).values,l=w.getTypedArrayFromDType("float32",o);for(let u=0;u<i.length;u++)l[u]=i[u]<0?a*i[u]:i[u];return n.makeTensorInfo(s.shape,"float32",l)}var uX={kernelName:yo,backendName:"cpu",kernelFunc:BS},cX=Qt((e,t)=>e<0?t*e:e);function WS(e){let{inputs:t,backend:n}=e,{x:r,alpha:s}=t;Ce([r,s],"prelu");let a=n.data.get(r.dataId).values,o=n.data.get(s.dataId).values,[i,l]=cX(r.shape,s.shape,a,o,"float32");return n.makeTensorInfo(l,"float32",i)}var dX={kernelName:Eo,backendName:"cpu",kernelFunc:WS},VS=gt(_o,e=>Math.max(0,e)),pX={kernelName:_o,backendName:"cpu",kernelFunc:VS},US=gt(Do,e=>Math.min(Math.max(0,e),6)),hX={kernelName:Do,backendName:"cpu",kernelFunc:US};function s3(e,t,n,r,s){if(n==="linear")return Ps({inputs:{x:t},backend:e});if(n==="relu")return VS({inputs:{x:t},backend:e});if(n==="elu")return LS({inputs:{x:t},backend:e});if(n==="relu6")return US({inputs:{x:t},backend:e});if(n==="prelu")return WS({inputs:{x:t,alpha:r},backend:e});if(n==="leakyrelu")return BS({inputs:{x:t},backend:e,attrs:{alpha:s}});if(n==="sigmoid")return CS({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}function $t(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{shape:a}=r,o=w.sizeFromShape(s.shape),i=w.inferFromImplicitShape(a,o),l=w.sizeFromShape(i);w.assert(o===l,()=>`The new shape (${i}) has ${l} elements and the old shape (${s.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`),n.incRef(s.dataId);let u=n.data.get(s.dataId);if(u.complexTensorInfos!=null){let c=u.complexTensorInfos.real,p=u.complexTensorInfos.imag;c.shape=i,p.shape=i}return{dataId:s.dataId,shape:i,dtype:s.dtype}}var fX={kernelName:hl,backendName:"cpu",kernelFunc:$t};function GS(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a}=t,{transposeA:o,transposeB:i}=r;Ce([s,a],"matMul");let l=s.shape.length,u=a.shape.length,c=o?s.shape[l-2]:s.shape[l-1],p=i?a.shape[u-1]:a.shape[u-2],d=o?s.shape[l-1]:s.shape[l-2],h=i?a.shape[u-2]:a.shape[u-1],f=s.shape.slice(0,-2),m=a.shape.slice(0,-2),g=w.sizeFromShape(f),y=w.sizeFromShape(m),A=El.assertAndGetBroadcastShape(s.shape.slice(0,-2),a.shape.slice(0,-2)).concat([d,h]);w.assert(c===p,()=>`Error in matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${s.shape} and ${a.shape} and transposeA=${o} and transposeB=${i} must match.`);let b=o?[g,c,d]:[g,d,c],v=i?[y,h,p]:[y,p,h],S=$t({inputs:{x:s},backend:n,attrs:{shape:b}}),I=$t({inputs:{x:a},backend:n,attrs:{shape:v}}),E=o?S.shape[1]:S.shape[2],R=o?S.shape[2]:S.shape[1],P=i?I.shape[1]:I.shape[2],_=Math.max(g,y),D=n.data.get(S.dataId).values,T=n.data.get(I.dataId).values,F=w.computeStrides(S.shape),U=w.computeStrides(I.shape),[X,z,Z]=o?[F[0],1,F[1]]:[F[0],F[1],1],[W,ee,Q]=i?[1,U[1],U[0]]:[U[1],1,U[0]],ae=R*P,J=We([_,R,P],S.dtype),se=J.values,ie=n.blockSize;for(let me=0;me<_;me++)for(let be=0;be<R;be+=ie)for(let Ee=0;Ee<P;Ee+=ie)for(let Re=0;Re<E;Re+=ie){let ze=Math.min(be+ie,R),Be=Math.min(Ee+ie,P),nt=Math.min(Re+ie,E);for(let it=be;it<ze;it++)for(let lt=Ee;lt<Be;lt++){let ft=0;for(let $e=Re;$e<nt;$e++){let wt=Math.min(me,g-1)*X,At=Math.min(me,y-1)*Q,Pn=D[wt+it*z+$e*Z],qt=T[$e*W+lt*ee+At];ft+=Pn*qt}se[me*ae+(it*P+lt)]+=ft}}return n.disposeIntermediateTensorInfo(S),n.disposeIntermediateTensorInfo(I),n.makeTensorInfo(A,J.dtype,J.values)}var mX={kernelName:Qa,backendName:"cpu",kernelFunc:GS};function gX(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a,bias:o,preluActivationWeights:i}=t,{transposeA:l,transposeB:u,activation:c,leakyreluAlpha:p}=r,d,h,f,m=[];d=GS({inputs:{a:s,b:a},attrs:{transposeA:l,transposeB:u},backend:n}),o&&(h=Op({inputs:{a:d,b:o},backend:n}),m.push(d),d=h),c&&(f=s3(n,d,c,i,p),m.push(d),d=f);for(let y of m)n.disposeIntermediateTensorInfo(y);return d}var yX={kernelName:Pa,backendName:"cpu",kernelFunc:gX},AX=gt(zu,e=>Math.acos(e)),xX={kernelName:zu,backendName:"cpu",kernelFunc:AX},bX=gt(Lu,e=>Math.acosh(e)),vX={kernelName:Lu,backendName:"cpu",kernelFunc:bX};function wX(e){let{inputs:t,backend:n}=e,r=t;Ce(t,"addN");let s=r.map(i=>n.data.get(i.dataId).values),a=We(r[0].shape,r[0].dtype),o=a.values;for(let i=0;i<r.length;i++){let l=s[i];for(let u=0;u<o.length;u++)o[u]+=l[u]}return n.makeTensorInfo(a.shape,a.dtype,a.values)}var kX={kernelName:Za,backendName:"cpu",kernelFunc:wX};function SX(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r;Ce(s,"all");let i=w.parseAxisParam(a,s.shape),l=i,u=C.getAxesPermutation(l,s.shape.length),c=s;u!=null&&(c=ar({inputs:{x:s},backend:n,attrs:{perm:u}}),l=C.getInnerMostAxes(l.length,s.shape.length)),C.assertAxesAreInnerMostDims("all",l,c.shape.length);let[p,d]=C.computeOutAndReduceShapes(c.shape,l),h=w.sizeFromShape(d),f=w.makeZerosTypedArray(w.sizeFromShape(p),c.dtype),m=n.data.get(c.dataId).values;for(let y=0;y<f.length;++y){let x=y*h,A=m[x];for(let b=0;b<h;++b){let v=m[x+b];A=A&&v}f[y]=A}u!=null&&n.disposeIntermediateTensorInfo(c);let g=n.makeTensorInfo(p,c.dtype,f);if(o){let y=C.expandShapeToKeepDim(p,i),x=$t({inputs:{x:g},backend:n,attrs:{shape:y}});return n.disposeIntermediateTensorInfo(g),x}return g}var IX={kernelName:Bu,backendName:"cpu",kernelFunc:SX};function CX(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r;Ce(s,"any");let i=w.parseAxisParam(a,s.shape),l=i,u=C.getAxesPermutation(l,s.shape.length),c=s;u!=null&&(c=ar({inputs:{x:s},backend:n,attrs:{perm:u}}),l=C.getInnerMostAxes(l.length,s.shape.length)),C.assertAxesAreInnerMostDims("any",l,c.shape.length);let[p,d]=C.computeOutAndReduceShapes(c.shape,l),h=w.sizeFromShape(d),f=w.makeZerosTypedArray(w.sizeFromShape(p),c.dtype),m=n.data.get(c.dataId).values;for(let y=0;y<f.length;++y){let x=y*h,A=m[x];for(let b=0;b<h;++b){let v=m[x+b];A=A||v}f[y]=A}u!=null&&n.disposeIntermediateTensorInfo(c);let g=n.makeTensorInfo(p,c.dtype,f);if(o){let y=C.expandShapeToKeepDim(p,i),x=$t({inputs:{x:g},backend:n,attrs:{shape:y}});return n.disposeIntermediateTensorInfo(g),x}return g}var TX={kernelName:Wu,backendName:"cpu",kernelFunc:CX};function NX(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r;Ce(s,"argMax");let o=w.parseAxisParam(a,s.shape),i=C.getAxesPermutation(o,s.shape.length),l=s,u=[];i!=null&&(l=ar({inputs:{x:s},backend:n,attrs:{perm:i}}),u.push(l),o=C.getInnerMostAxes(o.length,l.shape.length)),o=[o[0]],C.assertAxesAreInnerMostDims("argMax",o,l.shape.length);let[c,p]=C.computeOutAndReduceShapes(l.shape,o),d=w.sizeFromShape(c),h=w.makeZerosTypedArray(d,"int32"),f=w.sizeFromShape(p),m=n.data.get(l.dataId).values;for(let g=0;g<h.length;++g){let y=g*f,x=m[y],A=0;for(let b=0;b<f;++b){let v=m[y+b];v>x&&(x=v,A=b)}h[g]=A}return u.forEach(g=>n.disposeIntermediateTensorInfo(g)),n.makeTensorInfo(c,"int32",h)}var EX={kernelName:Ya,backendName:"cpu",kernelFunc:NX};function RX(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r;Ce(s,"argMin");let o=w.parseAxisParam(a,s.shape),i=C.getAxesPermutation(o,s.shape.length),l=s,u=[];i!=null&&(l=ar({inputs:{x:s},backend:n,attrs:{perm:i}}),u.push(l),o=C.getInnerMostAxes(o.length,l.shape.length)),o=[o[0]],C.assertAxesAreInnerMostDims("argMin",o,l.shape.length);let[c,p]=C.computeOutAndReduceShapes(l.shape,o),d=w.sizeFromShape(c),h=w.makeZerosTypedArray(d,"int32"),f=w.sizeFromShape(p),m=n.data.get(l.dataId).values;for(let g=0;g<h.length;++g){let y=g*f,x=m[y],A=0;for(let b=0;b<f;++b){let v=m[y+b];v<x&&(x=v,A=b)}h[g]=A}return u.forEach(g=>n.disposeIntermediateTensorInfo(g)),n.makeTensorInfo(c,"int32",h)}var _X={kernelName:Vu,backendName:"cpu",kernelFunc:RX},$X=gt(Uu,e=>Math.asin(e)),DX={kernelName:Uu,backendName:"cpu",kernelFunc:$X},PX=gt(Gu,e=>Math.asinh(e)),FX={kernelName:Gu,backendName:"cpu",kernelFunc:PX},OX=gt(Hu,e=>Math.atan(e)),MX={kernelName:Hu,backendName:"cpu",kernelFunc:OX},zX=Qt((e,t)=>Math.atan2(e,t)),LX=xn(qu,zX),BX={kernelName:qu,backendName:"cpu",kernelFunc:LX},WX=gt(ju,e=>Math.atanh(e)),VX={kernelName:ju,backendName:"cpu",kernelFunc:WX};function a3(e,t,n,r,s,a){let o=s.strideHeight,i=s.strideWidth,l=s.dilationHeight,u=s.dilationWidth,c=s.effectiveFilterHeight,p=s.effectiveFilterWidth,d=s.padInfo.top,h=s.padInfo.left,f=a==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,m=We(s.outShape,n),g=m.values,y=s.outShape[1]*s.outShape[2]*s.outShape[3],x=s.outShape[2]*s.outShape[3],A=s.outShape[3];for(let b=0;b<s.batchSize;++b){let v=b*y,S=b*r[0];for(let I=0;I<s.inChannels;++I)for(let E=0;E<s.outHeight;++E){let R=E*o-d,P=Math.max(0,R),_=Math.min(s.inHeight,c+R),D=v+E*x;for(let T=0;T<s.outWidth;++T){let F=T*i-h,U=Math.max(0,F),X=Math.min(s.inWidth,p+F),z=f,Z=0,W=0;for(let Q=P;Q<_;Q+=l){let ae=S+Q*r[1];for(let J=U;J<X;J+=u){let se=ae+J*r[2],ie=e[se+I];a==="max"&&ie>z?z=ie:a==="avg"&&(Z+=ie,W++)}if(isNaN(z))break}let ee=D+T*A+I;g[ee]=a==="avg"?Z/W:z}}}return m}function HS(e,t,n,r,s=!1,a=!1){let o=We(r.outShape,"int32"),i=r.strideHeight,l=r.strideWidth,u=r.dilationHeight,c=r.dilationWidth,p=r.effectiveFilterHeight,d=r.effectiveFilterWidth,h=r.padInfo.top,f=r.padInfo.left,m=We(t,n,e);for(let g=0;g<r.batchSize;++g)for(let y=0;y<r.inChannels;++y)for(let x=0;x<r.outHeight;++x){let A=x*i-h,b=A;for(;b<0;)b+=u;let v=Math.min(r.inHeight,p+A);for(let S=0;S<r.outWidth;++S){let I=S*l-f,E=I;for(;E<0;)E+=c;let R=Math.min(r.inWidth,d+I),P=Number.NEGATIVE_INFINITY,_=-1;for(let D=b;D<v;D+=u){let T=D-A;for(let F=E;F<R;F+=c){let U=F-I,X=m.get(g,D,F,y);X>P&&(P=X,s?_=a?((g*r.inHeight+D)*r.inWidth+F)*r.inChannels+y:(D*r.inWidth+F)*r.inChannels+y:_=T*d+U)}}o.set(_,g,x,S,y)}}return o}function jS(e,t,n,r,s,a){let o=s.strideDepth,i=s.strideHeight,l=s.strideWidth,u=s.dilationDepth,c=s.dilationHeight,p=s.dilationWidth,d=s.effectiveFilterDepth,h=s.effectiveFilterHeight,f=s.effectiveFilterWidth,m=s.padInfo.front,g=s.padInfo.top,y=s.padInfo.left,x=a==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,A=We(s.outShape,n),b=A.values,v=s.outShape[1]*s.outShape[2]*s.outShape[3]*s.outShape[4],S=s.outShape[2]*s.outShape[3]*s.outShape[4],I=s.outShape[3]*s.outShape[4],E=s.outShape[4];for(let R=0;R<s.batchSize;++R){let P=R*v,_=R*r[0];for(let D=0;D<s.inChannels;++D)for(let T=0;T<s.outDepth;++T){let F=T*o-m,U=F;for(;U<0;)U+=u;let X=Math.min(s.inDepth,d+F),z=P+T*S;for(let Z=0;Z<s.outHeight;++Z){let W=Z*i-g,ee=W;for(;ee<0;)ee+=c;let Q=Math.min(s.inHeight,h+W),ae=z+Z*I;for(let J=0;J<s.outWidth;++J){let se=J*l-y,ie=se;for(;ie<0;)ie+=p;let me=Math.min(s.inWidth,f+se),be=ae+J*E,Ee=x,Re=0,ze=0;for(let nt=U;nt<X;nt+=u){let it=_+nt*r[1];for(let lt=ee;lt<Q;lt+=c){let ft=it+lt*r[2];for(let $e=ie;$e<me;$e+=p){let wt=ft+$e*r[3],At=e[wt+D];if(a==="max"&&At>Ee?Ee=At:a==="avg"&&(Re+=At,ze++),isNaN(Ee))break}if(isNaN(Ee))break}if(isNaN(Ee))break}let Be=be+D;b[Be]=a==="avg"?Re/ze:Ee}}}}return A}function UX(e,t){let n=We(t.outShape,"int32"),r=t.strideDepth,s=t.strideHeight,a=t.strideWidth,o=t.dilationDepth,i=t.dilationHeight,l=t.dilationWidth,u=t.effectiveFilterDepth,c=t.effectiveFilterHeight,p=t.effectiveFilterWidth,d=t.padInfo.front,h=t.padInfo.top,f=t.padInfo.left;for(let m=0;m<t.batchSize;++m)for(let g=0;g<t.inChannels;++g)for(let y=0;y<t.outDepth;++y){let x=y*r-d,A=x;for(;A<0;)A+=o;let b=Math.min(t.inDepth,u+x);for(let v=0;v<t.outHeight;++v){let S=v*s-h,I=S;for(;I<0;)I+=i;let E=Math.min(t.inHeight,c+S);for(let R=0;R<t.outWidth;++R){let P=R*a-f,_=P;for(;_<0;)_+=l;let D=Math.min(t.inWidth,p+P),T=Number.NEGATIVE_INFINITY,F=-1;for(let U=A;U<b;U+=o){let X=U-x;for(let z=I;z<E;z+=i){let Z=z-S;for(let W=_;W<D;W+=l){let ee=W-P,Q=e.get(m,U,z,W,g);Q>=T&&(T=Q,F=X*c*p+Z*c+ee)}}}n.set(F,m,y,v,R,g)}}}return n}function GX(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t;Ce(s,"avgPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=r,u=1;w.assert(C.eitherStridesOrDilationsAreOne(o,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${u}'`);let c=C.computePool2DInfo(s.shape,a,o,u,i,l),p;if(c.filterWidth===1&&c.filterHeight===1&&w.arraysEqual(c.inShape,c.outShape))p=Ps({inputs:{x:s},backend:n});else{let d=n.data.get(s.dataId).values,h=w.computeStrides(s.shape),f=a3(d,s.shape,s.dtype,h,c,"avg");p=n.makeTensorInfo(c.outShape,s.dtype,f.values)}return p}var HX={kernelName:Ja,backendName:"cpu",kernelFunc:GX};function jX(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l,dataFormat:u}=r;Ce(s,"avgPool3d");let c=C.computePool3DInfo(s.shape,a,o,1,i,l,u),p=n.data.get(s.dataId).values,d=jS(p,s.shape,s.dtype,w.computeStrides(s.shape),c,"avg");return n.makeTensorInfo(d.shape,"float32",d.values)}var qX={kernelName:Yd,backendName:"cpu",kernelFunc:jX};function XX(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,{filterSize:o,strides:i,pad:l,dimRoundingMode:u}=r;Ce([s,a],"avgPool3DGrad");let c=C.computePool3DInfo(a.shape,o,i,1,l,u),p=c.strideDepth,d=c.strideHeight,h=c.strideWidth,f=c.filterDepth,m=c.filterHeight,g=c.filterWidth,y=c.dilationDepth,x=c.dilationHeight,A=c.dilationWidth,b=c.effectiveFilterDepth,v=c.effectiveFilterHeight,S=c.effectiveFilterWidth,I=b-1-c.padInfo.front,E=S-1-c.padInfo.left,R=v-1-c.padInfo.top,P=We(a.shape,"float32"),_=1/(f*m*g),D=n.bufferSync(s);for(let T=0;T<c.batchSize;++T)for(let F=0;F<c.inChannels;++F)for(let U=0;U<c.inDepth;++U)for(let X=0;X<c.inHeight;++X)for(let z=0;z<c.inWidth;++z){let Z=U-I,W=X-R,ee=z-E,Q=0;for(let ae=0;ae<b;ae+=y){let J=(Z+ae)/p;if(!(J<0||J>=c.outDepth||Math.floor(J)!==J))for(let se=0;se<v;se+=x){let ie=(W+se)/d;if(!(ie<0||ie>=c.outHeight||Math.floor(ie)!==ie))for(let me=0;me<S;me+=A){let be=(ee+me)/h;if(be<0||be>=c.outWidth||Math.floor(be)!==be)continue;Q+=D.get(T,J,ie,be,F)}}}P.set(Q*_,T,U,X,z,F)}return n.makeTensorInfo(P.shape,P.dtype,P.values)}var KX={kernelName:Jf,backendName:"cpu",kernelFunc:XX};function ZX(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,o=a;Ce([s,a],"avgPoolGrad");let{filterSize:i,strides:l,pad:u}=r,c=C.computePool2DInfo(o.shape,i,l,1,u),p=c.strideHeight,d=c.strideWidth,h=c.filterHeight,f=c.filterWidth,m=c.dilationHeight,g=c.dilationWidth,y=c.effectiveFilterHeight,x=c.effectiveFilterWidth,A=x-1-c.padInfo.left,b=y-1-c.padInfo.top,v=We(o.shape,"float32"),S=1/(h*f),I=n.data.get(s.dataId).values,E=We(s.shape,"float32",I);for(let R=0;R<c.batchSize;++R)for(let P=0;P<c.inChannels;++P)for(let _=0;_<c.inHeight;++_)for(let D=0;D<c.inWidth;++D){let T=_-b,F=D-A,U=0;for(let X=0;X<y;X+=m){let z=(T+X)/p;if(!(z<0||z>=c.outHeight||Math.floor(z)!==z))for(let Z=0;Z<x;Z+=g){let W=(F+Z)/d;if(W<0||W>=c.outWidth||Math.floor(W)!==W)continue;U+=E.get(R,z,W,P)}}v.set(U*S,R,_,D,P)}return n.makeTensorInfo(v.shape,v.dtype,v.values)}var YX={kernelName:Yf,backendName:"cpu",kernelFunc:ZX};function JX(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,scale:a,offset:o,mean:i,variance:l}=t;w.assert(i.shape.length===l.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),w.assert(o==null||i.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),w.assert(a==null||i.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),Ce([s,i,l,a,o],"batchNorm");let{varianceEpsilon:u}=r;u==null&&(u=.001);let c=n.data.get(s.dataId).values,p=n.data.get(i.dataId).values,d=n.data.get(l.dataId).values,h=a?n.data.get(a.dataId).values:new Float32Array([1]),f=o?n.data.get(o.dataId).values:new Float32Array([0]),m=new Float32Array(c.length),g=f.length,y=h.length,x=d.length,A=p.length,b=0,v=0,S=0,I=0;for(let E=0;E<c.length;++E)m[E]=f[b++]+(c[E]-p[v++])*h[S++]/Math.sqrt(d[I++]+u),b>=g&&(b=0),v>=A&&(v=0),S>=y&&(S=0),I>=x&&(I=0);return n.makeTensorInfo(s.shape,s.dtype,m)}var QX={kernelName:fo,backendName:"cpu",kernelFunc:JX};function eK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,crops:o}=r;Ce([s],"batchToSpaceND");let i=a.reduce((y,x)=>y*x),l=C.getReshaped(s.shape,a,i),u=C.getPermuted(l.length,a.length),c=C.getReshapedPermuted(s.shape,a,i),p=C.getSliceBeginCoords(o,a.length),d=C.getSliceSize(c,o,a.length),h=$t({inputs:{x:s},backend:n,attrs:{shape:l}}),f=ar({inputs:{x:h},backend:n,attrs:{perm:u}}),m=$t({inputs:{x:f},backend:n,attrs:{shape:c}}),g=zi({inputs:{x:m},backend:n,attrs:{begin:p,size:d}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}var tK={kernelName:Hi,backendName:"cpu",kernelFunc:eK};function nK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:o}=r,i=n.data.get(s.dataId).values,l=n.data.get(a.dataId).values,u=Yx(i,l,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,u)}var rK={kernelName:Qf,backendName:"cpu",kernelFunc:nK};function sK(e){let{inputs:t,backend:n}=e,{s0:r,s1:s}=t,a=n.data.get(r.dataId).values,o=n.data.get(s.dataId).values,i=C.assertAndGetBroadcastShape(Array.from(a),Array.from(o));return n.makeTensorInfo([i.length],"int32",Int32Array.from(i))}var aK={kernelName:em,backendName:"cpu",kernelFunc:sK},oK=gt(ta,(e,t)=>{let n=t;return e>n.clipValueMax?n.clipValueMax:e<n.clipValueMin?n.clipValueMin:e}),iK={kernelName:ta,backendName:"cpu",kernelFunc:oK},lK=e=>{let{x:t}=e.inputs,n=e.backend,r=new Float32Array(w.sizeFromShape(t.shape)),s=n.data.get(t.dataId),a=s.complexTensorInfos.real,o=s.complexTensorInfos.imag,i=n.data.get(a.dataId).values,l=n.data.get(o.dataId).values;for(let u=0;u<i.length;u++){let c=i[u],p=l[u];r[u]=Math.hypot(c,p)}return n.makeOutput(r,t.shape,"float32")},uK={kernelName:Qd,backendName:"cpu",kernelFunc:lK};function Du(e){let{inputs:t,backend:n}=e,{input:r}=t,s=n.data.get(r.dataId).complexTensorInfos.imag,a=n.data.get(s.dataId).values;return n.makeTensorInfo(s.shape,s.dtype,a)}var cK={kernelName:rp,backendName:"cpu",kernelFunc:Du};function Pu(e){let{inputs:t,backend:n,attrs:r}=e,{axis:s}=r,a=w.parseAxisParam(s,t[0].shape)[0],o=C.computeOutShape(t.map(m=>m.shape),a);if(w.sizeFromShape(o)===0)return n.makeTensorInfo(o,t[0].dtype,[]);let i=t.filter(m=>w.sizeFromShape(m.shape)>0);if(i.length===1)return Ps({inputs:{x:i[0]},backend:n});let l=i.map(m=>m.shape);if(C.assertParamsConsistent(l,a),i[0].dtype==="complex64"){let m=i.map(b=>Mi({inputs:{input:b},backend:n})),g=i.map(b=>Du({inputs:{input:b},backend:n})),y=Pu({inputs:m,backend:n,attrs:{axis:a}}),x=Pu({inputs:g,backend:n,attrs:{axis:a}}),A=mr({inputs:{real:y,imag:x},backend:n});return m.forEach(b=>n.disposeIntermediateTensorInfo(b)),g.forEach(b=>n.disposeIntermediateTensorInfo(b)),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(x),A}let u=i.map(m=>{let g=w.sizeFromShape(m.shape.slice(a));return $t({inputs:{x:m},backend:n,attrs:{shape:[-1,g]}})}),c=u.map(m=>({vals:n.data.get(m.dataId).values,shape:m.shape}));o=C.computeOutShape(u.map(m=>m.shape),1);let p=u[0].shape[0]===1,d=Jx(c,o,t[0].dtype,p),h=C.computeOutShape(i.map(m=>m.shape),a),f=n.makeTensorInfo(h,t[0].dtype,d);return u.forEach(m=>n.disposeIntermediateTensorInfo(m)),f}var dK={kernelName:ji,backendName:"cpu",kernelFunc:Pu};function qS(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dataFormat:l,dilations:u,dimRoundingMode:c}=r;Ce([s,a],"conv2d");let p=C.convertConv2DDataFormat(l),d=C.computeConv2DInfo(s.shape,a.shape,o,u,i,c,!1,p),h=d.filterHeight,f=d.filterWidth,m=d.dilationHeight,g=d.dilationWidth,y=d.padInfo.left,x=d.padInfo.top,A=d.dataFormat==="channelsLast",b=new on(d.outShape,s.dtype),v=w.computeStrides(s.shape),S=w.computeStrides(a.shape),I=v[0],E=A?v[1]:v[2],R=A?v[2]:1,P=A?1:v[1],_=b.strides[0],D=A?b.strides[1]:b.strides[2],T=A?b.strides[2]:1,F=A?1:b.strides[1],U=n.data.get(s.dataId).values,X=n.data.get(a.dataId).values,z=b.values;for(let Z=0;Z<d.batchSize;++Z){let W=Z*I,ee=Z*_;for(let Q=0;Q<d.outHeight;++Q){let ae=ee+Q*D,J=Q*d.strideHeight-x;for(let se=0;se<h;++se){let ie=J+se*m;if(ie<0||ie>=d.inHeight)continue;let me=se*S[0],be=W+ie*E;for(let Ee=0;Ee<d.outWidth;++Ee){let Re=ae+Ee*T,ze=Ee*d.strideWidth-y;for(let Be=0;Be<f;++Be){let nt=ze+Be*g;if(nt<0||nt>=d.inWidth)continue;let it=me+Be*S[1],lt=be+nt*R,ft=it;for(let $e=0;$e<d.inChannels;++$e){let wt=U[lt+$e*P];for(let At=0;At<d.outChannels;++At)z[Re+At*F]+=wt*X[ft+At];ft+=d.outChannels}}}}}}return n.makeTensorInfo(b.shape,b.dtype,z)}var pK={kernelName:no,backendName:"cpu",kernelFunc:qS};function hK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,pad:i,dataFormat:l,dimRoundingMode:u,filterShape:c}=r;Ce([s,a],"conv2dBackpropFilter");let p=C.convertConv2DDataFormat(l),d=C.computeConv2DInfo(s.shape,c,o,1,i,u,!1,p),{strideHeight:h,strideWidth:f,filterHeight:m,filterWidth:g}=d,y=d.dataFormat==="channelsLast",x=new on(d.filterShape,"float32"),A=d.padInfo.left,b=d.padInfo.top,v=n.data.get(s.dataId).values,S=n.data.get(a.dataId).values,I=new on(s.shape,s.dtype,v),E=new on(a.shape,a.dtype,S);for(let R=0;R<m;++R){let P=Math.max(0,Math.ceil((b-R)/h)),_=Math.min(d.outHeight,(d.inHeight+b-R)/h);for(let D=0;D<g;++D){let T=Math.max(0,Math.ceil((A-D)/f)),F=Math.min(d.outWidth,(d.inWidth+A-D)/f);for(let U=0;U<d.inChannels;++U)for(let X=0;X<d.outChannels;++X){let z=0;for(let Z=0;Z<d.batchSize;++Z)for(let W=P;W<_;++W){let ee=R+W*h-b;for(let Q=T;Q<F;++Q){let ae=D+Q*f-A;y?z+=I.get(Z,ee,ae,U)*E.get(Z,W,Q,X):z+=I.get(Z,U,ee,ae)*E.get(Z,X,W,Q)}}x.set(z,R,D,U,X)}}}return n.makeTensorInfo(x.shape,x.dtype,x.values)}var fK={kernelName:tm,backendName:"cpu",kernelFunc:hK};function mK(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{inputShape:o,strides:i,pad:l,dataFormat:u,dimRoundingMode:c}=r;Ce([s,a],"conv2dBackpropInput");let p=w.computeStrides(a.shape),d=w.computeStrides(s.shape),h=C.convertConv2DDataFormat(u),f=C.computeConv2DInfo(o,a.shape,i,1,l,c,!1,h),m=new on(f.inShape,"float32"),g=m.values,y=n.data.get(s.dataId).values,x=n.data.get(a.dataId).values,[A,b,v]=p,{batchSize:S,filterHeight:I,filterWidth:E,inChannels:R,inHeight:P,inWidth:_,outChannels:D,outHeight:T,outWidth:F,strideHeight:U,strideWidth:X}=f;h=f.dataFormat;let z=I-1-f.padInfo.top,Z=E-1-f.padInfo.left,W=h==="channelsLast",ee=m.strides[0],Q=W?m.strides[1]:m.strides[2],ae=W?m.strides[2]:1,J=W?1:m.strides[1],se=d[0],ie=W?d[1]:d[2],me=W?d[2]:1,be=W?1:d[1];for(let Ee=0;Ee<S;++Ee)for(let Re=0;Re<R;++Re)for(let ze=0;ze<P;++ze){let Be=ze-z,nt=Math.max(0,Math.ceil(Be/U)),it=Math.min(T,(I+Be)/U);for(let lt=0;lt<_;++lt){let ft=lt-Z,$e=Math.max(0,Math.ceil(ft/X)),wt=Math.min(F,(E+ft)/X),At=0;for(let qt=nt;qt<it;++qt){let ur=qt*U-Be;for(let nn=$e;nn<wt;++nn){let Fn=nn*X-ft,cr=se*Ee+ie*qt+me*nn,dr=A*(I-1-ur)+b*(E-1-Fn)+v*Re;for(let Sn=0;Sn<D;++Sn){let Ir=y[cr+be*Sn],On=x[dr+Sn];At+=Ir*On}}}let Pn=ee*Ee+Q*ze+ae*lt+J*Re;g[Pn]=At}}return n.makeTensorInfo(m.shape,m.dtype,m.values)}var gK={kernelName:ro,backendName:"cpu",kernelFunc:mK};function yK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:l}=r;Ce([s,a],"conv3d");let u=C.computeConv3DInfo(s.shape,a.shape,o,l,i),{filterDepth:c,filterHeight:p,filterWidth:d,dilationDepth:h,dilationHeight:f,dilationWidth:m,padInfo:g}=u,y=g.front,x=g.left,A=g.top,b=new on(u.outShape,s.dtype),v=n.data.get(s.dataId).values,S=n.data.get(a.dataId).values,I=b.values,E=w.computeStrides(s.shape),R=w.computeStrides(a.shape);for(let P=0;P<u.batchSize;++P){let _=P*E[0],D=P*b.strides[0];for(let T=0;T<u.outDepth;++T){let F=D+T*b.strides[1],U=T*u.strideDepth-y;for(let X=0;X<c;++X){let z=U+X*h;if(z<0||z>=u.inDepth)continue;let Z=X*R[0],W=_+z*E[1];for(let ee=0;ee<u.outHeight;++ee){let Q=F+ee*b.strides[2],ae=ee*u.strideHeight-A;for(let J=0;J<p;++J){let se=ae+J*f;if(se<0||se>=u.inHeight)continue;let ie=Z+J*R[1],me=W+se*E[2];for(let be=0;be<u.outWidth;++be){let Ee=Q+be*u.outChannels,Re=be*u.strideWidth-x;for(let ze=0;ze<d;++ze){let Be=Re+ze*m;if(Be<0||Be>=u.inWidth)continue;let nt=ie+ze*R[2],it=me+Be*u.inChannels,lt=nt;for(let ft=0;ft<u.inChannels;++ft){let $e=v[it+ft];for(let wt=0;wt<u.outChannels;++wt)I[Ee+wt]+=$e*S[lt+wt];lt+=u.outChannels}}}}}}}}return n.makeTensorInfo(b.shape,b.dtype,b.values)}var AK={kernelName:ep,backendName:"cpu",kernelFunc:yK};function xK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,pad:i,filterShape:l}=r;Ce([s,a],"conv3dBackpropFilterV2");let u=w.computeStrides(s.shape),c=w.computeStrides(a.shape),p=C.computeConv3DInfo(s.shape,l,o,1,i),d=p.strideDepth,h=p.strideHeight,f=p.strideWidth,m=p.filterDepth,g=p.filterHeight,y=p.filterWidth,x=new on(p.filterShape,"float32"),A=x.values,[b,v,S,I]=x.strides,E=n.data.get(a.dataId).values,[R,P,_,D]=c,T=n.data.get(s.dataId).values,[F,U,X,z]=u,Z=p.padInfo.front,W=p.padInfo.left,ee=p.padInfo.top;for(let Q=0;Q<m;++Q){let ae=Math.max(0,Math.ceil((Z-Q)/d)),J=Math.min(p.outDepth,(p.inDepth+Z-Q)/d),se=Q*b;for(let ie=0;ie<g;++ie){let me=Math.max(0,Math.ceil((ee-ie)/h)),be=Math.min(p.outHeight,(p.inHeight+ee-ie)/h),Ee=ie*v+se;for(let Re=0;Re<y;++Re){let ze=Math.max(0,Math.ceil((W-Re)/f)),Be=Math.min(p.outWidth,(p.inWidth+W-Re)/f),nt=Re*S+Ee;for(let it=0;it<p.inChannels;++it){let lt=it*I+nt;for(let ft=0;ft<p.outChannels;++ft){let $e=0;for(let wt=0;wt<p.batchSize;++wt){let At=wt*F,Pn=wt*R;for(let qt=ae;qt<J;++qt){let nn=(Q+qt*d-Z)*U+At,Fn=qt*P+Pn;for(let cr=me;cr<be;++cr){let Sn=(ie+cr*h-ee)*X+nn,Ir=cr*_+Fn;for(let On=ze;On<Be;++On){let Gs=(Re+On*f-W)*z+Sn,Kl=On*D+Ir;$e+=T[Gs+it]*E[Kl+ft]}}}}A[lt+ft]=$e}}}}}return n.makeTensorInfo(x.shape,x.dtype,x.values)}var bK={kernelName:nm,backendName:"cpu",kernelFunc:xK};function vK(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{pad:o,strides:i,inputShape:l}=r;Ce([s],"conv3dBackpropInputV2");let u=w.computeStrides(s.shape),c=w.computeStrides(a.shape),p=C.computeConv3DInfo(l,a.shape,i,1,o),d=new on(p.inShape,"float32"),h=d.values,[f,m,g,y]=d.strides,x=n.data.get(s.dataId).values,[A,b,v,S]=u,I=n.data.get(a.dataId).values,[E,R,P,_]=c,{batchSize:D,filterDepth:T,filterHeight:F,filterWidth:U,inChannels:X,inDepth:z,inHeight:Z,inWidth:W,outChannels:ee,outDepth:Q,outHeight:ae,outWidth:J,strideDepth:se,strideHeight:ie,strideWidth:me}=p,be=T-1-p.padInfo.front,Ee=F-1-p.padInfo.top,Re=U-1-p.padInfo.left;for(let ze=0;ze<D;++ze)for(let Be=0;Be<X;++Be)for(let nt=0;nt<z;++nt){let it=nt-be,lt=Math.max(0,Math.ceil(it/se)),ft=Math.min(Q,(T+it)/se);for(let $e=0;$e<Z;++$e){let wt=$e-Ee,At=Math.max(0,Math.ceil(wt/ie)),Pn=Math.min(ae,(F+wt)/ie);for(let qt=0;qt<W;++qt){let ur=qt-Re,nn=Math.max(0,Math.ceil(ur/me)),Fn=Math.min(J,(U+ur)/me),cr=0;for(let dr=lt;dr<ft;++dr){let Sn=dr*se-it;for(let Ir=At;Ir<Pn;++Ir){let On=Ir*ie-wt;for(let Us=nn;Us<Fn;++Us){let Gs=Us*me-ur,Kl=A*ze+b*dr+v*Ir+S*Us,Aa=E*(T-1-Sn)+R*(F-1-On)+P*(U-1-Gs)+_*Be;for(let Hs=0;Hs<ee;++Hs){let nd=x[Kl+Hs],Zl=I[Aa+Hs];cr+=nd*Zl}}}}h[f*ze+m*nt+g*$e+y*qt+Be]=cr}}}return n.makeTensorInfo(d.shape,d.dtype,d.values)}var wK={kernelName:rm,backendName:"cpu",kernelFunc:vK},kK=gt(so,e=>Math.cos(e)),SK={kernelName:so,backendName:"cpu",kernelFunc:kK},IK=gt(ao,e=>Math.cosh(e)),CK={kernelName:ao,backendName:"cpu",kernelFunc:IK};function TK(e){let{inputs:t,backend:n,attrs:r}=e,{image:s,boxes:a,boxInd:o}=t,{cropSize:i,method:l,extrapolationValue:u}=r,[c,p,d,h]=s.shape,f=a.shape[0],[m,g]=i,y=We([f,m,g,h],"float32"),x=n.data.get(a.dataId).values,A=n.data.get(o.dataId).values,b=n.data.get(s.dataId).values,v=w.computeStrides(s.shape),S=w.computeStrides(y.shape);for(let I=0;I<f;I++){let E=I*4,R=x[E],P=x[E+1],_=x[E+2],D=x[E+3],T=A[I];if(T>=c)continue;let F=m>1?(_-R)*(p-1)/(m-1):0,U=g>1?(D-P)*(d-1)/(g-1):0;for(let X=0;X<m;X++){let z=m>1?R*(p-1)+X*F:.5*(R+_)*(p-1);if(z<0||z>p-1){for(let Z=0;Z<g;Z++)for(let W=0;W<h;W++){let ee=W+Z*S[2]+X*S[1]+I*S[0];y.values[ee]=u}continue}if(l==="bilinear"){let Z=Math.floor(z),W=Math.ceil(z),ee=z-Z;for(let Q=0;Q<g;Q++){let ae=g>1?P*(d-1)+Q*U:.5*(P+D)*(d-1);if(ae<0||ae>d-1){for(let me=0;me<h;me++){let be=me+Q*S[2]+X*S[1]+I*S[0];y.values[be]=u}continue}let J=Math.floor(ae),se=Math.ceil(ae),ie=ae-J;for(let me=0;me<h;me++){let be=me+J*v[2]+Z*v[1]+T*v[0],Ee=b[be];be=me+se*v[2]+Z*v[1]+T*v[0];let Re=b[be];be=me+J*v[2]+W*v[1]+T*v[0];let ze=b[be];be=me+se*v[2]+W*v[1]+T*v[0];let Be=b[be],nt=Ee+(Re-Ee)*ie,it=ze+(Be-ze)*ie;be=me+Q*S[2]+X*S[1]+I*S[0],y.values[be]=nt+(it-nt)*ee}}}else for(let Z=0;Z<g;++Z){let W=g>1?P*(d-1)+Z*U:.5*(P+D)*(d-1);if(W<0||W>d-1){for(let ae=0;ae<h;ae++){let J=ae+Z*S[2]+X*S[1]+I*S[0];y.values[J]=u}continue}let ee=Math.round(W),Q=Math.round(z);for(let ae=0;ae<h;ae++){let J=ae+ee*v[2]+Q*v[1]+T*v[0],se=ae+Z*S[2]+X*S[1]+I*S[0];y.values[se]=b[J]}}}}return n.makeTensorInfo(y.shape,y.dtype,y.values)}var NK={kernelName:Xi,backendName:"cpu",kernelFunc:TK};function EK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:o,reverse:i}=r;Ce(s,"cumprod");let l=C.getAxesPermutation([a],s.shape.length),u=s;l!=null&&(u=ar({inputs:{x:s},backend:n,attrs:{perm:l}}));let c=C.getInnerMostAxes(1,s.shape.length)[0];if(c!==u.shape.length-1)throw new Error(`backend.cumprod in CPU expects an inner-most axis=${u.shape.length-1} but got axis=${c}`);let p=Nn(u.dtype,"int32"),d=w.makeOnesTypedArray(w.sizeFromShape(u.shape),p),h=n.data.get(u.dataId).values,f=u.shape[u.shape.length-1],m=i?(y,x)=>y+f-x-1:(y,x)=>y+x;for(let y=0;y<h.length;y+=f)for(let x=0;x<f;x++){let A=m(y,x);if(x===0)d[A]=o?1:h[A];else{let b=m(y,x-1);d[A]=o?h[b]*d[b]:h[A]*d[b]}}let g=n.makeTensorInfo(u.shape,p,d);if(l!=null){let y=C.getUndoAxesPermutation(l),x=ar({inputs:{x:g},backend:n,attrs:{perm:y}});return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(u),x}return g}var RK={kernelName:qi,backendName:"cpu",kernelFunc:EK};function _K(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:o,reverse:i}=r;Ce(s,"cumsum");let l=C.getAxesPermutation([a],s.shape.length),u=s;l!=null&&(u=ar({inputs:{x:s},backend:n,attrs:{perm:l}}));let c=C.getInnerMostAxes(1,s.shape.length)[0];if(c!==u.shape.length-1)throw new Error(`backend.cumsum in CPU expects an inner-most axis=${u.shape.length-1} but got axis=${c}`);let p=Nn(u.dtype,"int32"),d=w.makeZerosTypedArray(w.sizeFromShape(u.shape),p),h=n.data.get(u.dataId).values,f=u.shape[u.shape.length-1],m=i?(y,x)=>y+f-x-1:(y,x)=>y+x;for(let y=0;y<h.length;y+=f)for(let x=0;x<f;x++){let A=m(y,x);if(x===0)d[A]=o?0:h[A];else{let b=m(y,x-1);d[A]=o?h[b]+d[b]:h[A]+d[b]}}let g=n.makeTensorInfo(u.shape,p,d);if(l!=null){let y=C.getUndoAxesPermutation(l),x=ar({inputs:{x:g},backend:n,attrs:{perm:y}});return n.disposeIntermediateTensorInfo(g),n.disposeIntermediateTensorInfo(u),x}return g}var $K={kernelName:oo,backendName:"cpu",kernelFunc:_K};function DK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:o,binaryOutput:i}=r;if(s.shape.length===1){let l=n.data.get(s.dataId).values,u=n.data.get(a.dataId).values,c=Yx(l,u,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,c)}else if(s.shape.length===2){let l=n.bufferSync(s),u=n.bufferSync(a),c=rS(l,u,o,i);return n.makeTensorInfo(c.shape,a.dtype,c.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${s.shape.length}.`)}var PK={kernelName:sm,backendName:"cpu",kernelFunc:DK};function FK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockSize:a,dataFormat:o}=r;w.assert(o==="NHWC",()=>`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${o}`);let i=s.shape[0],l=s.shape[1],u=s.shape[2],c=s.shape[3],p=l*a,d=u*a,h=c/(a*a),f=n.data.get(s.dataId).values,m=new Float32Array(i*p*d*h),g=0;for(let y=0;y<i;++y)for(let x=0;x<p;++x){let A=Math.floor(x/a),b=x%a;for(let v=0;v<d;++v){let S=Math.floor(v/a),I=v%a,E=(b*a+I)*h;for(let R=0;R<h;++R){let _=R+E+c*(S+u*(A+l*y));m[g++]=f[_]}}}return n.makeTensorInfo([i,p,d,h],s.dtype,m)}var OK={kernelName:Ki,backendName:"cpu",kernelFunc:FK};function XS(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:l,dimRoundingMode:u}=r;Ce([s,a],"depthwiseConv2DNative");let c=w.computeStrides(s.shape),p=w.computeStrides(a.shape),d=l;d==null&&(d=[1,1]),w.assert(C.eitherStridesOrDilationsAreOne(o,d),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${d}'`);let h=C.computeConv2DInfo(s.shape,a.shape,o,d,i,u,!0),{filterHeight:f,filterWidth:m,dilationHeight:g,dilationWidth:y,padInfo:x}=h,A=x.left,b=x.top,v=h.outChannels/h.inChannels,S=new on(h.outShape,s.dtype),I=n.data.get(s.dataId).values,E=n.data.get(a.dataId).values,R=S.values;for(let P=0;P<h.batchSize;++P){let _=P*c[0],D=P*S.strides[0];for(let T=0;T<h.outHeight;++T){let F=D+T*S.strides[1],U=T*h.strideHeight-b;for(let X=0;X<f;++X){let z=U+X*g;if(z<0||z>=h.inHeight)continue;let Z=X*p[0],W=_+z*c[1];for(let ee=0;ee<h.outWidth;++ee){let Q=F+ee*S.strides[2],ae=ee*h.strideWidth-A;for(let J=0;J<m;++J){let se=ae+J*y;if(se<0||se>=h.inWidth)continue;let ie=Z+J*p[1],me=W+se*h.inChannels,be=Q,Ee=ie;for(let Re=0;Re<h.inChannels;++Re){let ze=I[me+Re];for(let Be=0;Be<v;++Be)R[be+Be]+=ze*E[Ee+Be];be+=v,Ee+=v}}}}}}return n.makeTensorInfo(S.shape,S.dtype,S.values)}var MK={kernelName:io,backendName:"cpu",kernelFunc:XS};function zK(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,dilations:i,pad:l,dimRoundingMode:u,filterShape:c}=r;Ce([s,a],"depthwiseConv2dNativeBackpropFilter");let p=C.computeConv2DInfo(s.shape,c,o,i,l,u,!0),{strideHeight:d,strideWidth:h,filterHeight:f,filterWidth:m}=p,g=new on(p.filterShape,"float32"),y=p.padInfo.left,x=p.padInfo.top,A=p.outChannels/p.inChannels,b=n.data.get(s.dataId).values,v=new on(s.shape,s.dtype,b),S=n.data.get(a.dataId).values,I=new on(a.shape,a.dtype,S);for(let E=0;E<f;++E){let R=Math.max(0,Math.ceil((x-E)/d)),P=Math.min(p.outHeight,(p.inHeight+x-E)/d);for(let _=0;_<m;++_){let D=Math.max(0,Math.ceil((y-_)/h)),T=Math.min(p.outWidth,(p.inWidth+y-_)/h);for(let F=0;F<p.outChannels;++F){let U=Math.trunc(F/A),X=F%A,z=0;for(let Z=0;Z<p.batchSize;++Z)for(let W=R;W<P;++W){let ee=E+W*d-x;for(let Q=D;Q<T;++Q){let ae=_+Q*h-y;z+=v.get(Z,ee,ae,U)*I.get(Z,W,Q,F)}}g.set(z,E,_,U,X)}}}return n.makeTensorInfo(g.shape,g.dtype,g.values)}var LK={kernelName:am,backendName:"cpu",kernelFunc:zK};function BK(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{strides:o,dilations:i,pad:l,dimRoundingMode:u,inputShape:c}=r;Ce([s,a],"depthwiseConv2DNativeBackpropInput");let p=w.computeStrides(s.shape),d=w.computeStrides(a.shape),h=C.computeConv2DInfo(c,a.shape,o,i,l,u,!0),f=new on(h.inShape,"float32"),m=f.values,[g,y,x]=f.strides,A=n.data.get(s.dataId).values,[b,v,S]=p,I=n.data.get(a.dataId).values,[E,R,P]=d,{batchSize:_,filterHeight:D,filterWidth:T,inChannels:F,inHeight:U,inWidth:X,outChannels:z,outHeight:Z,outWidth:W,strideHeight:ee,strideWidth:Q}=h,ae=D-1-h.padInfo.top,J=T-1-h.padInfo.left,se=z/F;for(let ie=0;ie<_;++ie)for(let me=0;me<F;++me)for(let be=0;be<U;++be){let Ee=be-ae,Re=Math.max(0,Math.ceil(Ee/ee)),ze=Math.min(Z,(D+Ee)/ee);for(let Be=0;Be<X;++Be){let nt=Be-J,it=Math.max(0,Math.ceil(nt/Q)),lt=Math.min(W,(T+nt)/Q),ft=0;for(let $e=Re;$e<ze;++$e){let wt=$e*ee-Ee;for(let At=it;At<lt;++At){let Pn=At*Q-nt,qt=b*ie+v*$e+S*At,ur=E*(D-1-wt)+R*(T-1-Pn)+P*me;for(let nn=0;nn<se;++nn){let Fn=me*se+nn,cr=A[qt+Fn],dr=I[ur+nn];ft+=cr*dr}}}m[g*ie+y*be+x*Be+me]=ft}}return n.makeTensorInfo(f.shape,f.dtype,f.values)}var WK={kernelName:om,backendName:"cpu",kernelFunc:BK};function VK(e){let{inputs:t,backend:n}=e,{x:r}=t,s=w.sizeFromShape(r.shape),a=n.data.get(r.dataId).values,o=We([s,s],r.dtype),i=o.values;for(let u=0;u<a.length;u++)i[u*s+u]=a[u];let l=[...r.shape,...r.shape];return n.makeTensorInfo(l,o.dtype,o.values)}var UK={kernelName:im,backendName:"cpu",kernelFunc:VK},GK={kernelName:tp,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:r,filter:s}=e,{strides:a,pad:o,dilations:i}=n,l=t,u=l.data.get(r.dataId).values,c=r.shape.length,p=l.data.get(s.dataId).values,d=s.shape.length,{batchSize:h,inHeight:f,inWidth:m,inChannels:g,outHeight:y,outWidth:x,padInfo:A,strideHeight:b,strideWidth:v,filterHeight:S,filterWidth:I,dilationHeight:E,dilationWidth:R,outShape:P}=C.computeDilation2DInfo(r.shape,s.shape,a,o,"NHWC",i),_=w.sizeFromShape(P),D=P.length,T=w.getArrayFromDType(r.dtype,_);for(let U=0;U<h;++U)for(let X=0;X<y;++X){let z=X*b-A.top;for(let Z=0;Z<x;++Z){let W=Z*v-A.left;for(let ee=0;ee<g;++ee){let Q=Number.MIN_SAFE_INTEGER;for(let J=0;J<S;++J){let se=z+J*E;if(se>=0&&se<f)for(let ie=0;ie<I;++ie){let me=W+ie*R;if(me>=0&&me<m){let be=w.locToIndex([U,se,me,ee],c,w.computeStrides(r.shape)),Ee=w.locToIndex([J,ie,ee],d,w.computeStrides(s.shape)),Re=u[be]+p[Ee];Re>Q&&(Q=Re)}}}let ae=w.locToIndex([U,X,Z,ee],D,w.computeStrides(P));T[ae]=Q}}}return{dataId:l.write(w.toTypedArray(T,r.dtype),P,r.dtype),shape:P,dtype:r.dtype}}},HK={kernelName:xf,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:r,filter:s,dy:a}=e,{strides:o,pad:i,dilations:l}=n,u=t,c=w.toNestedArray(r.shape,u.data.get(r.dataId).values),p=w.toNestedArray(s.shape,u.data.get(s.dataId).values),{batchSize:d,inHeight:h,inWidth:f,inChannels:m,outHeight:g,outWidth:y,padInfo:x,strideHeight:A,strideWidth:b,filterHeight:v,filterWidth:S,dilationHeight:I,dilationWidth:E,outShape:R}=C.computeDilation2DInfo(r.shape,s.shape,o,i,"NHWC",l);w.assert(a.rank===R.length,()=>`Error in ${xf}, dy must have the same rank as output ${R.length}, but got ${a.rank}`);let P=w.toNestedArray(R,u.data.get(a.dataId).values),_=w.makeZerosNestedTypedArray(s.shape,s.dtype);for(let T=0;T<d;++T)for(let F=0;F<g;++F){let U=F*A-x.top;for(let X=0;X<y;++X){let z=X*b-x.left;for(let Z=0;Z<m;++Z){let W=Number.MIN_SAFE_INTEGER,ee=0,Q=0;for(let ae=0;ae<v;++ae){let J=U+ae*I;if(J>=0&&J<h)for(let se=0;se<S;++se){let ie=z+se*E;if(ie>=0&&ie<f){let me=c[T][J][ie][Z]+p[ae][se][Z];me>W&&(W=me,ee=ae,Q=se)}}}_[ee][Q][Z]+=P[T][F][X][Z]}}}return{dataId:u.write(w.toTypedArray(_,r.dtype),s.shape,s.dtype),shape:s.shape,dtype:s.dtype}}},jK={kernelName:Af,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:r,filter:s,dy:a}=e,{strides:o,pad:i,dilations:l}=n,u=t,c=w.toNestedArray(r.shape,u.data.get(r.dataId).values),p=w.toNestedArray(s.shape,u.data.get(s.dataId).values),{batchSize:d,inHeight:h,inWidth:f,inChannels:m,outHeight:g,outWidth:y,padInfo:x,strideHeight:A,strideWidth:b,filterHeight:v,filterWidth:S,dilationHeight:I,dilationWidth:E,outShape:R}=C.computeDilation2DInfo(r.shape,s.shape,o,i,"NHWC",l);w.assert(a.rank===R.length,()=>`Error in ${Af}, dy must have the same rank as output ${R.length}, but got ${a.rank}`);let P=w.toNestedArray(R,u.data.get(a.dataId).values),_=w.makeZerosNestedTypedArray(r.shape,r.dtype);for(let T=0;T<d;++T)for(let F=0;F<g;++F){let U=F*A-x.top;for(let X=0;X<y;++X){let z=X*b-x.left;for(let Z=0;Z<m;++Z){let W=Number.MIN_SAFE_INTEGER,ee=U<0?0:U,Q=z<0?0:z;for(let ae=0;ae<v;++ae){let J=U+ae*I;if(J>=0&&J<h)for(let se=0;se<S;++se){let ie=z+se*E;if(ie>=0&&ie<f){let me=c[T][J][ie][Z]+p[ae][se][Z];me>W&&(W=me,ee=J,Q=ie)}}}_[T][ee][Q][Z]+=P[T][F][X][Z]}}}return{dataId:u.write(w.toTypedArray(_,r.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}};function Mp(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r;Ce(s,"sum");let i;s.dtype==="bool"?i=qa({inputs:{x:s},backend:n,attrs:{dtype:"int32"}}):i=Ps({inputs:{x:s},backend:n});let l=i.shape.length,u=w.parseAxisParam(a,i.shape),c=C.getAxesPermutation(u,l),p=u,d=i;c!=null&&(d=ar({inputs:{x:i},backend:n,attrs:{perm:c}}),p=C.getInnerMostAxes(p.length,l)),C.assertAxesAreInnerMostDims("sum",p,d.shape.length);let[h,f]=C.computeOutAndReduceShapes(d.shape,p),m=C.upcastType(d.dtype,"int32"),g=Lf(n,h,m),y=w.sizeFromShape(f),x=n.data.get(g.dataId).values,A=n.data.get(d.dataId).values;for(let b=0;b<x.length;++b){let v=b*y,S=0;for(let I=0;I<y;++I)S+=A[v+I];x[b]=S}if(o){let b=C.expandShapeToKeepDim(g.shape,u),v=g;g=$t({inputs:{x:g},backend:n,attrs:{shape:b}}),n.disposeIntermediateTensorInfo(v)}return n.disposeIntermediateTensorInfo(i),c!=null&&n.disposeIntermediateTensorInfo(d),g}var qK={kernelName:zo,backendName:"cpu",kernelFunc:Mp};function XK(e){let{inputs:t,backend:n,attrs:r}=e,{equation:s}=r,a=t,{allDims:o,summedDims:i,idDims:l}=C.decodeEinsumEquation(s,a.length);C.checkEinsumDimSizes(o.length,l,a);let{path:u,steps:c}=C.getEinsumComputePath(i,l),p=c.length,d=null,h=o.length,f=[];for(let m=0;m<p;++m){for(let g of c[m]){let{permutationIndices:y,expandDims:x}=C.getEinsumPermutation(h,l[g]),A;C.isIdentityPermutation(y)?A=a[g]:(A=ar({inputs:{x:a[g]},backend:n,attrs:{perm:y}}),f.push(A));let b=A.shape.slice();for(let v=0;v<x.length;++v)b.splice(x[v],0,1);w.arraysEqual(A.shape,b)||(A=$t({inputs:{x:A},backend:n,attrs:{shape:b}}),f.push(A)),d===null?d=A:(d=b0({inputs:{a:A,b:d},backend:n}),f.push(d))}m<p-1&&(u[m]>=0&&(d=Mp({inputs:{x:d},backend:n,attrs:{axis:u[m]-(o.length-h),keepDims:!1}}),f.push(d)),h--)}for(let m of f)m!==d&&n.disposeIntermediateTensorInfo(m);return d}var KK={kernelName:np,backendName:"cpu",kernelFunc:XK};function ZK(e){let{inputs:t,backend:n}=e,{dy:r,y:s}=t;Ce([r,s],"eluGrad");let a=new Float32Array(w.sizeFromShape(s.shape)),o=n.data.get(s.dataId).values,i=n.data.get(r.dataId).values;for(let l=0;l<o.length;++l){let u=o[l];u>=1?a[l]=i[l]:a[l]=i[l]*(u+1)}return n.makeTensorInfo(s.shape,"float32",a)}var YK={kernelName:lm,backendName:"cpu",kernelFunc:ZK},JK=C.ERF_P,QK=C.ERF_A1,eZ=C.ERF_A2,tZ=C.ERF_A3,nZ=C.ERF_A4,rZ=C.ERF_A5,sZ=gt(Xu,e=>{let t=Math.sign(e),n=Math.abs(e),r=1/(1+JK*n);return t*(1-((((rZ*r+nZ)*r+tZ)*r+eZ)*r+QK)*r*Math.exp(-n*n))}),aZ={kernelName:Xu,backendName:"cpu",kernelFunc:sZ};function Wf(e){let{inputs:t,backend:n,attrs:r}=e,{input:s}=t,{dim:a}=r,o=s.shape.length,i=s.shape.slice(),l=a;return a<0&&(w.assert(-(o+1)<=a,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),l=o+a+1),i.splice(l,0,1),$t({inputs:{x:s},backend:n,attrs:{shape:i}})}var oZ={kernelName:Yi,backendName:"cpu",kernelFunc:Wf},iZ=Qt((e,t)=>e/t),o3=xn(lo,iZ),Xg={kernelName:lo,backendName:"cpu",kernelFunc:o3};function KS(e,t,n){let r=e.shape,s=r[0],a=r[1],o=n.data.get(e.dataId),i=o.complexTensorInfos.real,l=o.complexTensorInfos.imag,u=[s,a],c=w.sizeFromShape(u),p=w.getTypedArrayFromDType("float32",c),d=w.getTypedArrayFromDType("float32",c);for(let g=0;g<s;g++){let y=zi({inputs:{x:i},backend:n,attrs:{begin:[g,0],size:[1,a]}}),x=zi({inputs:{x:l},backend:n,attrs:{begin:[g,0],size:[1,a]}}),A=mr({inputs:{real:y,imag:x},backend:n}),{real:b,imag:v}=lZ(A,t,n),S=C.mergeRealAndImagArrays(b,v);for(let I=0;I<a;I++){let E=C.getComplexWithIndex(S,I);p[g*a+I]=E.real,d[g*a+I]=E.imag}n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(x),n.disposeIntermediateTensorInfo(A)}let h=n.makeTensorInfo(u,"float32",p),f=n.makeTensorInfo(u,"float32",d),m=mr({inputs:{real:h,imag:f},backend:n});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),m}function lZ(e,t,n){let r=w.sizeFromShape(e.shape),s=n.data.get(e.dataId),a=n.data.get(s.complexTensorInfos.real.dataId).values,o=n.data.get(s.complexTensorInfos.imag.dataId).values;if(uZ(r)){let i=Kg(a,o,r,t,n),l=[e.shape[0],e.shape[1]];if(t){let u=n.makeTensorInfo(l,"float32",i.real),c=n.makeTensorInfo(l,"float32",i.imag),p=n.makeTensorInfo([],"float32",w.createScalarValue(r,"float32")),d=Ps({inputs:{x:p},backend:n}),h=Xg.kernelFunc({inputs:{a:u,b:p},backend:n}),f=Xg.kernelFunc({inputs:{a:c,b:d},backend:n}),m=n.data.get(h.dataId).values,g=n.data.get(f.dataId).values;return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),{real:m,imag:g}}return i}else{let i=C.mergeRealAndImagArrays(a,o),l=cZ(i,r,t);return C.splitRealAndImagArrays(l)}}function uZ(e){return(e&e-1)===0}function Kg(e,t,n,r,s){if(n===1)return{real:e,imag:t};let a=C.mergeRealAndImagArrays(e,t),o=n/2,i=C.complexWithEvenIndex(a),l=i.real,u=i.imag,c=[l.length],p=s.makeTensorInfo(c,"float32",l),d=s.makeTensorInfo(c,"float32",u),h=mr({inputs:{real:p,imag:d},backend:s}),f=C.complexWithOddIndex(a),m=f.real,g=f.imag,y=[m.length],x=s.makeTensorInfo(y,"float32",m),A=s.makeTensorInfo(y,"float32",g),b=mr({inputs:{real:x,imag:A},backend:s}),v=Kg(l,u,o,r,s),S=v.real,I=v.imag,E=[S.length],R=s.makeTensorInfo(E,"float32",S),P=s.makeTensorInfo(E,"float32",I),_=mr({inputs:{real:R,imag:P},backend:s}),D=Kg(m,g,o,r,s),T=D.real,F=D.imag,U=[T.length],X=s.makeTensorInfo(U,"float32",T),z=s.makeTensorInfo(U,"float32",F),Z=mr({inputs:{real:X,imag:z},backend:s}),W=C.exponents(n,r),ee=[W.real.length],Q=s.makeTensorInfo(ee,"float32",W.real),ae=s.makeTensorInfo(ee,"float32",W.imag),J=mr({inputs:{real:Q,imag:ae},backend:s}),se=b0({inputs:{a:J,b:Z},backend:s}),ie=Op({inputs:{a:_,b:se},backend:s}),me=r3({inputs:{a:_,b:se},backend:s}),be=Mi({inputs:{input:ie},backend:s}),Ee=Mi({inputs:{input:me},backend:s}),Re=Du({inputs:{input:ie},backend:s}),ze=Du({inputs:{input:me},backend:s}),Be=Pu({inputs:[be,Ee],backend:s,attrs:{axis:0}}),nt=Pu({inputs:[Re,ze],backend:s,attrs:{axis:0}}),it=s.data.get(Be.dataId).values,lt=s.data.get(nt.dataId).values;return s.disposeIntermediateTensorInfo(p),s.disposeIntermediateTensorInfo(d),s.disposeIntermediateTensorInfo(h),s.disposeIntermediateTensorInfo(x),s.disposeIntermediateTensorInfo(A),s.disposeIntermediateTensorInfo(b),s.disposeIntermediateTensorInfo(R),s.disposeIntermediateTensorInfo(P),s.disposeIntermediateTensorInfo(_),s.disposeIntermediateTensorInfo(X),s.disposeIntermediateTensorInfo(z),s.disposeIntermediateTensorInfo(Z),s.disposeIntermediateTensorInfo(Q),s.disposeIntermediateTensorInfo(ae),s.disposeIntermediateTensorInfo(J),s.disposeIntermediateTensorInfo(se),s.disposeIntermediateTensorInfo(ie),s.disposeIntermediateTensorInfo(me),s.disposeIntermediateTensorInfo(be),s.disposeIntermediateTensorInfo(Re),s.disposeIntermediateTensorInfo(Ee),s.disposeIntermediateTensorInfo(ze),s.disposeIntermediateTensorInfo(Be),s.disposeIntermediateTensorInfo(nt),{real:it,imag:lt}}function cZ(e,t,n){let r=new Float32Array(t*2);for(let s=0;s<t;s++){let a=0,o=0;for(let i=0;i<t;i++){let l=C.exponent(s*i,t,n),u=C.getComplexWithIndex(e,i);a+=u.real*l.real-u.imag*l.imag,o+=u.real*l.imag+u.imag*l.real}n&&(a/=t,o/=t),C.assignToTypedArray(r,a,o,s)}return r}function dZ(e){let{inputs:t,backend:n}=e,{input:r}=t,s=w.sizeFromShape(r.shape),a=r.shape[r.shape.length-1],o=s/a,i=$t({inputs:{x:r},backend:n,attrs:{shape:[o,a]}}),l=KS(i,!1,n),u=$t({inputs:{x:l},backend:n,attrs:{shape:r.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),u}var pZ={kernelName:um,backendName:"cpu",kernelFunc:dZ};function i3(e){let{backend:t,attrs:n}=e,{shape:r,value:s,dtype:a}=n,o=a||w.inferDtype(s),i=w.getArrayFromDType(o,w.sizeFromShape(r));return fZ(i,s,o),t.makeTensorInfo(r,o,i)}var hZ={kernelName:Ku,backendName:"cpu",kernelFunc:i3};function fZ(e,t,n){e.fill(t)}var mZ={kernelName:Qi,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:r}=e,s=n,a=w.getTypedArrayFromDType(r.dtype,w.sizeFromShape(r.shape)),[o,i,l,u]=r.shape,c=s.data.get(r.dataId).values;for(let d=0;d<o;d++){let h=d*l*i*u;for(let f=0;f<i;f++){let m=f*(l*u);for(let g=0;g<l;g++){let y=g*u;for(let x=0;x<u;x++){let A=Math.round(l-g-1),b=h+m+y+x,v=c[b];if(A>=0&&A<l){let S=A*u,I=h+m+S+x;v=c[I]}a[b]=v}}}}return{dataId:s.write(a,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},gZ=Qt((e,t)=>Math.floor(e/t)),yZ=xn(ho,gZ,null,"int32"),AZ={kernelName:ho,backendName:"cpu",kernelFunc:yZ};function xZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:d,activation:h,leakyreluAlpha:f}=r,m=qS({inputs:{x:s,filter:a},backend:n,attrs:{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:d}});if(o){let g=m;m=Op({inputs:{a:m,b:o},backend:n}),n.disposeIntermediateTensorInfo(g)}if(h){let g=m;m=s3(n,m,h,i,f),n.disposeIntermediateTensorInfo(g)}return m}var bZ={kernelName:Fa,backendName:"cpu",kernelFunc:xZ};function vZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:d,activation:h,leakyreluAlpha:f}=r,m=XS({inputs:{x:s,filter:a},backend:n,attrs:{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:d}});if(o){let g=m;m=Op({inputs:{a:m,b:o},backend:n}),n.disposeIntermediateTensorInfo(g)}if(h){let g=m;m=s3(n,m,h,i,f),n.disposeIntermediateTensorInfo(g)}return m}var wZ={kernelName:Oa,backendName:"cpu",kernelFunc:vZ};function kZ(e){let{inputs:t,backend:n}=e,{params:r,indices:s}=t,a=w.sizeFromShape(r.shape),o=s.shape,i=o[o.length-1],[l,u,c,p]=C.prepareAndValidate(r,s);if(u===0)return n.makeTensorInfo(l,r.dtype,[]);let d=n.data.get(s.dataId).values,h=n.bufferSync(r),f=dS(d,h,r.dtype,u,i,c,p,r.shape,a);return n.makeTensorInfo(l,r.dtype,f.values)}var SZ={kernelName:tl,backendName:"cpu",kernelFunc:kZ};function IZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,indices:a}=t,{axis:o,batchDims:i}=r;Ce([s,a],"gatherV2");let l=w.parseAxisParam(o,s.shape)[0],u=n.data.get(a.dataId).values,c=s.shape[l];for(let b=0;b<u.length;++b){let v=u[b];w.assert(v<=c-1&&v>=0,()=>`GatherV2: the index value ${v} is not in [0, ${c-1}]`)}let p=i;i==null&&(p=0);let d=w.sizeFromShape(a.shape),h=C.segment_util.collectGatherOpShapeInfo(s,a,l,p),f=$t({inputs:{x:s},backend:n,attrs:{shape:[h.batchSize,h.outerSize,h.dimSize,h.sliceSize]}}),m=$t({inputs:{x:a},backend:n,attrs:{shape:[h.batchSize,d/h.batchSize]}}),g=[h.batchSize,h.outerSize,d/h.batchSize,h.sliceSize],y=n.bufferSync(m),x=n.bufferSync(f),A=pS(x,y,g);return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),n.makeTensorInfo(h.outputShape,A.dtype,A.values)}var CZ={kernelName:el,backendName:"cpu",kernelFunc:IZ};function TZ(e){let{inputs:t,backend:n}=e,{input:r}=t,s=w.sizeFromShape(r.shape),a=r.shape[r.shape.length-1],o=s/a,i=$t({inputs:{x:r},backend:n,attrs:{shape:[o,a]}}),l=KS(i,!0,n),u=$t({inputs:{x:l},backend:n,attrs:{shape:r.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),u}var NZ={kernelName:cm,backendName:"cpu",kernelFunc:TZ},EZ=gt(Zu,e=>Number.isFinite(e)?1:0,"bool"),RZ={kernelName:Zu,backendName:"cpu",kernelFunc:EZ},_Z=gt(Yu,e=>Math.abs(e)===1/0?1:0,"bool"),$Z={kernelName:Yu,backendName:"cpu",kernelFunc:_Z},DZ=gt(Ju,e=>Number.isNaN(e)?1:0,"bool"),PZ={kernelName:Ju,backendName:"cpu",kernelFunc:DZ};function FZ(e){let{backend:t,attrs:n}=e,{start:r,stop:s,num:a}=n,o=yS(r,s,a);return t.makeTensorInfo([o.length],"float32",o)}var OZ={kernelName:dm,backendName:"cpu",kernelFunc:FZ},MZ=gt(Qu,e=>Math.log1p(e)),zZ={kernelName:Qu,backendName:"cpu",kernelFunc:MZ},LZ=Qt((e,t)=>e&&t),BZ=xn(al,LZ,null,"bool"),WZ={kernelName:al,backendName:"cpu",kernelFunc:BZ},VZ=gt(ec,e=>e?0:1,"bool"),UZ={kernelName:ec,backendName:"cpu",kernelFunc:VZ},GZ=Qt((e,t)=>e||t),HZ=xn(sp,GZ,null,"bool"),jZ={kernelName:sp,backendName:"cpu",kernelFunc:HZ};function qZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{depthRadius:a,bias:o,alpha:i,beta:l}=r;Ce(s,"LRN");let u=s.shape[3],c=u-1,p=n.data.get(s.dataId).values,d=w.sizeFromShape(s.shape),h=new Float32Array(d);function f(m){let g=m%u,y=m-g+Math.max(0,g-a),x=m-g+Math.min(g+a,c),A=0;for(;y<=x;y++){let b=p[y];A+=b*b}return A}for(let m=0;m<d;m++){let g=f(m),y=p[m]*Math.pow(o+i*g,-l);h[m]=y}return n.makeTensorInfo(s.shape,s.dtype,h)}var XZ={kernelName:ap,backendName:"cpu",kernelFunc:qZ};function KZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,y:a,dy:o}=t,{depthRadius:i,bias:l,alpha:u,beta:c}=r;Ce(o,"LRNGrad");let p=w.sizeFromShape(o.shape),d=o.shape[3],h=n.data.get(o.dataId).values,f=n.data.get(s.dataId).values,m=n.data.get(a.dataId).values,g=new Float32Array(p),y=p;for(let x=0;x<y;x++){let A=x%d,b=x-A+Math.max(0,A-i),v=x-A+Math.min(d,A+i+1),S=0;for(let I=b;I<v;I++)S+=Math.pow(f[I],2);S=u*S+l;for(let I=b;I<v;I++){let E=-2*u*c*f[I]*m[x]/S;x===I&&(E+=Math.pow(S,-c)),E*=h[x],g[I]+=E}}return n.makeTensorInfo(o.shape,s.dtype,g)}var ZZ={kernelName:pm,backendName:"cpu",kernelFunc:KZ};function ZS(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reductionIndices:a,keepDims:o}=r,i=n,l=s.shape,u=l.length,c=w.parseAxisParam(a,l),p=c,d=C.getAxesPermutation(p,u),h=i.data.get(s.dataId).values;if(d!=null){let b=new Array(u);for(let v=0;v<b.length;v++)b[v]=l[d[v]];h=e3(h,l,s.dtype,d,b),p=C.getInnerMostAxes(p.length,u),l=b}Ce(s,"max"),C.assertAxesAreInnerMostDims("max",p,u);let[f,m]=C.computeOutAndReduceShapes(l,p),g=w.sizeFromShape(m),y=xS(h,g,f,s.dtype),x=i.write(y,f,s.dtype),A=f;return o&&(A=C.expandShapeToKeepDim(f,c)),{dataId:x,shape:A,dtype:s.dtype}}var YZ={kernelName:xo,backendName:"cpu",kernelFunc:ZS};function JZ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t;Ce(s,"maxPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=r,u=1;w.assert(C.eitherStridesOrDilationsAreOne(o,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${u}'`);let c=C.computePool2DInfo(s.shape,a,o,u,i,l),p;if(c.filterWidth===1&&c.filterHeight===1&&w.arraysEqual(c.inShape,c.outShape))p=Ps({inputs:{x:s},backend:n});else{let d=n.data.get(s.dataId).values,h=w.computeStrides(s.shape),f=a3(d,s.shape,s.dtype,h,c,"max");p=n.makeTensorInfo(c.outShape,s.dtype,f.values)}return p}var QZ={kernelName:vo,backendName:"cpu",kernelFunc:JZ};function eY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l,dataFormat:u}=r;Ce(s,"maxPool3d");let c=C.computePool3DInfo(s.shape,a,o,1,i,l,u),p=n.data.get(s.dataId).values,d=jS(p,s.shape,s.dtype,w.computeStrides(s.shape),c,"max");return n.makeTensorInfo(d.shape,"float32",d.values)}var tY={kernelName:op,backendName:"cpu",kernelFunc:eY};function nY(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,{filterSize:o,strides:i,pad:l,dimRoundingMode:u}=r;Ce([s,a],"maxPool3DGrad");let c=C.computePool3DInfo(a.shape,o,i,1,l,u),p=n.bufferSync(a),d=UX(p,c),h=c.strideDepth,f=c.strideHeight,m=c.strideWidth,g=c.dilationDepth,y=c.dilationHeight,x=c.dilationWidth,A=c.effectiveFilterDepth,b=c.effectiveFilterHeight,v=c.effectiveFilterWidth,S=A-1-c.padInfo.front,I=v-1-c.padInfo.left,E=b-1-c.padInfo.top,R=We(a.shape,"float32"),P=n.bufferSync(s);for(let _=0;_<c.batchSize;++_)for(let D=0;D<c.inChannels;++D)for(let T=0;T<c.inDepth;++T)for(let F=0;F<c.inHeight;++F)for(let U=0;U<c.inWidth;++U){let X=T-S,z=F-E,Z=U-I,W=0;for(let ee=0;ee<A;ee+=g){let Q=(X+ee)/h;if(!(Q<0||Q>=c.outDepth||Math.floor(Q)!==Q))for(let ae=0;ae<b;ae+=y){let J=(z+ae)/f;if(!(J<0||J>=c.outHeight||Math.floor(J)!==J))for(let se=0;se<v;se+=x){let ie=(Z+se)/m;if(ie<0||ie>=c.outWidth||Math.floor(ie)!==ie)continue;let me=A*b*v-1-d.get(_,Q,J,ie,D),be=ee*b*v+ae*v+se,Ee=me===be?1:0;if(Ee===0)continue;W+=P.get(_,Q,J,ie,D)*Ee}}}R.set(W,_,T,F,U,D)}return n.makeTensorInfo(R.shape,R.dtype,R.values)}var rY={kernelName:fm,backendName:"cpu",kernelFunc:nY};function sY(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a,output:o}=t,i=a;Ce([a,o],"maxPoolGrad");let{filterSize:l,strides:u,pad:c,dimRoundingMode:p}=r,d=C.computePool2DInfo(i.shape,l,u,1,c,p),h=n.data.get(i.dataId).values,f=We(d.outShape,i.dtype,HS(h,i.shape,i.dtype,d).values),m=d.strideHeight,g=d.strideWidth,y=d.dilationHeight,x=d.dilationWidth,A=d.effectiveFilterHeight,b=d.effectiveFilterWidth,v=b-1-d.padInfo.left,S=A-1-d.padInfo.top,I=We(i.shape,"float32"),E=n.data.get(s.dataId).values,R=We(s.shape,"float32",E);for(let P=0;P<d.batchSize;++P)for(let _=0;_<d.inChannels;++_)for(let D=0;D<d.inHeight;++D)for(let T=0;T<d.inWidth;++T){let F=D-S,U=T-v,X=0;for(let z=0;z<A;z+=y){let Z=(F+z)/m;if(!(Z<0||Z>=d.outHeight||Math.floor(Z)!==Z))for(let W=0;W<b;W+=x){let ee=(U+W)/g;if(ee<0||ee>=d.outWidth||Math.floor(ee)!==ee)continue;let Q=A*b-1-f.get(P,Z,ee,_),ae=z*b+W,J=Q===ae?1:0;if(J===0)continue;X+=R.get(P,Z,ee,_)*J}}I.set(X,P,D,T,_)}return n.makeTensorInfo(I.shape,I.dtype,I.values)}var aY={kernelName:hm,backendName:"cpu",kernelFunc:sY};function oY(e,t,n,r,s){let a=w.computeStrides(t),o=a3(e,t,n,a,s,"max"),i=HS(e,t,n,s,!0,r);return[o.values,i.values]}var iY={kernelName:mm,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:r}=e,{filterSize:s,strides:a,pad:o,includeBatchInIndex:i}=t,l=n;Ce(r,"MaxPoolWithArgmax");let u=l.data.get(r.dataId).values,c=C.computePool2DInfo(r.shape,s,a,[1,1],o),[p,d]=oY(u,r.shape,r.dtype,i,c),h=l.write(p,c.outShape,r.dtype),f=l.write(d,c.outShape,r.dtype);return[{dataId:h,shape:c.outShape,dtype:r.dtype},{dataId:f,shape:c.outShape,dtype:"int32"}]}};function lY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=w.parseAxisParam(a,s.shape),u=C.computeOutAndReduceShapes(s.shape,i)[1],c=w.sizeFromShape(u),p=[],d=n.makeTensorInfo([],"float32",new Float32Array([c]));p.push(d);let h=qa({inputs:{x:s},backend:n,attrs:{dtype:"float32"}});p.push(h);let f=o3({inputs:{a:h,b:d},backend:n});p.push(f);let m=Mp({inputs:{x:f},backend:n,attrs:{axis:a,keepDims:o}});return p.forEach(g=>n.disposeIntermediateTensorInfo(g)),m}var uY={kernelName:wo,backendName:"cpu",kernelFunc:lY};function cY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r;Ce(s,"min");let i=w.parseAxisParam(a,s.shape),l=i,u=C.getAxesPermutation(l,s.shape.length),c=s;u!=null&&(c=ar({inputs:{x:s},backend:n,attrs:{perm:u}}),l=C.getInnerMostAxes(l.length,s.shape.length)),C.assertAxesAreInnerMostDims("min",l,c.shape.length);let[p,d]=C.computeOutAndReduceShapes(c.shape,l),h=w.sizeFromShape(d),f=w.makeZerosTypedArray(w.sizeFromShape(p),c.dtype),m=n.data.get(c.dataId).values;for(let y=0;y<f.length;++y){let x=y*h,A=m[x];for(let b=0;b<h;++b){let v=m[x+b];(Number.isNaN(v)||v<A)&&(A=v)}f[y]=A}u!=null&&n.disposeIntermediateTensorInfo(c);let g=n.makeTensorInfo(p,c.dtype,f);if(o){let y=C.expandShapeToKeepDim(p,i),x=$t({inputs:{x:g},backend:n,attrs:{shape:y}});return n.disposeIntermediateTensorInfo(g),x}return g}var dY={kernelName:ko,backendName:"cpu",kernelFunc:cY};function pY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{paddings:a,mode:o}=r;Ce(s,"mirrorPad");let i=a.map((A,b)=>A[0]+s.shape[b]+A[1]),l=a.map(A=>A[0]),u=a.map((A,b)=>A[0]+s.shape[b]),c=o==="reflect"?0:1,p=n.data.get(s.dataId).values,d=s.shape.length,h=w.computeStrides(s.shape),f=w.sizeFromShape(i),m=i.length,g=w.computeStrides(i),y=w.getTypedArrayFromDType(s.dtype,f);for(let A=0;A<f;A++){let b=w.indexToLoc(A,m,g);for(let S=0;S<m;S++)b[S]<l[S]?b[S]=l[S]*2-b[S]-c:b[S]>=u[S]&&(b[S]=(u[S]-1)*2-b[S]+c);b=b.map((S,I)=>S-l[I]);let v=w.locToIndex(b,d,h);y[A]=p[v]}return{dataId:n.write(y,i,s.dtype),shape:i,dtype:s.dtype}}var hY={kernelName:Io,backendName:"cpu",kernelFunc:pY},fY=Qt((e,t)=>{let n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t}),mY=xn(tc,fY),gY={kernelName:tc,backendName:"cpu",kernelFunc:mY},yY=Vi(Xf());function YS(e){let{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{dim:a}=r,o=s.shape.length,i=a;if(i===-1&&(i=o-1),i!==o-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${o} and dim was ${i}`);let l=w.parseAxisParam([i],s.shape),u=ZS({inputs:{x:s},backend:n,attrs:{reductionIndices:l,keepDims:!1}}),c=C.expandShapeToKeepDim(u.shape,l),p=$t({inputs:{x:u},backend:n,attrs:{shape:c}}),d=r3({inputs:{a:s,b:p},backend:n}),h=lS({inputs:{x:d},backend:n}),f=Mp({inputs:{x:h},backend:n,attrs:{axis:l,keepDims:!1}}),m=$t({inputs:{x:f},backend:n,attrs:{shape:c}}),g=o3({inputs:{a:h,b:m},backend:n});return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(m),g}var AY={kernelName:Lo,backendName:"cpu",kernelFunc:YS};function xY(e){let{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{numSamples:a,seed:o,normalized:i}=r;Ce(s,"multinomial");let l=i?s:YS({inputs:{logits:s},backend:n,attrs:{dim:-1}}),u=l.shape[0],c=l.shape[1],p=n.data.get(l.dataId).values,d=[u,a],h=w.makeZerosTypedArray(w.sizeFromShape(d),"int32");for(let f=0;f<u;++f){let m=f*c,g=new Float32Array(c-1);g[0]=p[m];for(let A=1;A<g.length;++A)g[A]=g[A-1]+p[m+A];let y=yY.alea(o.toString()),x=f*a;for(let A=0;A<a;++A){let b=y();h[x+A]=g.length;for(let v=0;v<g.length;v++)if(b<g[v]){h[x+A]=v;break}}}return i||n.disposeIntermediateTensorInfo(l),n.makeTensorInfo(d,"int32",h)}var bY={kernelName:gm,backendName:"cpu",kernelFunc:xY},vY=Kr.nonMaxSuppressionV3Impl;function wY(e){let{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:l}=r;Ce(s,"NonMaxSuppression");let u=n.data.get(s.dataId).values,c=n.data.get(a.dataId).values,{selectedIndices:p}=vY(u,c,o,i,l);return n.makeTensorInfo([p.length],"int32",new Int32Array(p))}var kY={kernelName:ll,backendName:"cpu",kernelFunc:wY},SY=Kr.nonMaxSuppressionV4Impl;function IY(e){let{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:l,padToMaxOutputSize:u}=r;Ce(s,"NonMaxSuppressionPadded");let c=n.data.get(s.dataId).values,p=n.data.get(a.dataId).values,{selectedIndices:d,validOutputs:h}=SY(c,p,o,i,l,u);return[n.makeTensorInfo([d.length],"int32",new Int32Array(d)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}var CY={kernelName:nc,backendName:"cpu",kernelFunc:IY},TY=Kr.nonMaxSuppressionV5Impl;function NY(e){let{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:l,softNmsSigma:u}=r;Ce(s,"NonMaxSuppressionWithScore");let c=n.data.get(s.dataId).values,p=n.data.get(a.dataId).values,d=o,h=i,f=l,m=u,{selectedIndices:g,selectedScores:y}=TY(c,p,d,h,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var EY={kernelName:ul,backendName:"cpu",kernelFunc:NY};function RY(e){let{inputs:t,backend:n,attrs:r}=e,{indices:s}=t,{depth:a,onValue:o,offValue:i}=r;Ce(s,"oneHot");let l=w.sizeFromShape(s.shape),u=new Float32Array(l*a);u.fill(i);let c=n.data.get(s.dataId).values;for(let p=0;p<l;++p)c[p]>=0&&c[p]<a&&(u[p*a+c[p]]=o);return n.makeTensorInfo([...s.shape,a],"int32",u)}var _Y={kernelName:dl,backendName:"cpu",kernelFunc:RY};function Vf(e){let{inputs:t,backend:n}=e,{x:r}=t;if(r.dtype==="string")throw new Error("zerosLike is not supported for string tensors");if(r.dtype==="complex64"){let s=Mi({inputs:{input:r},backend:n}),a=Vf({inputs:{x:s},backend:n}),o=Du({inputs:{input:r},backend:n}),i=Vf({inputs:{x:o},backend:n}),l=mr({inputs:{real:a,imag:i},backend:n});return n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),l}else return i3({backend:n,attrs:{shape:r.shape,value:0,dtype:r.dtype}})}var $Y={kernelName:Tl,backendName:"cpu",kernelFunc:Vf};function JS(e){let{inputs:t,backend:n}=e,{x:r}=t;if(r.dtype==="string")throw new Error("onesLike is not supported for string tensors");if(r.dtype==="complex64"){let s=Mi({inputs:{input:r},backend:n}),a=JS({inputs:{x:s},backend:n}),o=Du({inputs:{input:r},backend:n}),i=Vf({inputs:{x:o},backend:n}),l=mr({inputs:{real:a,imag:i},backend:n});return n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),l}else return i3({backend:n,attrs:{shape:r.shape,value:1,dtype:r.dtype}})}var DY={kernelName:cl,backendName:"cpu",kernelFunc:JS};function QS(e){let{inputs:t,backend:n,attrs:r}=e,{axis:s}=r;if(t.length===1)return Wf({inputs:{input:t[0]},backend:n,attrs:{dim:s}});let a=t[0].shape,o=t[0].dtype;t.forEach(c=>{w.assertShapesMatch(a,c.shape,"All tensors passed to stack must have matching shapes"),w.assert(o===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=t.map(c=>{let p=Wf({inputs:{input:c},backend:n,attrs:{dim:s}});return i.push(p),p}),u=Pu({inputs:l,backend:n,attrs:{axis:s}});return i.forEach(c=>n.disposeIntermediateTensorInfo(c)),u}var PY={kernelName:pl,backendName:"cpu",kernelFunc:QS};function FY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{paddings:a,constantValue:o}=r;Ce(s,"pad");let i=a.map((x,A)=>x[0]+s.shape[A]+x[1]),l=a.map(x=>x[0]),u=n.data.get(s.dataId).values,c=w.sizeFromShape(s.shape),p=s.shape.length,d=w.computeStrides(s.shape),h=w.sizeFromShape(i),f=i.length,m=w.computeStrides(i),g=w.getTypedArrayFromDType(s.dtype,h);o!==0&&g.fill(o);for(let x=0;x<c;x++){let b=w.indexToLoc(x,p,d).map((S,I)=>S+l[I]),v=w.locToIndex(b,f,m);g[v]=u[x]}return{dataId:n.write(g,i,s.dtype),shape:i,dtype:s.dtype}}var eI={kernelName:To,backendName:"cpu",kernelFunc:FY},OY=Qt((e,t)=>Math.pow(e,t)),MY=xn(No,OY),zY={kernelName:No,backendName:"cpu",kernelFunc:MY};function LY(e){let{backend:t,attrs:n}=e,{start:r,stop:s,dtype:a,step:o}=n,i=t3(r,s,o,a);return t.makeTensorInfo([i.length],a,i)}var BY={kernelName:rc,backendName:"cpu",kernelFunc:LY},WY=gt(sc,e=>1/e),VY={kernelName:sc,backendName:"cpu",kernelFunc:WY};function UY(e){let{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:o,size:i}=r;Ce(s,"resizeBilinear");let l=w.computeStrides(s.shape),[u,c]=i,[p,d,h,f]=s.shape,m=n.data.get(s.dataId).values,g=new Float32Array(w.sizeFromShape([p,u,c,f])),y=[a&&u>1?d-1:d,a&&c>1?h-1:h],x=[a&&u>1?u-1:u,a&&c>1?c-1:c],A=0,b=y[0]/x[0],v=y[1]/x[1];for(let S=0;S<p;S++)for(let I=0;I<u;I++){let E;o?E=b*(I+.5)-.5:E=b*I;let R=Math.max(0,Math.floor(E)),P=E-R,_=Math.min(d-1,Math.ceil(E)),D=S*l[0]+R*l[1],T=S*l[0]+_*l[1];for(let F=0;F<c;F++){let U;o?U=v*(F+.5)-.5:U=v*F;let X=Math.max(0,Math.floor(U)),z=U-X,Z=Math.min(h-1,Math.ceil(U)),W=D+X*l[2],ee=T+X*l[2],Q=D+Z*l[2],ae=T+Z*l[2];for(let J=0;J<f;J++){let se=m[W+J],ie=m[ee+J],me=m[Q+J],be=m[ae+J],Ee=se+(me-se)*z,Re=ie+(be-ie)*z,ze=Ee+(Re-Ee)*P;g[A++]=ze}}}return n.makeTensorInfo([p,u,c,f],"float32",g)}var GY={kernelName:$o,backendName:"cpu",kernelFunc:UY};function HY(e){let{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:o}=r;Ce([a,s],"resizeBilinearGrad");let i=w.computeStrides(s.shape),[l,u,c,p]=s.shape,[,d,h]=a.shape,f=new Float32Array(l*u*c*p),m=[o&&d>1?u-1:u,o&&h>1?c-1:c],g=[o&&d>1?d-1:d,o&&h>1?h-1:h],y=m[0]/g[0],x=m[1]/g[1],A=n.data.get(a.dataId).values,b=0;for(let v=0;v<l;v++){let S=v*i[0];for(let I=0;I<d;I++){let E=I*y,R=Math.floor(E),P=Math.min(Math.ceil(E),u-1),_=S+R*i[1],D=S+P*i[1],T=E-R,F=1-T;for(let U=0;U<h;U++){let X=U*x,z=Math.floor(X),Z=Math.min(Math.ceil(X),c-1),W=X-z,ee=1-W,Q=_+z*i[2],ae=_+Z*i[2],J=D+z*i[2],se=D+Z*i[2],ie=F*ee,me=F*W,be=T*ee,Ee=T*W;for(let Re=0;Re<p;Re++){let ze=A[b++];f[Q+Re]+=ze*ie,f[ae+Re]+=ze*me,f[J+Re]+=ze*be,f[se+Re]+=ze*Ee}}}}return n.makeTensorInfo([l,c,u,p],"float32",f)}var jY={kernelName:Am,backendName:"cpu",kernelFunc:HY};function qY(e){let{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:o,size:i}=r;Ce(s,"resizeNearestNeighbor");let l=w.computeStrides(s.shape),[u,c]=i,[p,d,h,f]=s.shape,m=n.data.get(s.dataId).values,g=new Float32Array(p*u*c*f),y=[a&&u>1?d-1:d,a&&c>1?h-1:h],x=[a&&u>1?u-1:u,a&&c>1?c-1:c],A=y[0]/x[0],b=y[1]/x[1],v=0;for(let S=0;S<p;S++){let I=S*l[0];for(let E=0;E<u;E++){let R=o?A*(E+.5):A*E,P=Math.min(d-1,a?Math.round(R):Math.floor(R));o&&(P=Math.max(0,P));let _=I+P*l[1];for(let D=0;D<c;D++){let T=o?b*(D+.5):b*D,F=Math.min(h-1,a?Math.round(T):Math.floor(T));o&&(F=Math.max(0,F));let U=_+F*l[2];for(let X=0;X<f;X++){let z=m[U+X];g[v++]=z}}}}return n.makeTensorInfo([p,u,c,f],s.dtype,g)}var XY={kernelName:ac,backendName:"cpu",kernelFunc:qY};function KY(e){let{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:o}=r;Ce([a,s],"resizeNearestNeighborGrad");let i=w.computeStrides(s.shape),l=w.computeStrides(a.shape),[u,c,p,d]=s.shape,[,h,f]=a.shape,m=new Float32Array(u*c*p*d),g=n.data.get(a.dataId).values,y=[o&&h>1?c-1:c,o&&f>1?p-1:p],x=[o&&h>1?h-1:h,o&&f>1?f-1:f],A=y[0]/x[0],b=y[1]/x[1],v=1/A,S=1/b,I=Math.ceil(v)*2+2,E=Math.ceil(S)*2+2;for(let R=0;R<u;R++){let P=R*i[0];for(let _=0;_<c;_++){let D=P+_*i[1],T=Math.floor(_*v),F=Math.floor(T-I/2);for(let U=0;U<p;U++){let X=D+U*i[2],z=Math.floor(U*S),Z=Math.floor(z-E/2);for(let W=0;W<d;W++){let ee=0;for(let Q=0;Q<I;Q++){let ae=Q+F;if(ae<0||ae>=h)continue;let J=P+ae*l[1],se=ae*A,ie=Math.min(c-1,o?Math.round(se):Math.floor(se));if(_===ie)for(let me=0;me<E;me++){let be=me+Z;if(be<0||be>=f)continue;let Ee=J+be*l[2],Re=be*b,ze=Math.min(p-1,o?Math.round(Re):Math.floor(Re));U===ze&&(ee+=g[Ee+W])}}m[X+W]=ee}}}}return n.makeTensorInfo(s.shape,s.dtype,m)}var ZY={kernelName:ym,backendName:"cpu",kernelFunc:KY};function YY(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dims:a}=r;Ce(s,"reverse");let o=s.shape.length,i=w.parseAxisParam(a,s.shape);if(o===0)return Ps({inputs:{x:s},backend:n});let l=new on(s.shape,s.dtype),u=n.bufferSync(s);for(let c=0;c<l.size;c++){let p=l.indexToLoc(c),d=p.slice();i.forEach(h=>d[h]=s.shape[h]-1-d[h]),l.set(u.get(...d),...p)}return n.makeTensorInfo(l.shape,l.dtype,l.values)}var JY={kernelName:fl,backendName:"cpu",kernelFunc:YY},QY={kernelName:Nl,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:r}=e,{radians:s,fillValue:a,center:o}=t,i=n,l=w.getTypedArrayFromDType(r.dtype,w.sizeFromShape(r.shape)),[u,c,p,d]=r.shape,[h,f]=C.getImageCenter(o,c,p),m=255,g=Math.sin(s),y=Math.cos(s),x=i.data.get(r.dataId).values;for(let b=0;b<u;b++){let v=b*p*c*d;for(let S=0;S<c;S++){let I=S*(p*d);for(let E=0;E<p;E++){let R=E*d;for(let P=0;P<d;P++){let _=[u,S,E,P],D=_[2],T=_[1],F=(D-h)*y-(T-f)*g,U=(D-h)*g+(T-f)*y;F=Math.round(F+h),U=Math.round(U+f);let X=a;if(typeof a!="number"&&(P===3?X=m:X=a[P]),F>=0&&F<p&&U>=0&&U<c){let Z=U*(p*d),W=F*d,ee=v+Z+W+P;X=x[ee]}let z=v+I+R+P;l[z]=X}}}}return{dataId:i.write(l,r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},eJ=gt(ml,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}),tJ={kernelName:ml,backendName:"cpu",kernelFunc:eJ};function tI(e,t,n,r,s,a,o,i,l,u){let c=[r/s,s],p=e.values,d=t.values;if(r===0)return We(n,t.dtype);let h=We(c,t.dtype);h.values.fill(l);for(let f=0;f<a;f++){let m=[],g=0;for(let y=0;y<o;y++){let x=p[f*o+y];m.push(x),g+=x*i[y]}if(g<0||g>=r/s)throw new Error(`Invalid indices: ${m} does not index into ${n}`);for(let y=0;y<s;y++)u?h.values[g*s+y]+=d[f*s+y]:h.values[g*s+y]=t.rank===0?d[0]:d[f*s+y]}return h}function nJ(e){let{inputs:t,backend:n,attrs:r}=e,{indices:s,updates:a}=t,{shape:o}=r,{sliceRank:i,numUpdates:l,sliceSize:u,strides:c,outputSize:p}=C.calculateShapes(a,s,o),d=!0,h=n.bufferSync(s),f=n.bufferSync(a),m=tI(h,f,o,p,u,l,i,c,0,d);return n.makeTensorInfo(o,m.dtype,m.values)}var rJ={kernelName:gl,backendName:"cpu",kernelFunc:nJ};function sJ(e){let{inputs:t,backend:n}=e,{condition:r,t:s,e:a}=t;Ce([r,s,a],"select");let o=r.shape.length,i=n.data.get(r.dataId).values,l=n.data.get(s.dataId).values,u=n.data.get(a.dataId).values,c=Nn(s.dtype,a.dtype),p=w.makeZerosTypedArray(w.sizeFromShape(s.shape),c),d=0,h=o===0||o>1||s.shape.length===1?1:w.sizeFromShape(s.shape.slice(1));for(let f=0;f<i.length;f++)for(let m=0;m<h;m++)i[f]===1?p[d++]=l[f]:p[d++]=u[f];return n.makeTensorInfo(s.shape,c,p)}var aJ={kernelName:yl,backendName:"cpu",kernelFunc:sJ},oJ=C.SELU_SCALEALPHA,iJ=C.SELU_SCALE,lJ=gt(oc,e=>e>=0?iJ*e:oJ*(Math.exp(e)-1)),uJ={kernelName:oc,backendName:"cpu",kernelFunc:lJ},cJ=gt(ic,e=>e<0?-1:e>0?1:0),dJ={kernelName:ic,backendName:"cpu",kernelFunc:cJ},pJ=gt(Fo,e=>Math.sin(e)),hJ={kernelName:Fo,backendName:"cpu",kernelFunc:pJ},fJ=gt(xl,e=>Math.sinh(e)),mJ={kernelName:xl,backendName:"cpu",kernelFunc:fJ},gJ=11920928955078125e-23,_v=Math.log(gJ)+2,yJ=gt(lc,e=>{let t=e>-_v,n=e<_v,r=Math.exp(e),s;return n?s=r:t?s=e:s=Math.log(1+r),s}),AJ={kernelName:lc,backendName:"cpu",kernelFunc:yJ};function xJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,paddings:o}=r;Ce([s],"spaceToBatchND");let i=w.sizeFromShape(a),l=[[0,0]];l.push(...o);for(let S=1+a.length;S<s.shape.length;++S)l.push([0,0]);let u=eI.kernelFunc({inputs:{x:s},backend:n,attrs:{paddings:l,constantValue:0}}),c=C.getReshaped(u.shape,a,i,!1),p=C.getPermuted(c.length,a.length,!1),d=C.getReshapedPermuted(u.shape,a,i,!1),m=$t({inputs:{x:u},backend:n,attrs:{shape:c}}),x=ar({inputs:{x:m},backend:n,attrs:{perm:p}}),v=$t({inputs:{x},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(x),v}var bJ={kernelName:bl,backendName:"cpu",kernelFunc:xJ};function vJ(e){let{inputs:t,backend:n}=e,{indices:r,values:s,denseShape:a,defaultValue:o}=t;if(a.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
|
|
${a.shape}`);if(r.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
|
|
${r.shape}`);if(s.shape.length!==1)throw new Error(`Values must be a vector, saw:
|
|
${s.shape}`);if(o.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
|
|
${o.shape}`);let i=n.data.get(r.dataId).values,l=n.data.get(s.dataId).values,u=n.data.get(a.dataId).values,c=n.data.get(o.dataId).values[0],[p,d,h,f,m]=TS(i,r.shape,r.dtype,l,s.dtype,u,c);return[n.makeTensorInfo(d,r.dtype,p),n.makeTensorInfo([d[0]],s.dtype,h),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),n.makeTensorInfo([m.length],r.dtype,new Int32Array(m))]}var wJ={kernelName:lp,backendName:"cpu",kernelFunc:vJ};function kJ(e){let{inputs:t,backend:n}=e,{inputIndices:r,inputShape:s,newShape:a}=t;if(r.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
|
|
${r.shape}`);if(s.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
|
|
${s.shape}`);if(a.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);let o=Array.from(n.data.get(s.dataId).values),i=n.data.get(r.dataId).values,l=Array.from(n.data.get(a.dataId).values),[u,c,p]=NS(i,r.shape,r.dtype,o,l);return[n.makeTensorInfo(c,r.dtype,u),n.makeTensorInfo([p.length],a.dtype,new Int32Array(p))]}var SJ={kernelName:uc,backendName:"cpu",kernelFunc:kJ};function IJ(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${s.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${a.shape}`);if(s.shape[0]!==a.shape[0])throw new Error("segmentIds and indices should have same size.");let o=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values,l=n.data.get(a.dataId).values,[u,c]=n3(o,r.shape,r.dtype,i,l,!0);return n.makeTensorInfo(c,r.dtype,u)}var CJ={kernelName:up,backendName:"cpu",kernelFunc:IJ};function TJ(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${s.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${a.shape}`);if(s.shape[0]!==a.shape[0])throw new Error("segmentIds and indices should have same size.");let o=n.data.get(r.dataId).values,i=n.data.get(s.dataId).values,l=n.data.get(a.dataId).values,[u,c]=n3(o,r.shape,r.dtype,i,l);return n.makeTensorInfo(c,r.dtype,u)}var NJ={kernelName:cp,backendName:"cpu",kernelFunc:TJ};function EJ(e){let{inputs:t,backend:n,attrs:r}=e,{sparseIndices:s,sparseValues:a,defaultValue:o}=t,{outputShape:i}=r,{sliceRank:l,numUpdates:u,sliceSize:c,strides:p,outputSize:d}=C.calculateShapes(a,s,i),h=!1,f=n.bufferSync(s),m=n.bufferSync(a),g=n.data.get(o.dataId).values[0],y=tI(f,m,i,d,c,u,l,p,g,h);return n.makeTensorInfo(i,y.dtype,y.values)}var RJ={kernelName:dp,backendName:"cpu",kernelFunc:EJ};function _J(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{numOrSizeSplits:a,axis:o}=r,i=w.parseAxisParam(o,s.shape)[0],l=C.prepareSplitSize(s,a,i),u=new Array(s.shape.length).fill(0),c=s.shape.slice();return l.map(p=>{let d=[...c];d[i]=p;let h=zi({inputs:{x:s},backend:n,attrs:{begin:u,size:d}});return u[i]+=p,h})}var $J={kernelName:vl,backendName:"cpu",kernelFunc:_J},DJ={kernelName:cc,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{let{x:n}=e,r=t;Ce(n,"square");let s=r.data.get(n.dataId).values,a=new Float32Array(s.length);for(let i=0;i<s.length;++i){let l=s[i];a[i]=l*l}return{dataId:r.write(a,n.shape,n.dtype),shape:n.shape,dtype:n.dtype}}},PJ=gt(Go,(e,t)=>{let n=t;return isNaN(e)?NaN:e>0?1:n.alpha}),FJ={kernelName:Go,backendName:"cpu",kernelFunc:PJ};function OJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,end:o,strides:i,beginMask:l,endMask:u,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:d}=r;Ce(s,"stridedSlice");let{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:x,end:A,strides:b}=Mt.sliceInfo(s.shape,a,o,i,l,u,c,p,d),v;if(m)v=$t({inputs:{x:s},backend:n,attrs:{shape:f}});else if(g||y){w.assert(s.shape.length>=1,()=>`Input must have rank at least 1, got: ${s.shape.length}`);let S=Mt.computeOutShape(x,A,b),I=zi({inputs:{x:s},backend:n,attrs:{begin:x,size:S}});v=$t({inputs:{x:I},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(I)}else{let S=n.bufferSync(s),I=RS(h,S,b,x);v=n.makeTensorInfo(f,I.dtype,I.values)}return v}var MJ={kernelName:wl,backendName:"cpu",kernelFunc:OJ};function zJ(e){let{inputs:t,backend:n,attrs:r}=e,{separator:s,nGramWidths:a,leftPad:o,rightPad:i,padWidth:l,preserveShortSequences:u}=r,{data:c,dataSplits:p}=t,d=n.data.get(c.dataId).values,h=n.data.get(p.dataId).values,[f,m]=_S(d,h,s,a,o,i,l,u);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(p.shape,"int32",m)]}var LJ={kernelName:pp,backendName:"cpu",kernelFunc:zJ};function BJ(e){let{inputs:t,backend:n,attrs:r}=e,{skipEmpty:s}=r,{input:a,delimiter:o}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(a.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(o.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${o.shape}`);let i=n.data.get(a.dataId).values,l=n.data.get(o.dataId).values[0],[u,c,p]=$S(i,l,s),d=c.length;return[n.makeTensorInfo([d,2],"int32",u),n.makeTensorInfo([d],"string",c),n.makeTensorInfo([2],"int32",new Int32Array(p))]}var WJ={kernelName:xm,backendName:"cpu",kernelFunc:BJ};function VJ(e){let{inputs:t,backend:n,attrs:r}=e,{numBuckets:s}=r,{input:a}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(s<=0)throw new Error("Number of buckets must be at least 1");let o=n.data.get(a.dataId).values,i=DS(o,s);return n.makeTensorInfo(a.shape,"int32",i)}var UJ={kernelName:bm,backendName:"cpu",kernelFunc:VJ},GJ=gt(kl,e=>Math.tan(e)),HJ={kernelName:kl,backendName:"cpu",kernelFunc:GJ},jJ=gt(Vo,e=>Math.tanh(e)),qJ={kernelName:Vo,backendName:"cpu",kernelFunc:jJ};function XJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reps:a}=r;Ce(s,"tile");let o=FS(n.bufferSync(s),a);return n.makeTensorInfo(o.shape,o.dtype,o.values)}var KJ={kernelName:na,backendName:"cpu",kernelFunc:XJ};function ZJ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{k:a,sorted:o}=r;Ce(s,"topk");let i=n.data.get(s.dataId).values,[l,u]=MS(i,s.shape,s.dtype,a,o);return[n.makeTensorInfo(l.shape,l.dtype,l.values),n.makeTensorInfo(u.shape,u.dtype,u.values)]}var YJ={kernelName:Sl,backendName:"cpu",kernelFunc:ZJ};function JJ(e){let{inputs:t,attrs:n,backend:r}=e,{image:s,transforms:a}=t,{interpolation:o,fillMode:i,fillValue:l,outputShape:u}=n,[c,p,d,h]=s.shape,[f,m]=u!=null?u:[p,d],g=[c,f,m,h],y=w.computeStrides(s.shape),x=y[0],A=y[1],b=y[2],v=w.getTypedArrayFromDType(s.dtype,w.sizeFromShape(g));v.fill(l);let S=r.data.get(s.dataId).values,I=r.data.get(a.dataId).values;for(let R=0;R<c;++R){let P=a.shape[0]===1?I:I.subarray(R*8,R*8+8);for(let _=0;_<f;++_)for(let D=0;D<m;++D)for(let T=0;T<h;++T){let F,U=P[6]*D+P[7]*_+1;if(U===0)continue;let X=(P[0]*D+P[1]*_+P[2])/U,z=(P[3]*D+P[4]*_+P[5])/U,Z=$v(X,d,i),W=$v(z,p,i);switch(o){case"nearest":F=sQ(S,p,d,x,A,b,R,W,Z,T,l);break;case"bilinear":F=aQ(S,p,d,x,A,b,R,W,Z,T,l);break;default:throw new Error(`Error in Transform: Expect 'nearest' or 'bilinear', but got ${o}`)}let ee=R*x+_*A+D*b+T;v[ee]=F}return r.makeTensorInfo(g,s.dtype,v)}return{dataId:r.write(v,g,s.dtype),shape:s.shape,dtype:s.dtype}}var QJ={kernelName:Il,backendName:"cpu",kernelFunc:JJ};function $v(e,t,n){switch(n){case"reflect":return eQ(e,t);case"wrap":return tQ(e,t);case"nearest":return rQ(e,t);case"constant":default:return nQ(e,t)}}function eQ(e,t){let n=e;if(n<0)if(t<=1)n=0;else{let r=2*t;n<r&&(n=r*Math.trunc(-n/r)+n),n=n<-t?n+r:-n-1}else if(n>t-1)if(t<=1)n=0;else{let r=2*t;n-=r*Math.trunc(n/r),n>=t&&(n=r-n-1)}return w.clamp(0,n,t-1)}function tQ(e,t){let n=e;if(n<0)if(t<=1)n=0;else{let r=t-1;n+=t*(Math.trunc(-n/r)+1)}else if(n>t-1)if(t<=1)n=0;else{let r=t-1;n-=t*Math.trunc(n/r)}return w.clamp(0,n,t-1)}function nQ(e,t){return e}function rQ(e,t){return w.clamp(0,e,t-1)}function Td(e,t,n,r,s,a,o,i,l,u,c){let p=o*r+i*s+l*a+u;return 0<=i&&i<t&&0<=l&&l<n?e[p]:c}function sQ(e,t,n,r,s,a,o,i,l,u,c){let p=Math.round(i),d=Math.round(l);return Td(e,t,n,r,s,a,o,p,d,u,c)}function aQ(e,t,n,r,s,a,o,i,l,u,c){let p=Math.floor(i),d=Math.floor(l),h=p+1,f=d+1,m=(f-l)*Td(e,t,n,r,s,a,o,p,d,u,c)+(l-d)*Td(e,t,n,r,s,a,o,p,f,u,c),g=(f-l)*Td(e,t,n,r,s,a,o,h,d,u,c)+(l-d)*Td(e,t,n,r,s,a,o,h,f,u,c);return(h-i)*m+(i-p)*g}function oQ(e){let{inputs:t,attrs:n,backend:r}=e,{axis:s}=n,{x:a}=t;Ce(a,"unique");let o=r.data.get(a.dataId).values,{outputValues:i,outputShape:l,indices:u}=zS(o,s,a.shape,a.dtype);return[r.makeTensorInfo(l,a.dtype,i),r.makeTensorInfo([u.length],"int32",u)]}var iQ={kernelName:vm,backendName:"cpu",kernelFunc:oQ};function lQ(e){let{inputs:t,backend:n,attrs:r}=e,{value:s}=t,{axis:a}=r;a<0&&(a+=s.shape.length);let o=s.shape.length,i=s.shape[a],l=new Array(o-1),u=0;for(let h=0;h<o;h++)h!==a&&(l[u++]=s.shape[h]);let c=new Array(o).fill(0),p=s.shape.slice();p[a]=1;let d=new Array(i);for(let h=0;h<d.length;h++){c[a]=h;let f=zi({inputs:{x:s},backend:n,attrs:{begin:c,size:p}});d[h]=$t({inputs:{x:f},backend:n,attrs:{shape:l}}),n.disposeIntermediateTensorInfo(f)}return d}var uQ={kernelName:Cl,backendName:"cpu",kernelFunc:lQ};function cQ(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,segmentIds:a}=t,{numSegments:o}=r;Ce(s,"unsortedSegmentSum");let i=s.shape.length,l=a.shape.length,u=[],c=[],p=i-l,d=a;for(let f=0;f<p;++f){let m=Wf({inputs:{input:d},backend:n,attrs:{dim:f+1}});d=m,c.push(m)}for(let f=0;f<o;++f){let m=w.createScalarValue(f,"int32"),g=n.makeTensorInfo([],"int32",m),y=oS({inputs:{a:g,b:d},backend:n}),x=qa({inputs:{x:y},backend:n,attrs:{dtype:"float32"}}),A=b0({inputs:{a:x,b:s},backend:n}),b=Mp({inputs:{x:A},backend:n,attrs:{axis:0,keepDims:!1}});u.push(b),c.push(g),c.push(y),c.push(x),c.push(A),c.push(b)}let h=QS({inputs:u,backend:n,attrs:{axis:0}});return c.forEach(f=>n.disposeIntermediateTensorInfo(f)),h}var dQ={kernelName:hp,backendName:"cpu",kernelFunc:cQ},pQ=[yX,uq,xX,vX,mq,kX,IX,TX,EX,_X,DX,FX,MX,BX,VX,HX,qX,KX,YX,mX,QX,tK,rK,aK,hq,yq,iK,cq,uK,dK,pK,fK,gK,AK,bK,wK,SK,CK,NK,RK,$K,PK,OK,MK,LK,WK,UK,GK,HK,jK,KK,lX,YK,Aq,aZ,xq,oZ,vq,pZ,hZ,mZ,kq,AZ,bZ,wZ,SZ,CZ,Iq,Tq,dq,NZ,cK,RZ,$Z,PZ,uX,Eq,_q,OZ,Dq,zZ,WZ,UZ,jZ,XZ,ZZ,YZ,Fq,QZ,tY,rY,aY,iY,uY,dY,Mq,hY,gY,bY,Lq,Wq,kY,CY,EY,Uq,_Y,DY,PY,eI,zY,dX,jq,BY,pq,Xg,VY,pX,hX,fX,GY,jY,XY,ZY,JY,QY,tJ,Xq,rJ,aJ,uJ,Zq,dJ,hJ,mJ,Yq,AY,AJ,bJ,wJ,SJ,CJ,NJ,RJ,$J,eX,DJ,nX,FJ,MJ,LJ,WJ,UJ,oX,qK,HJ,qJ,KJ,YJ,QJ,Gq,iQ,uQ,dQ,$Y];for(let e of pQ)qr(e);var nI={};Le(nI,{assertNotComplex:()=>Sc,bindCanvasToFramebuffer:()=>kQ,bindColorTextureToFramebuffer:()=>uf,bindTextureToProgramUniformSampler:()=>yI,bindTextureUnit:()=>fI,bindVertexBufferToProgramAttribute:()=>Zg,callAndCheck:()=>we,canBeRepresented:()=>rI,createFragmentShader:()=>oI,createFramebuffer:()=>hI,createProgram:()=>iI,createStaticIndexBuffer:()=>cI,createStaticVertexBuffer:()=>uI,createTexture:()=>dI,createVertexShader:()=>aI,getBatchDim:()=>Li,getExtensionOrThrow:()=>Nd,getFramebufferErrorMessage:()=>AI,getMaxTexturesInShader:()=>wI,getNumChannels:()=>vQ,getProgramUniformLocation:()=>gI,getProgramUniformLocationOrThrow:()=>mI,getRowsCols:()=>Bi,getShapeAs3D:()=>cf,getTextureShapeFromLogicalShape:()=>bI,getWebGLDisjointQueryTimerVersion:()=>kI,getWebGLErrorMessage:()=>sI,getWebGLMaxTextureSize:()=>vI,hasExtension:()=>Er,isCapableOfRenderingToFloatTexture:()=>SI,isDownloadFloatTextureEnabled:()=>II,isReshapeFree:()=>Xd,isWebGLFenceEnabled:()=>CI,isWebGLVersionEnabled:()=>Jg,linkProgram:()=>lI,logShaderSourceAndInfoLog:()=>u3,resetMaxTextureSize:()=>SQ,resetMaxTexturesInShader:()=>IQ,unbindColorTextureFromFramebuffer:()=>Yg,unbindTextureUnit:()=>wQ,validateFramebuffer:()=>Ed,validateProgram:()=>lf,validateTextureSize:()=>pI});var ki={},ug={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function v0(e,t){ki[e]=t}function As(e,t){if(!(e in ki)||t!=null){let r=fQ(e,t);if(r!==null)ki[e]=r;else return console.log("Could not get context for WebGL version",e),null}let n=ki[e];return n==null||n.isContextLost()?(delete ki[e],As(e)):(n.disable(n.DEPTH_TEST),n.disable(n.STENCIL_TEST),n.disable(n.BLEND),n.disable(n.DITHER),n.disable(n.POLYGON_OFFSET_FILL),n.disable(n.SAMPLE_COVERAGE),n.enable(n.SCISSOR_TEST),n.enable(n.CULL_FACE),n.cullFace(n.BACK),ki[e])}function hQ(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 fQ(e,t){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let n=t==null?hQ(e):t;return n.addEventListener("webglcontextlost",r=>{r.preventDefault(),delete ki[e]},!1),e===1?n.getContext("webgl",ug)||n.getContext("experimental-webgl",ug):n.getContext("webgl2",ug)}function zp(e,t){return[t,e]}function mQ(e,t){return e*t}function Qh(e){let t=w.sizeFromShape(e),n=Math.ceil(t/4);return w.sizeToSquarishShape(n)}function kc(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function gQ(e,t){let[n,r]=kc(e,t);return n*r*4}function l3(e,t){let n=e,r,s,a,o,i,l,u,c,p,d;return Y().getNumber("WEBGL_VERSION")===2?(r=n.R32F,s=n.R16F,a=n.RGBA16F,o=n.RGBA32F,i=n.RED,u=4,c=1,p=n.HALF_FLOAT,d=n.FLOAT,l=n.RGBA8):(r=e.RGBA,s=e.RGBA,a=e.RGBA,o=n.RGBA,i=e.RGBA,u=4,c=4,p=t!=null?t.HALF_FLOAT_OES:null,d=e.FLOAT,l=e.RGBA),{internalFormatFloat:r,internalFormatHalfFloat:s,internalFormatPackedHalfFloat:a,internalFormatPackedFloat:o,textureFormatFloat:i,downloadTextureFormat:l,downloadUnpackNumChannels:u,defaultNumChannels:c,textureTypeHalfFloat:p,textureTypeFloat:d}}function we(e,t){let n=t();return Y().getBool("DEBUG")&&yQ(e),n}function yQ(e){let t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+sI(e,t))}var AQ=596e-10,xQ=65504;function rI(e){return!!(Y().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||e===0||AQ<Math.abs(e)&&Math.abs(e)<xQ)}function sI(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 Nd(e,t){return ia(e,()=>e.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function aI(e,t){let n=ia(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(we(e,()=>e.shaderSource(n,t)),we(e,()=>e.compileShader(n)),e.getShaderParameter(n,e.COMPILE_STATUS)===!1)throw console.log(e.getShaderInfoLog(n)),new Error("Failed to compile vertex shader.");return n}function oI(e,t){let n=ia(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(we(e,()=>e.shaderSource(n,t)),we(e,()=>e.compileShader(n)),Y().get("ENGINE_COMPILE_ONLY"))return n;if(e.getShaderParameter(n,e.COMPILE_STATUS)===!1)throw u3(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}var bQ=/ERROR: [0-9]+:([0-9]+):/g;function u3(e,t){let n=bQ.exec(t);if(n==null){console.log(`Couldn't parse line number in error: ${t}`),console.log(e);return}let r=+n[1],s=e.split(`
|
|
`),a=s.length.toString().length+2,o=s.map((p,d)=>w.rightPad((d+1).toString(),a)+p),i=0;for(let p=0;p<o.length;p++)i=Math.max(o[p].length,i);let l=o.slice(0,r-1),u=o.slice(r-1,r),c=o.slice(r);console.log(l.join(`
|
|
`)),console.log(t.split(`
|
|
`)[0]),console.log(`%c ${w.rightPad(u[0],i)}`,"border:1px solid red; background-color:#e3d2d2; color:#a61717"),console.log(c.join(`
|
|
`))}function iI(e){return ia(e,()=>e.createProgram(),"Unable to create WebGLProgram.")}function lI(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 lf(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 uI(e,t){let n=ia(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return we(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),we(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function cI(e,t){let n=ia(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return we(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),we(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function vQ(){return Y().getNumber("WEBGL_VERSION")===2?1:4}function dI(e){return ia(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function pI(e,t){let n=Y().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){let r=`[${e}x${t}]`;throw new Error("Requested texture size "+r+" is invalid.")}if(e>n||t>n){let r=`[${e}x${t}]`,s=`[${n}x${n}]`;throw new Error("Requested texture size "+r+" greater than WebGL maximum on this browser / GPU "+s+".")}}function hI(e){return ia(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function Zg(e,t,n,r,s,a,o){let i=e.getAttribLocation(t,n);return i===-1?!1:(we(e,()=>e.bindBuffer(e.ARRAY_BUFFER,r)),we(e,()=>e.vertexAttribPointer(i,s,e.FLOAT,!1,a,o)),we(e,()=>e.enableVertexAttribArray(i)),!0)}function fI(e,t,n){xI(e,n),we(e,()=>e.activeTexture(e.TEXTURE0+n)),we(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function wQ(e,t){xI(e,t),we(e,()=>e.activeTexture(e.TEXTURE0+t)),we(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function mI(e,t,n){return ia(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function gI(e,t,n){return e.getUniformLocation(t,n)}function yI(e,t,n,r){we(e,()=>fI(e,t,r)),we(e,()=>e.uniform1i(n,r))}function kQ(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 uf(e,t,n){we(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),we(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function Yg(e,t){we(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),we(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function Ed(e){let t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+AI(e,t))}function AI(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 ia(e,t,n){let r=we(e,()=>t());if(r==null)throw new Error(n);return r}function xI(e,t){let n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,r=t+e.TEXTURE0;if(r<e.TEXTURE0||r>n){let s=`[gl.TEXTURE0, gl.TEXTURE${n}]`;throw new Error(`textureUnit must be in ${s}.`)}}function Li(e,t=2){return w.sizeFromShape(e.slice(0,e.length-t))}function Bi(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 cf(e){let t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[Li(e),...Bi(e)]),t}function bI(e,t=!1){let n=Y().getNumber("WEBGL_MAX_TEXTURE_SIZE");t&&(n=n*2,e=e.map((s,a)=>a>=e.length-2?w.nearestLargerEven(e[a]):e[a]),e.length===1&&(e=[2,e[0]])),e.length!==2&&(e=w.squeezeShape(e).newShape);let r=w.sizeFromShape(e);if(e.length<=1&&r<=n)return[1,r];if(e.length===2&&e[0]<=n&&e[1]<=n)return e;if(e.length===3&&e[0]*e[1]<=n&&e[2]<=n)return[e[0]*e[1],e[2]];if(e.length===3&&e[0]<=n&&e[1]*e[2]<=n)return[e[0],e[1]*e[2]];if(e.length===4&&e[0]*e[1]*e[2]<=n&&e[3]<=n)return[e[0]*e[1]*e[2],e[3]];if(e.length===4&&e[0]<=n&&e[1]*e[2]*e[3]<=n)return[e[0],e[1]*e[2]*e[3]];if(t){let s=Li(e),a=2,o=2;return e.length&&([a,o]=Bi(e)),r=s*(a/2)*(o/2),w.sizeToSquarishShape(r).map(i=>i*2)}return w.sizeToSquarishShape(r)}function ef(e){return e%2===0}function Xd(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 n=e.slice(-1)[0],r=t.slice(-1)[0];if(n===r||ef(n)&&ef(r)&&(e[0]===1||t[0]===1))return!0}return e[1]===t[1]&&ef(e[0])&&ef(t[0])}var df,pf;function vI(e){if(df==null){let t=As(e);df=t.getParameter(t.MAX_TEXTURE_SIZE)}return df}function SQ(){df=null}function IQ(){pf=null}function wI(e){if(pf==null){let t=As(e);pf=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,pf)}function kI(e){if(e===0)return 0;let t,n=As(e);return Er(n,"EXT_disjoint_timer_query_webgl2")&&e===2?t=2:Er(n,"EXT_disjoint_timer_query")?t=1:t=0,t}function Er(e,t){return e.getExtension(t)!=null}function Jg(e){try{if(As(e)!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function SI(e){if(e===0)return!1;let t=As(e);if(e===1){if(!Er(t,"OES_texture_float"))return!1}else if(!Er(t,"EXT_color_buffer_float"))return!1;return Qg(t)}function II(e){if(e===0)return!1;let t=As(e);if(e===1){if(!Er(t,"OES_texture_float")||!Er(t,"WEBGL_color_buffer_float"))return!1}else{if(Er(t,"EXT_color_buffer_float"))return Qg(t);let r="EXT_color_buffer_half_float";if(Er(t,r)){let s=t.getExtension(r);return CQ(t,s)}return!1}return Qg(t)}function Qg(e){let t=l3(e),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n);let r=1,s=1;e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,r,s,0,t.textureFormatFloat,t.textureTypeFloat,null);let a=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,a),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);let o=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(a),o}function CQ(e,t){let n=l3(e,t),r=e.createTexture();e.bindTexture(e.TEXTURE_2D,r);let s=1,a=1;e.texImage2D(e.TEXTURE_2D,0,n.internalFormatHalfFloat,s,a,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);let o=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,o),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,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(o),i}function CI(e){return e!==2?!1:As(e).fenceSync!=null}function Sc(e,t){Array.isArray(e)||(e=[e]),e.forEach(n=>{n!=null&&w.assert(n.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the WebGL backend.`)})}var De=Y();De.registerFlag("HAS_WEBGL",()=>De.getNumber("WEBGL_VERSION")>0);De.registerFlag("WEBGL_VERSION",()=>Jg(2)?2:Jg(1)?1:0);De.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);De.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>De.get("WEBGL_VERSION")===2);De.registerFlag("WEBGL_CPU_FORWARD",()=>!0);De.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);De.registerFlag("WEBGL_PACK",()=>De.getBool("HAS_WEBGL"));De.registerFlag("WEBGL_PACK_NORMALIZATION",()=>De.getBool("WEBGL_PACK"));De.registerFlag("WEBGL_PACK_CLIP",()=>De.getBool("WEBGL_PACK"));De.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>De.getBool("WEBGL_PACK"));De.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>De.getBool("WEBGL_PACK"));De.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>De.getBool("WEBGL_PACK"));De.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>De.getBool("WEBGL_PACK"));De.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>De.getBool("WEBGL_PACK"));De.registerFlag("WEBGL_PACK_REDUCE",()=>De.getBool("WEBGL_PACK"));De.registerFlag("WEBGL_LAZILY_UNPACK",()=>De.getBool("WEBGL_PACK"));De.registerFlag("WEBGL_CONV_IM2COL",()=>De.getBool("WEBGL_PACK"));De.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>vI(De.getNumber("WEBGL_VERSION")));De.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>wI(De.getNumber("WEBGL_VERSION")));De.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{let e=De.getNumber("WEBGL_VERSION");return e===0?0:kI(e)});De.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>De.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!yp.isMobile());De.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>SI(De.getNumber("WEBGL_VERSION")));De.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>De.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:De.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));De.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>II(De.getNumber("WEBGL_VERSION")));De.registerFlag("WEBGL_FENCE_API_ENABLED",()=>CI(De.getNumber("WEBGL_VERSION")));De.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>De.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0);De.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}.`)});De.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>yp.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}.`)});De.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",()=>128);De.registerFlag("WEBGL_USE_SHAPES_UNIFORMS",()=>!1);De.registerFlag("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e5);De.registerFlag("TOPK_K_CPU_HANDOFF_THRESHOLD",()=>128);function Kn(){let e,t,n,r,s,a,o,i,l,u;return Y().getNumber("WEBGL_VERSION")===2?(e="#version 300 es",t="in",n="out",r="in",s="texture",a="outputColor",o="out vec4 outputColor;",i=`
|
|
bool isnan_custom(float val) {
|
|
uint floatToUint = floatBitsToUint(val);
|
|
return (floatToUint & 0x7fffffffu) > 0x7f800000u;
|
|
}
|
|
|
|
bvec4 isnan_custom(vec4 val) {
|
|
return bvec4(isnan_custom(val.x),
|
|
isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w));
|
|
}
|
|
|
|
#define isnan(value) isnan_custom(value)
|
|
`,l="",u=`
|
|
#define round(value) newRound(value)
|
|
int newRound(float value) {
|
|
return int(floor(value + 0.5));
|
|
}
|
|
|
|
ivec4 newRound(vec4 value) {
|
|
return ivec4(floor(value + vec4(0.5)));
|
|
}
|
|
`):(e="",t="attribute",n="varying",r="varying",s="texture2D",a="gl_FragColor",o="",i=`
|
|
#define isnan(value) isnan_custom(value)
|
|
bool isnan_custom(float val) {
|
|
return (val > 0. || val < 1. || val == 0.) ? false : true;
|
|
}
|
|
bvec4 isnan_custom(vec4 val) {
|
|
return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w));
|
|
}
|
|
`,l=`
|
|
uniform float INFINITY;
|
|
|
|
bool isinf(float val) {
|
|
return abs(val) == INFINITY;
|
|
}
|
|
bvec4 isinf(vec4 val) {
|
|
return equal(abs(val), vec4(INFINITY));
|
|
}
|
|
`,u=`
|
|
int round(float value) {
|
|
return int(floor(value + 0.5));
|
|
}
|
|
|
|
ivec4 round(vec4 value) {
|
|
return ivec4(floor(value + vec4(0.5)));
|
|
}
|
|
`),{version:e,attribute:t,varyingVs:n,varyingFs:r,texture2D:s,output:a,defineOutput:o,defineSpecialNaN:i,defineSpecialInf:l,defineRound:u}}function Ml(e,t,n="index"){let r=w.computeStrides(t);return r.map((s,a)=>{let o=`int ${e[a]} = ${n} / ${s}`,i=a===r.length-1?`int ${e[a+1]} = ${n} - ${e[a]} * ${s}`:`index -= ${e[a]} * ${s}`;return`${o}; ${i};`}).join("")}function w0(e,t,n="index"){let r=w.computeStrides(t);return r.map((s,a)=>{let o=`int ${e[a]} = ${n} / outShapeStrides[${a}]`,i=a===r.length-1?`int ${e[a+1]} = ${n} - ${e[a]} * outShapeStrides[${a}]`:`index -= ${e[a]} * outShapeStrides[${a}]`;return`${o}; ${i};`}).join("")}function TQ(e,t){let n=e.length,r=e.map(a=>`${t}[${a}]`),s=new Array(n-1);s[n-2]=r[n-1];for(let a=n-3;a>=0;--a)s[a]=`(${s[a+1]} * ${r[a+1]})`;return s}function NQ(e,t,n="index"){let r=e.map((a,o)=>o),s=TQ(r,t);return s.map((a,o)=>{let i=`int ${e[o]} = ${n} / ${s[o]}`,l=o===s.length-1?`int ${e[o+1]} = ${n} - ${e[o]} * ${s[o]}`:`index -= ${e[o]} * ${s[o]}`;return`${i}; ${l};`}).join("")}function c3(e){let t=w.computeStrides(e).map(n=>n.toString());return`
|
|
int getFlatIndex(ivec3 coords) {
|
|
return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z;
|
|
}
|
|
`}function d3(){return`
|
|
int getFlatIndex(ivec3 coords) {
|
|
return coords.x * outShapeStrides[0] + coords.y * outShapeStrides[1] + coords.z;
|
|
}
|
|
`}var TI=`
|
|
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:NI}=C;function EQ(e,t,n){let r=[];if(e.forEach(h=>{let f=w.sizeFromShape(h.shapeInfo.logicalShape);if(h.shapeInfo.isUniform?r.push(`uniform float ${h.name}${f>1?`[${f}]`:""};`):(r.push(`uniform sampler2D ${h.name};`),r.push(`uniform int offset${h.name};`)),n.enableShapeUniforms){let{uniformShape:m}=p3(n.packedInputs,h.shapeInfo.logicalShape,h.shapeInfo.texShape);switch(m.length){case 1:r.push(`uniform int ${h.name}Shape;`);break;case 2:r.push(`uniform ivec2 ${h.name}Shape;`);break;case 3:r.push(`uniform ivec3 ${h.name}Shape;`);break;case 4:r.push(`uniform ivec4 ${h.name}Shape;`);break;default:break}r.push(`uniform ivec2 ${h.name}TexShape;`)}}),n.enableShapeUniforms){switch(t.logicalShape.length){case 1:r.push("uniform int outShape;");break;case 2:r.push("uniform ivec2 outShape;"),r.push("uniform int outShapeStrides;");break;case 3:r.push("uniform ivec3 outShape;"),r.push("uniform ivec2 outShapeStrides;");break;case 4:r.push("uniform ivec4 outShape;"),r.push("uniform ivec3 outShapeStrides;");break;default:break}r.push("uniform ivec2 outTexShape;")}n.customUniforms&&n.customUniforms.forEach(h=>{r.push(`uniform ${h.type} ${h.name}${h.arrayIndex?`[${h.arrayIndex}]`:""};`)});let s=r.join(`
|
|
`),a=e.map(h=>RQ(h,t,n.packedInputs,n.enableShapeUniforms)).join(`
|
|
`),o=t.texShape,i=Kn(),l=DQ(i),u,c,p=OQ(i);return t.isPacked?(u=_Q(t.logicalShape,o,n.enableShapeUniforms),c=FQ(i)):(u=$Q(t.logicalShape,o,n.enableShapeUniforms),c=PQ(i)),n.packedInputs&&(p+=BQ),[p,l,c,s,u,a,n.userCode].join(`
|
|
`)}function Ic(e,t=!1){let n=e.shapeInfo.logicalShape;switch(n.length){case 0:return JQ(e,t);case 1:return eee(e,t);case 2:return nee(e,t);case 3:return see(e,t);case 4:return oee(e,t);case 5:return iee(e);case 6:return lee(e);default:throw new Error(`${n.length}-D input sampling is not yet supported`)}}function EI(e,t){switch(e.shapeInfo.logicalShape.length){case 0:return YQ(e);case 1:return QQ(e,t);case 2:return tee(e,t);case 3:return ree(e,t);default:return aee(e,t)}}function RQ(e,t,n=!1,r){let s="";n?s+=EI(e,r):s+=Ic(e,r);let a=e.shapeInfo.logicalShape,o=t.logicalShape;return a.length<=o.length&&(n?s+=uee(e,t):s+=cee(e,t)),s}function _Q(e,t,n){switch(e.length){case 0:return RI();case 1:return WQ(e,t,n);case 2:return KQ(e,t,n);case 3:return UQ(e,t,n);default:return HQ(e,t,n)}}function $Q(e,t,n){switch(e.length){case 0:return RI();case 1:return VQ(e,t,n);case 2:return ZQ(e,t,n);case 3:return GQ(e,t,n);case 4:return jQ(e,t,n);case 5:return qQ(e,t);case 6:return XQ(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function DQ(e){return`
|
|
float sampleTexture(sampler2D textureSampler, vec2 uv) {
|
|
return ${e.texture2D}(textureSampler, uv).r;
|
|
}
|
|
`}function PQ(e){return`
|
|
void setOutput(float val) {
|
|
${e.output} = vec4(val, 0, 0, 0);
|
|
}
|
|
`}function FQ(e){return`
|
|
void setOutput(vec4 val) {
|
|
${e.output} = val;
|
|
}
|
|
`}function OQ(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);
|
|
}
|
|
|
|
${MQ}
|
|
${zQ}
|
|
${LQ}
|
|
`}var MQ=`
|
|
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);
|
|
}
|
|
`,LQ=`
|
|
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);
|
|
}
|
|
`,BQ=`
|
|
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 RI(){return`
|
|
int getOutputCoords() {
|
|
return 0;
|
|
}
|
|
`}function WQ(e,t,n){let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return r[0]===1?n?`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.x * ceil(float(outTexShape[1]) / 2.0));
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.x * ${r[1]}.0);
|
|
}
|
|
`:r[1]===1?n?`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.y * ceil(float(outTexShape[0]) / 2.0));
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
return 2 * int(resultUV.y * ${r[0]}.0);
|
|
}
|
|
`:n?`
|
|
int getOutputCoords() {
|
|
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(packedTexShape[0], packedTexShape[1]));
|
|
return 2 * (resTexRC.x * packedTexShape[1] + resTexRC.y);
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${r[0]}, ${r[1]}));
|
|
return 2 * (resTexRC.x * ${r[1]} + resTexRC.y);
|
|
}
|
|
`}function VQ(e,t,n){return t[0]===1?n?`
|
|
int getOutputCoords() {
|
|
return int(resultUV.x * float(outTexShape[1]));
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
return int(resultUV.x * ${t[1]}.0);
|
|
}
|
|
`:t[1]===1?n?`
|
|
int getOutputCoords() {
|
|
return int(resultUV.y * float(outTexShape[0]));
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
return int(resultUV.y * ${t[0]}.0);
|
|
}
|
|
`:n?`
|
|
int getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(outTexShape[0], outTexShape[1]));
|
|
return resTexRC.x * outTexShape[1] + resTexRC.y;
|
|
}
|
|
`:`
|
|
int getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${t[0]}, ${t[1]}));
|
|
return resTexRC.x * ${t[1]} + resTexRC.y;
|
|
}
|
|
`}function UQ(e,t,n){if(n)return`
|
|
ivec3 getOutputCoords() {
|
|
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
|
|
int texelsInLogicalRow = int(ceil(float(outShape[2]) / 2.0));
|
|
int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[1]) / 2.0));
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(packedTexShape[0], packedTexShape[1]));
|
|
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
|
|
|
|
int b = index / texelsInBatch;
|
|
index -= b * texelsInBatch;
|
|
|
|
int r = 2 * (index / texelsInLogicalRow);
|
|
int c = imod(index, texelsInLogicalRow) * 2;
|
|
|
|
return ivec3(b, r, c);
|
|
}
|
|
`;let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[2]/2),a=s*Math.ceil(e[1]/2);return`
|
|
ivec3 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${r[0]}, ${r[1]}));
|
|
int index = resTexRC.x * ${r[1]} + resTexRC.y;
|
|
|
|
int b = index / ${a};
|
|
index -= b * ${a};
|
|
|
|
int r = 2 * (index / ${s});
|
|
int c = imod(index, ${s}) * 2;
|
|
|
|
return ivec3(b, r, c);
|
|
}
|
|
`}function GQ(e,t,n){if(n)return`
|
|
ivec3 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(outTexShape[0], outTexShape[1]));
|
|
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
|
|
${w0(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`;let r=Ml(["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;
|
|
${r}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`}function HQ(e,t,n){if(n)return`
|
|
ivec4 getOutputCoords() {
|
|
ivec2 packedTexShape = ivec2(ceil(float(outTexShape[0]) / 2.0), ceil(float(outTexShape[1]) / 2.0));
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(packedTexShape[0], packedTexShape[1]));
|
|
int index = resTexRC.x * packedTexShape[1] + resTexRC.y;
|
|
|
|
int texelsInLogicalRow = int(ceil(float(outShape[3]) / 2.0));
|
|
int texelsInBatch = texelsInLogicalRow * int(ceil(float(outShape[2]) / 2.0));
|
|
int texelsInBatchN = texelsInBatch * outShape[1];
|
|
|
|
int b2 = index / texelsInBatchN;
|
|
index -= b2 * texelsInBatchN;
|
|
|
|
int b = index / texelsInBatch;
|
|
index -= b * texelsInBatch;
|
|
|
|
int r = 2 * (index / texelsInLogicalRow);
|
|
int c = imod(index, texelsInLogicalRow) * 2;
|
|
|
|
return ivec4(b2, b, r, c);
|
|
}
|
|
`;let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],s=Math.ceil(e[e.length-1]/2),a=s*Math.ceil(e[e.length-2]/2),o=a,i="",l="b, r, c";for(let u=2;u<e.length-1;u++)o*=e[e.length-u-1],i=`
|
|
int b${u} = index / ${o};
|
|
index -= b${u} * ${o};
|
|
`+i,l=`b${u}, `+l;return`
|
|
ivec${e.length} getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(${r[0]}, ${r[1]}));
|
|
int index = resTexRC.x * ${r[1]} + resTexRC.y;
|
|
|
|
${i}
|
|
|
|
int b = index / ${a};
|
|
index -= b * ${a};
|
|
|
|
int r = 2 * (index / ${s});
|
|
int c = imod(index, ${s}) * 2;
|
|
|
|
return ivec${e.length}(${l});
|
|
}
|
|
`}function jQ(e,t,n){if(n)return`
|
|
ivec4 getOutputCoords() {
|
|
ivec2 resTexRC = ivec2(resultUV.yx *
|
|
vec2(outTexShape[0], outTexShape[1]));
|
|
int index = resTexRC.x * outTexShape[1] + resTexRC.y;
|
|
${w0(["r","c","d","d2"],e)}
|
|
return ivec4(r, c, d, d2);
|
|
}
|
|
`;let r=Ml(["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;
|
|
${r}
|
|
return ivec4(r, c, d, d2);
|
|
}
|
|
`}function qQ(e,t){let n=Ml(["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;
|
|
|
|
${n}
|
|
|
|
ivec5 outShape = ivec5(r, c, d, d2, d3);
|
|
return outShape;
|
|
}
|
|
`}function XQ(e,t){let n=Ml(["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;
|
|
|
|
${n}
|
|
|
|
ivec6 result = ivec6(r, c, d, d2, d3, d4);
|
|
return result;
|
|
}
|
|
`}function KQ(e,t,n){let r=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];if(w.arraysEqual(e,t))return n?`
|
|
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(${r[0]}, ${r[1]}));
|
|
}
|
|
`;let s=Math.ceil(e[1]/2);return n?`
|
|
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(${r[0]}, ${r[1]}));
|
|
|
|
int index = resTexRC.x * ${r[1]} + resTexRC.y;
|
|
int r = 2 * (index / ${s});
|
|
int c = imod(index, ${s}) * 2;
|
|
|
|
return ivec2(r, c);
|
|
}
|
|
`}function ZQ(e,t,n){return w.arraysEqual(e,t)?n?`
|
|
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?n?`
|
|
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?n?`
|
|
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);
|
|
}
|
|
`:n?`
|
|
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 YQ(e){let t=e.name,n="get"+t.charAt(0).toUpperCase()+t.slice(1),r=Kn();return`
|
|
vec4 ${n}() {
|
|
return ${r.texture2D}(${t}, halfCR);
|
|
}
|
|
`}function JQ(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`float ${r}() {return ${n};}`;let[s,a]=e.shapeInfo.texShape;if(s===1&&a===1)return`
|
|
float ${r}() {
|
|
return sampleTexture(${n}, halfCR);
|
|
}
|
|
`;let o=zl(n);if(t)return`
|
|
float ${r}() {
|
|
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], ${o});
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let[i,l]=e.shapeInfo.texShape;return`
|
|
float ${r}() {
|
|
vec2 uv = uvFromFlat(${i}, ${l}, ${o});
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function QQ(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=e.shapeInfo.texShape,a=Kn();if(t)return`
|
|
vec4 ${r}(int index) {
|
|
ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}TexShape[1]) / 2.0));
|
|
vec2 uv = packedUVfrom1D(
|
|
packedTexShape[0], packedTexShape[1], index);
|
|
return ${a.texture2D}(${n}, uv);
|
|
}
|
|
`;let o=[Math.ceil(s[0]/2),Math.ceil(s[1]/2)];return`
|
|
vec4 ${r}(int index) {
|
|
vec2 uv = packedUVfrom1D(
|
|
${o[0]}, ${o[1]}, index);
|
|
return ${a.texture2D}(${n}, uv);
|
|
}
|
|
`}function eee(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1);if(e.shapeInfo.isUniform)return`
|
|
float ${r}(int index) {
|
|
${Cc(e)}
|
|
}
|
|
`;let s=e.shapeInfo.texShape,a=s[0],o=s[1];if(o===1&&a===1)return`
|
|
float ${r}(int index) {
|
|
return sampleTexture(${n}, halfCR);
|
|
}
|
|
`;let i=zl(n);return o===1?t?`
|
|
float ${r}(int index) {
|
|
vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / float(${n}TexShape[0]));
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${r}(int index) {
|
|
vec2 uv = vec2(0.5, (float(index + ${i}) + 0.5) / ${a}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:a===1?t?`
|
|
float ${r}(int index) {
|
|
vec2 uv = vec2((float(index + ${i}) + 0.5) / float(${n}TexShape[1]), 0.5);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${r}(int index) {
|
|
vec2 uv = vec2((float(index + ${i}) + 0.5) / ${o}.0, 0.5);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:t?`
|
|
float ${r}(int index) {
|
|
vec2 uv = uvFromFlat(${n}TexShape[0], ${n}TexShape[1], index + ${i});
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`:`
|
|
float ${r}(int index) {
|
|
vec2 uv = uvFromFlat(${a}, ${o}, index + ${i});
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function tee(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape,o=a[0],i=a[1],l=Kn();if(a!=null&&w.arraysEqual(n,a))return t?`
|
|
vec4 ${s}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);
|
|
|
|
return ${l.texture2D}(${r}, uv);
|
|
}
|
|
`:`
|
|
vec4 ${s}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${i}.0, ${o}.0);
|
|
|
|
return ${l.texture2D}(${r}, uv);
|
|
}
|
|
`;if(t)return`
|
|
vec4 ${s}(int row, int col) {
|
|
ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}TexShape[1]) / 2.0));
|
|
int valuesPerRow = int(ceil(float(${r}Shape[1]) / 2.0));
|
|
vec2 uv = packedUVfrom2D(valuesPerRow, packedTexShape[0], packedTexShape[1], row, col);
|
|
return ${l.texture2D}(${r}, uv);
|
|
}
|
|
`;let u=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)],c=Math.ceil(n[1]/2);return`
|
|
vec4 ${s}(int row, int col) {
|
|
vec2 uv = packedUVfrom2D(${c}, ${u[0]}, ${u[1]}, row, col);
|
|
return ${l.texture2D}(${r}, uv);
|
|
}
|
|
`}function nee(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape;if(a!=null&&w.arraysEqual(n,a)){if(t)return`
|
|
float ${s}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`;let d=a[0],h=a[1];return`
|
|
float ${s}(int row, int col) {
|
|
vec2 uv = (vec2(col, row) + halfCR) / vec2(${h}.0, ${d}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`}let{newShape:o,keptDims:i}=w.squeezeShape(n),l=o;if(l.length<n.length){let d=Tc(e,l),h=["row","col"];return`
|
|
${Ic(d,t)}
|
|
float ${s}(int row, int col) {
|
|
return ${s}(${Nc(h,i)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${s}(int row, int col) {
|
|
int index = round(dot(vec2(row, col), vec2(${n[1]}, 1)));
|
|
${Cc(e)}
|
|
}
|
|
`;let u=a[0],c=a[1],p=zl(r);return c===1?t?`
|
|
float ${s}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${p}), vec3(${r}Shape[1], 1, 1));
|
|
vec2 uv = vec2(0.5, (index + 0.5) / float(${r}TexShape[0]));
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${s}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${p}), vec3(${n[1]}, 1, 1));
|
|
vec2 uv = vec2(0.5, (index + 0.5) / ${u}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:u===1?t?`
|
|
float ${s}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${p}), vec3(${r}Shape[1], 1, 1));
|
|
vec2 uv = vec2((index + 0.5) / float(${r}TexShape[1]), 0.5);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${s}(int row, int col) {
|
|
float index = dot(vec3(row, col, ${p}), vec3(${n[1]}, 1, 1));
|
|
vec2 uv = vec2((index + 0.5) / ${c}.0, 0.5);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:t?`
|
|
float ${s}(int row, int col) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${r}Shape[1] + col + ${p};
|
|
vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${s}(int row, int col) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${n[1]} + col + ${p};
|
|
vec2 uv = uvFromFlat(${u}, ${c}, index);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`}function ree(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=e.shapeInfo.texShape,o=[Math.ceil(a[0]/2),Math.ceil(a[1]/2)];if(n[0]===1){let d=n.slice(1),h=[1,2],f=Tc(e,d),m=["b","row","col"];return`
|
|
${EI(f,t)}
|
|
vec4 ${s}(int b, int row, int col) {
|
|
return ${s}(${Nc(m,h)});
|
|
}
|
|
`}let i=Kn();if(t)return`
|
|
vec4 ${s}(int b, int row, int col) {
|
|
ivec2 packedTexShape = ivec2(ceil(float(${r}TexShape[0]) / 2.0), ceil(float(${r}TexShape[1]) / 2.0));
|
|
int valuesPerRow = int(ceil(float(${r}Shape[2]) / 2.0));
|
|
int texelsInBatch = valuesPerRow * int(ceil(float(${r}Shape[1]) / 2.0));
|
|
vec2 uv = packedUVfrom3D(
|
|
packedTexShape[0], packedTexShape[1], texelsInBatch, valuesPerRow, b, row, col);
|
|
return ${i.texture2D}(${r}, uv);
|
|
}
|
|
`;let l=o[0],u=o[1],c=Math.ceil(n[2]/2),p=c*Math.ceil(n[1]/2);return`
|
|
vec4 ${s}(int b, int row, int col) {
|
|
vec2 uv = packedUVfrom3D(
|
|
${l}, ${u}, ${p}, ${c}, b, row, col);
|
|
return ${i.texture2D}(${r}, uv);
|
|
}
|
|
`}function see(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=n[1]*n[2],o=n[2],{newShape:i,keptDims:l}=w.squeezeShape(n),u=i;if(u.length<n.length){let m=Tc(e,u),g=["row","col","depth"];return`
|
|
${Ic(m,t)}
|
|
float ${s}(int row, int col, int depth) {
|
|
return ${s}(${Nc(g,l)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${s}(int row, int col, int depth) {
|
|
int index = round(dot(vec3(row, col, depth),
|
|
vec3(${a}, ${o}, 1)));
|
|
${Cc(e)}
|
|
}
|
|
`;let c=e.shapeInfo.texShape,p=c[0],d=c[1],h=e.shapeInfo.flatOffset;if(d===a&&h==null)return t?`
|
|
float ${s}(int row, int col, int depth) {
|
|
int stride1 = ${r}Shape[2];
|
|
float texR = float(row);
|
|
float texC = dot(vec2(col, depth), vec2(stride1, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${r}TexShape[1], ${r}TexShape[0]);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${s}(int row, int col, int depth) {
|
|
float texR = float(row);
|
|
float texC = dot(vec2(col, depth), vec2(${o}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${d}.0, ${p}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`;if(d===o&&h==null)return t?`
|
|
float ${s}(int row, int col, int depth) {
|
|
float texR = dot(vec2(row, col), vec2(${r}Shape[1], 1));
|
|
float texC = float(depth);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${r}TexShape[1], ${r}TexShape[0]);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${s}(int row, int col, int depth) {
|
|
float texR = dot(vec2(row, col), vec2(${n[1]}, 1));
|
|
float texC = float(depth);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${d}.0, ${p}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`;let f=zl(r);return t?`
|
|
float ${s}(int row, int col, int depth) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int stride0 = ${r}Shape[1] * ${r}Shape[2];
|
|
int stride1 = ${r}Shape[2];
|
|
int index = row * ${a} + col * ${o} + depth + ${f};
|
|
vec2 uv = uvFromFlat(${r}TexShape[0], ${r}TexShape[1], index);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${s}(int row, int col, int depth) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${a} + col * ${o} + depth + ${f};
|
|
vec2 uv = uvFromFlat(${p}, ${d}, index);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`}function aee(e,t){let n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=Kn();if(t)return`
|
|
vec4 ${r}(int b2, int b, int row, int col) {
|
|
int valuesPerRow = int(ceil(float(${n}Shape[3]) / 2.0));
|
|
int texelsInBatch = valuesPerRow * int(ceil(float(${n}Shape[2]) / 2.0));
|
|
int index = b * texelsInBatch + (row / 2) * valuesPerRow + (col / 2);
|
|
texelsInBatch *= ${n}Shape[1];
|
|
index = b2 * texelsInBatch + index;
|
|
ivec2 packedTexShape = ivec2(ceil(float(${n}TexShape[0]) / 2.0), ceil(float(${n}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 ${s.texture2D}(${n}, uv);
|
|
}
|
|
`;let a=e.shapeInfo.logicalShape,o=a.length,i=e.shapeInfo.texShape,l=[Math.ceil(i[0]/2),Math.ceil(i[1]/2)],u=l[0],c=l[1],p=Math.ceil(a[o-1]/2),d=p*Math.ceil(a[o-2]/2),h="int b, int row, int col",f=`b * ${d} + (row / 2) * ${p} + (col / 2)`;for(let m=2;m<o-1;m++)h=`int b${m}, `+h,d*=a[o-m-1],f=`b${m} * ${d} + `+f;return`
|
|
vec4 ${r}(${h}) {
|
|
int index = ${f};
|
|
int texR = index / ${c};
|
|
int texC = index - texR * ${c};
|
|
vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${c}, ${u});
|
|
return ${s.texture2D}(${n}, uv);
|
|
}
|
|
`}function oee(e,t){let n=e.shapeInfo.logicalShape,r=e.name,s="get"+r.charAt(0).toUpperCase()+r.slice(1),a=n[3],o=n[2]*a,i=n[1]*o,{newShape:l,keptDims:u}=w.squeezeShape(n);if(l.length<n.length){let x=Tc(e,l),A=["row","col","depth","depth2"];return`
|
|
${Ic(x,t)}
|
|
float ${s}(int row, int col, int depth, int depth2) {
|
|
return ${s}(${Nc(A,u)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${s}(int row, int col, int depth, int depth2) {
|
|
int index = round(dot(vec4(row, col, depth, depth2),
|
|
vec4(${i}, ${o}, ${a}, 1)));
|
|
${Cc(e)}
|
|
}
|
|
`;let c=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,d=p[0],h=p[1],f=`int stride2 = ${r}Shape[3];`,m=`int stride1 = ${r}Shape[2] * stride2;`,g=`int stride0 = ${r}Shape[1] * stride1;`;if(h===i&&c==null)return t?`
|
|
float ${s}(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(${r}TexShape[1], ${r}TexShape[0]);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${s}(int row, int col, int depth, int depth2) {
|
|
float texR = float(row);
|
|
float texC =
|
|
dot(vec3(col, depth, depth2),
|
|
vec3(${o}, ${a}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${h}.0, ${d}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`;if(h===a&&c==null)return t?`
|
|
float ${s}(int row, int col, int depth, int depth2) {
|
|
float texR = dot(vec3(row, col, depth),
|
|
vec3(${r}Shape[1] * ${r}Shape[2], ${r}Shape[2], 1));
|
|
float texC = float(depth2);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${r}TexShape[1], ${r}TexShape[0]);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${s}(int row, int col, int depth, int depth2) {
|
|
float texR = dot(vec3(row, col, depth),
|
|
vec3(${n[1]*n[2]}, ${n[2]}, 1));
|
|
float texC = float(depth2);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${h}.0, ${d}.0);
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`;let y=zl(r);return t?`
|
|
float ${s}(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(${r}TexShape[0], ${r}TexShape[1], index + ${y});
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`:`
|
|
float ${s}(int row, int col, int depth, int depth2) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${i} + col * ${o} +
|
|
depth * ${a} + depth2;
|
|
vec2 uv = uvFromFlat(${d}, ${h}, index + ${y});
|
|
return sampleTexture(${r}, uv);
|
|
}
|
|
`}function iee(e){let t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),s=t[4],a=t[3]*s,o=t[2]*a,i=t[1]*o,{newShape:l,keptDims:u}=w.squeezeShape(t);if(l.length<t.length){let m=Tc(e,l),g=["row","col","depth","depth2","depth3"];return`
|
|
${Ic(m)}
|
|
float ${r}(int row, int col, int depth, int depth2, int depth3) {
|
|
return ${r}(${Nc(g,u)});
|
|
}
|
|
`}if(e.shapeInfo.isUniform)return`
|
|
float ${r}(int row, int col, int depth, int depth2, int depth3) {
|
|
float index = dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${i}, ${o}, ${a}, ${s})) +
|
|
depth3;
|
|
${Cc(e)}
|
|
}
|
|
`;let c=e.shapeInfo.flatOffset,p=e.shapeInfo.texShape,d=p[0],h=p[1];if(h===i&&c==null)return`
|
|
float ${r}(int row, int col, int depth, int depth2, int depth3) {
|
|
int texR = row;
|
|
float texC = dot(vec4(col, depth, depth2, depth3),
|
|
vec4(${o}, ${a}, ${s}, 1));
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${h}.0, ${d}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;if(h===s&&c==null)return`
|
|
float ${r}(int row, int col, int depth, int depth2, int depth3) {
|
|
float texR = dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${t[1]*t[2]*t[3]},
|
|
${t[2]*t[3]}, ${t[3]}, 1));
|
|
int texC = depth3;
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${h}.0, ${d}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let f=zl(n);return`
|
|
float ${r}(int row, int col, int depth, int depth2, int depth3) {
|
|
// Explicitly use integer operations as dot() only works on floats.
|
|
int index = row * ${i} + col * ${o} + depth * ${a} +
|
|
depth2 * ${s} + depth3 + ${f};
|
|
vec2 uv = uvFromFlat(${d}, ${h}, index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function lee(e){let t=e.shapeInfo.logicalShape,n=e.name,r="get"+n.charAt(0).toUpperCase()+n.slice(1),{newShape:s,keptDims:a}=w.squeezeShape(t);if(s.length<t.length){let g=Tc(e,s),y=["row","col","depth","depth2","depth3","depth4"];return`
|
|
${Ic(g)}
|
|
float ${r}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
return ${r}(${Nc(y,a)});
|
|
}
|
|
`}let o=t[5],i=t[4]*o,l=t[3]*i,u=t[2]*l,c=t[1]*u;if(e.shapeInfo.isUniform)return`
|
|
float ${r}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
int index = round(dot(
|
|
vec4(row, col, depth, depth2),
|
|
vec4(${c}, ${u}, ${l}, ${i})) +
|
|
dot(
|
|
vec2(depth3, depth4),
|
|
vec2(${o}, 1)));
|
|
${Cc(e)}
|
|
}
|
|
`;let p=e.shapeInfo.flatOffset,d=e.shapeInfo.texShape,h=d[0],f=d[1];if(f===c&&p==null)return`
|
|
float ${r}(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}, ${i}, ${o})) +
|
|
float(depth4);
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${f}.0, ${h}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;if(f===o&&p==null)return`
|
|
float ${r}(int row, int col, int depth,
|
|
int depth2, int depth3, int depth4) {
|
|
float texR = dot(vec4(row, col, depth, depth2),
|
|
vec4(${t[1]*t[2]*t[3]*t[4]},
|
|
${t[2]*t[3]*t[4]},
|
|
${t[3]*t[4]},
|
|
${t[4]})) + float(depth3);
|
|
int texC = depth4;
|
|
vec2 uv = (vec2(texC, texR) + halfCR) /
|
|
vec2(${f}.0, ${h}.0);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`;let m=zl(n);return`
|
|
float ${r}(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 * ${c} + col * ${u} + depth * ${l} +
|
|
depth2 * ${i} + depth3 * ${o} + depth4 + ${m};
|
|
vec2 uv = uvFromFlat(${h}, ${f}, index);
|
|
return sampleTexture(${n}, uv);
|
|
}
|
|
`}function Cc(e){let t=e.name,n=w.sizeFromShape(e.shapeInfo.logicalShape);return n<2?`return ${t};`:`
|
|
for (int i = 0; i < ${n}; i++) {
|
|
if (i == index) {
|
|
return ${t}[i];
|
|
}
|
|
}
|
|
`}function uee(e,t){let n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),s="get"+r+"AtOutCoords",a=e.shapeInfo.logicalShape.length,o=t.logicalShape.length,i=NI(e.shapeInfo.logicalShape,t.logicalShape),l=yt(o),u=o-a,c,p=["x","y","z","w","u","v"];a===0?c="":o<2&&i.length>=1?c="coords = 0;":c=i.map(x=>`coords.${p[x+u]} = 0;`).join(`
|
|
`);let d="";o<2&&a>0?d="coords":d=e.shapeInfo.logicalShape.map((x,A)=>`coords.${p[A+u]}`).join(", ");let h="return outputValue;",m=w.sizeFromShape(e.shapeInfo.logicalShape)===1,y=w.sizeFromShape(t.logicalShape)===1;if(a===1&&!m&&!y)h=`
|
|
return vec4(outputValue.xy, outputValue.xy);
|
|
`;else if(m&&!y)o===1?h=`
|
|
return vec4(outputValue.x, outputValue.x, 0., 0.);
|
|
`:h=`
|
|
return vec4(outputValue.x);
|
|
`;else if(i.length){let x=a-2,A=a-1;i.indexOf(x)>-1&&i.indexOf(A)>-1?h="return vec4(outputValue.x);":i.indexOf(x)>-1?h="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":i.indexOf(A)>-1&&(h="return vec4(outputValue.xx, outputValue.zz);")}return`
|
|
vec4 ${s}() {
|
|
${l} coords = getOutputCoords();
|
|
${c}
|
|
vec4 outputValue = get${r}(${d});
|
|
${h}
|
|
}
|
|
`}function cee(e,t){let n=e.name,r=n.charAt(0).toUpperCase()+n.slice(1),s="get"+r+"AtOutCoords",a=t.texShape,o=e.shapeInfo.texShape,i=e.shapeInfo.logicalShape.length,l=t.logicalShape.length;if(!e.shapeInfo.isUniform&&i===l&&e.shapeInfo.flatOffset==null&&w.arraysEqual(o,a))return`
|
|
float ${s}() {
|
|
return sampleTexture(${n}, resultUV);
|
|
}
|
|
`;let u=yt(l),c=NI(e.shapeInfo.logicalShape,t.logicalShape),p=l-i,d,h=["x","y","z","w","u","v"];i===0?d="":l<2&&c.length>=1?d="coords = 0;":d=c.map(m=>`coords.${h[m+p]} = 0;`).join(`
|
|
`);let f="";return l<2&&i>0?f="coords":f=e.shapeInfo.logicalShape.map((m,g)=>`coords.${h[g+p]}`).join(", "),`
|
|
float ${s}() {
|
|
${u} coords = getOutputCoords();
|
|
${d}
|
|
return get${r}(${f});
|
|
}
|
|
`}function yt(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 p3(e,t,n){let{newShape:r,keptDims:s}=w.squeezeShape(t),a=t.length,o=e&&a===3&&t[0]===1,i=o?t.slice(1):r,l=!e&&a>1&&!w.arraysEqual(t,n)&&r.length<a||o;return{useSqueezeShape:l,uniformShape:l?i:t,keptDims:s}}function Tc(e,t){let n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function Nc(e,t){return t.map(n=>e[n]).join(", ")}function dee(e,t,n,r){let s=n.map((c,p)=>{let d={logicalShape:c.shape,texShape:c.isUniform?null:c.texData.texShape,isUniform:c.isUniform,isPacked:c.isUniform?!1:c.texData.isPacked,flatOffset:null};return c.texData!=null&&c.texData.slice!=null&&c.texData.slice.flatOffset>0&&(d.flatOffset=c.texData.slice.flatOffset),{name:t.variableNames[p],shapeInfo:d}}),a=s.map(c=>c.shapeInfo),o={logicalShape:r.shape,texShape:r.texData.texShape,isUniform:!1,isPacked:r.texData.isPacked,flatOffset:null},i=EQ(s,o,t),l=oI(e.gl,i),u=e.createProgram(l);return Y().get("ENGINE_COMPILE_ONLY")?{program:t,fragmentShader:l,source:i,webGLProgram:u,inShapeInfos:a,outShapeInfo:o,uniformLocations:null,customUniformLocations:null,infLoc:null,nanLoc:null,inShapesLocations:null,inTexShapesLocations:null,outShapeLocation:null,outShapeStridesLocation:null,outTexShapeLocation:null}:{program:t,fragmentShader:l,source:i,webGLProgram:u,inShapeInfos:a,outShapeInfo:o,..._I(e,t,u)}}function _I(e,t,n){let r={},s={},a={},o=[],i,l,u,c=null,p=null;p=e.getUniformLocation(n,"NAN",!1),Y().getNumber("WEBGL_VERSION")===1&&(c=e.getUniformLocation(n,"INFINITY",!1));let d=!1;for(let h=0;h<t.variableNames.length;h++){let f=t.variableNames[h];r[f]=e.getUniformLocation(n,f,d),r[`offset${f}`]=e.getUniformLocation(n,`offset${f}`,d),t.enableShapeUniforms&&(s[`${f}Shape`]=e.getUniformLocation(n,`${f}Shape`,d),a[`${f}TexShape`]=e.getUniformLocation(n,`${f}TexShape`,d))}return t.enableShapeUniforms&&(i=e.getUniformLocation(n,"outShape",d),u=e.getUniformLocation(n,"outShapeStrides",d),l=e.getUniformLocation(n,"outTexShape",d)),t.customUniforms&&t.customUniforms.forEach((h,f)=>{o[f]=e.getUniformLocation(n,h.name,d)}),{uniformLocations:r,customUniformLocations:o,infLoc:c,nanLoc:p,inShapesLocations:s,inTexShapesLocations:a,outShapeLocation:i,outShapeStridesLocation:u,outTexShapeLocation:l}}function Dv(e,t){if(e.length!==t.length)throw Error(`Binary was compiled with ${e.length} inputs, but was executed with ${t.length} inputs`);e.forEach((n,r)=>{let s=n.logicalShape,a=t[r],o=a.shape;if(!w.arraysEqual(s,o))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${s} and ${o} must match`);if(n.isUniform&&a.isUniform)return;let i=n.texShape,l=a.isUniform?null:a.texData.texShape;if(!w.arraysEqual(i,l))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${i} and ${l} must match`)})}function pee(e,t,n,r,s){t.program.enableShapeUniforms||(Dv(t.inShapeInfos,n),Dv([t.outShapeInfo],[r]));let a=r.texData.texture,o=r.texData.texShape;r.texData.isPacked?e.setOutputPackedMatrixTexture(a.texture,o[0],o[1]):e.setOutputMatrixTexture(a.texture,o[0],o[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),n.forEach((l,u)=>{let c=t.program.variableNames[u],p=t.uniformLocations[c],d=t.uniformLocations[`offset${c}`],h=t.inShapesLocations[`${c}Shape`],f=t.inTexShapesLocations[`${c}TexShape`];if(h){let{uniformShape:m}=p3(t.program.packedInputs,l.shape,l.texData.texShape);switch(m.length){case 1:e.gl.uniform1iv(h,new Int32Array(m));break;case 2:e.gl.uniform2iv(h,new Int32Array(m));break;case 3:e.gl.uniform3iv(h,new Int32Array(m));break;case 4:e.gl.uniform4iv(h,new Int32Array(m));break;default:break}}if(f&&e.gl.uniform2i(f,l.texData.texShape[0],l.texData.texShape[1]),p!=null){if(l.isUniform){if(w.sizeFromShape(l.shape)<2)e.gl.uniform1f(p,l.uniformValues[0]);else{let m=l.uniformValues;m instanceof Float32Array||(m=new Float32Array(m)),e.gl.uniform1fv(p,m)}return}l.texData.slice!=null&&d!=null&&e.gl.uniform1i(d,l.texData.slice.flatOffset),e.setInputMatrixTexture(l.texData.texture.texture,p,u)}});let i=t.outShapeLocation;if(i)switch(r.shape.length){case 1:e.gl.uniform1iv(i,new Int32Array(r.shape));break;case 2:e.gl.uniform2iv(i,new Int32Array(r.shape));break;case 3:e.gl.uniform3iv(i,new Int32Array(r.shape));break;case 4:e.gl.uniform4iv(i,new Int32Array(r.shape));break;default:break}if(t.outShapeStridesLocation){let l=w.computeStrides(r.shape);switch(r.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,r.texData.texShape[0],r.texData.texShape[1]),t.program.customUniforms&&s&&t.program.customUniforms.forEach((l,u)=>{let c=t.customUniformLocations[u],p=s[u];if(l.type==="float")e.gl.uniform1fv(c,p);else if(l.type==="vec2")e.gl.uniform2fv(c,p);else if(l.type==="vec3")e.gl.uniform3fv(c,p);else if(l.type==="vec4")e.gl.uniform4fv(c,p);else if(l.type==="int")e.gl.uniform1iv(c,p);else if(l.type==="ivec2")e.gl.uniform2iv(c,p);else if(l.type==="ivec3")e.gl.uniform3iv(c,p);else if(l.type==="ivec4")e.gl.uniform4iv(c,p);else throw Error(`uniform type ${l.type} is not supported yet.`)}),e.executeProgram()}function hee(e,t,n){let r="";t.concat(n).forEach(o=>{let i=o.texData!=null&&o.texData.slice!=null&&o.texData.slice.flatOffset>0;if(e.enableShapeUniforms&&!o.isUniform){let l=o.texData.texShape,{useSqueezeShape:u,uniformShape:c,keptDims:p}=p3(e.packedInputs,o.shape,l),d="",h="",f="";if(c.length===1&&e.packedInputs){let v=[Math.ceil(l[0]/2),Math.ceil(l[1]/2)];d=`${v[0]>1}_${v[1]>1}`}else if(c.length===2&&!e.packedInputs)h=`${c[0]>1}_${c[1]>1}`;else if(c.length>2&&!e.packedInputs){let v=w.computeStrides(c);f=`${v[0]===l[1]}_${v[v.length-1]===l[1]}`}let m=o.shape.length,g=c.length===2&&w.arraysEqual(o.shape,l),y=w.sizeFromShape(o.shape)===1,x=C.getBroadcastDims(o.shape,n.shape),A=!e.packedInputs&&m===n.shape.length&&w.arraysEqual(l,n.texData.texShape),b=e.packedInputs||c.length>2?"":`${l[0]>1}_${l[1]>1}`;r+=`${m}_${A}_${u?p:""}_${c.length}_${y}_${x}_${g}_${d}_${h}_${f}_${b}_${i}`}else{let l=o.isUniform?"uniform":o.texData.texShape;r+=`${o.shape}_${l}_${i}`}});let s=e.userCode,a=e.constructor.name;return a+="_"+r+"_"+s+`${Y().getNumber("WEBGL_VERSION")}`,a}function lr(e){return Y().getBool("WEBGL_USE_SHAPES_UNIFORMS")&&e<=4}var fee=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=Kn();this.outputShape=e,this.enableShapeUniforms=lr(this.outputShape.length),this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${this.enableShapeUniforms?w0(["r","c","d"],e):Ml(["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;
|
|
}
|
|
`}},mee=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let t=Kn();this.outputShape=e,this.enableShapeUniforms=lr(this.outputShape.length),this.userCode=`
|
|
ivec3 outCoordsFromFlatIndex(int index) {
|
|
${this.enableShapeUniforms?w0(["r","c","d"],e):Ml(["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;
|
|
}
|
|
`}},gee=class{constructor(e){this.variableNames=["A"],this.outTexUsage=3;let t=Kn();this.outputShape=e,this.userCode=`
|
|
${TI}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}},yee=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=3;let t=Kn();this.outputShape=e,this.userCode=`
|
|
${TI}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z));
|
|
${t.output} = encode_float(x);
|
|
}
|
|
`}},Aee=class{constructor(e,t=!1){this.variableNames=["A"],this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=Kn();this.outputShape=e,this.enableShapeUniforms=lr(this.outputShape.length);let r="result";t&&(r="floor(result * 255. + 0.5)"),this.userCode=`
|
|
${this.enableShapeUniforms?d3():c3(e)}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
|
|
int flatIndex = getFlatIndex(coords);
|
|
int offset = imod(flatIndex, 4);
|
|
|
|
flatIndex = idiv(flatIndex, 4, 1.);
|
|
|
|
int r = flatIndex / texShape[1];
|
|
int c = imod(flatIndex, texShape[1]);
|
|
vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
|
|
vec4 values = ${n.texture2D}(A, uv);
|
|
|
|
float result;
|
|
|
|
if(offset == 0) {
|
|
result = values[0];
|
|
} else if(offset == 1) {
|
|
result = values[1];
|
|
} else if(offset == 2) {
|
|
result = values[2];
|
|
} else {
|
|
result = values[3];
|
|
}
|
|
|
|
${n.output} = vec4(${r}, 0., 0., 0.);
|
|
}
|
|
`}},xee=class{constructor(e,t=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.customUniforms=[{name:"texShape",type:"ivec2"}];let n=Kn();this.outputShape=e,this.enableShapeUniforms=lr(this.outputShape.length);let r="",s="result";t&&(s="floor(result * 255. + 0.5)");for(let a=0;a<=1;a++)for(let o=0;o<=1;o++){let i=a*2+o;r+=`
|
|
localCoords = coords;
|
|
if(localCoords[2] + ${o} < ${this.enableShapeUniforms?"outShape[2]":`${e[2]}`}) {
|
|
localCoords[2] += ${o};
|
|
if (localCoords[1] + ${a} < ${this.enableShapeUniforms?"outShape[1]":`${e[1]}`}) {
|
|
localCoords[1] += ${a};
|
|
|
|
flatIndex = getFlatIndex(localCoords);
|
|
offset = imod(flatIndex, 4);
|
|
|
|
flatIndex = idiv(flatIndex, 4, 1.);
|
|
|
|
int r = flatIndex / texShape[1];
|
|
int c = imod(flatIndex, texShape[1]);
|
|
vec2 uv = (vec2(c, r) + halfCR) / vec2(texShape[1], texShape[0]);
|
|
values = ${n.texture2D}(A, uv);
|
|
|
|
if (offset == 0) {
|
|
result[${i}] = values[0];
|
|
} else if (offset == 1) {
|
|
result[${i}] = values[1];
|
|
} else if (offset == 2) {
|
|
result[${i}] = values[2];
|
|
} else {
|
|
result[${i}] = values[3];
|
|
}
|
|
}
|
|
}
|
|
`}this.userCode=`
|
|
${this.enableShapeUniforms?d3():c3(e)}
|
|
|
|
void main() {
|
|
ivec3 coords = getOutputCoords();
|
|
|
|
vec4 result = vec4(0.);
|
|
int flatIndex, r, c, offset;
|
|
ivec3 localCoords;
|
|
vec2 uv;
|
|
vec4 values;
|
|
|
|
${r}
|
|
|
|
${n.output} = ${s};
|
|
}
|
|
`}},$I={};Le($I,{bindVertexProgramAttributeStreams:()=>WI,createBufferFromOutputTexture:()=>GI,createFloat16MatrixTexture:()=>MI,createFloat16PackedMatrixTexture:()=>BI,createFloat32MatrixTexture:()=>OI,createIndexBuffer:()=>FI,createPackedMatrixTexture:()=>LI,createUnsignedBytesMatrixTexture:()=>zI,createVertexBuffer:()=>PI,createVertexShader:()=>DI,downloadByteEncodedFloatMatrixFromOutputTexture:()=>jI,downloadFloat32MatrixFromBuffer:()=>HI,downloadMatrixFromPackedOutputTexture:()=>XI,downloadPackedMatrixFromBuffer:()=>qI,getInternalFormatForFloat16MatrixTexture:()=>f3,getInternalFormatForFloat16PackedMatrixTexture:()=>y3,getInternalFormatForFloat32MatrixTexture:()=>h3,getInternalFormatForPackedMatrixTexture:()=>g3,getInternalFormatForUnsignedBytesMatrixTexture:()=>m3,uploadDenseMatrixToTexture:()=>VI,uploadPixelDataToTexture:()=>UI});function DI(e){let t=Kn(),n=`${t.version}
|
|
precision highp float;
|
|
${t.attribute} vec3 clipSpacePos;
|
|
${t.attribute} vec2 uv;
|
|
${t.varyingVs} vec2 resultUV;
|
|
|
|
void main() {
|
|
gl_Position = vec4(clipSpacePos, 1);
|
|
resultUV = uv;
|
|
}`;return aI(e,n)}function PI(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 uI(e,t)}function FI(e){let t=new Uint16Array([0,1,2,2,1,3]);return cI(e,t)}function Lp(e,t,n,r,s,a){pI(t,n);let o=dI(e),i=e.TEXTURE_2D;return we(e,()=>e.bindTexture(i,o)),we(e,()=>e.texParameteri(i,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),we(e,()=>e.texParameteri(i,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),we(e,()=>e.texParameteri(i,e.TEXTURE_MIN_FILTER,e.NEAREST)),we(e,()=>e.texParameteri(i,e.TEXTURE_MAG_FILTER,e.NEAREST)),Y().getNumber("WEBGL_VERSION")===1?we(e,()=>e.texImage2D(i,0,r,t,n,0,s,a,null)):we(e,()=>e.texStorage2D(i,1,r,t,n)),we(e,()=>e.bindTexture(e.TEXTURE_2D,null)),{texture:o,texShape:[n,t]}}function h3(e){return e.internalFormatFloat}function OI(e,t,n,r){let[s,a]=zp(t,n);return Lp(e,s,a,h3(r),r.textureFormatFloat,e.FLOAT)}function f3(e){return e.internalFormatHalfFloat}function MI(e,t,n,r){let[s,a]=zp(t,n);return Lp(e,s,a,f3(r),r.textureFormatFloat,r.textureTypeHalfFloat)}function m3(e){return e.downloadTextureFormat}function zI(e,t,n,r){let[s,a]=zp(t,n);return Lp(e,s,a,m3(r),e.RGBA,e.UNSIGNED_BYTE)}function g3(e){return e.internalFormatPackedFloat}function LI(e,t,n,r){let[s,a]=kc(t,n);return Lp(e,s,a,g3(r),e.RGBA,e.FLOAT)}function y3(e){return e.internalFormatPackedHalfFloat}function BI(e,t,n,r){let[s,a]=kc(t,n);return Lp(e,s,a,y3(r),e.RGBA,r.textureTypeHalfFloat)}function WI(e,t,n){return we(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),Zg(e,t,"clipSpacePos",n,3,20,0)&&Zg(e,t,"uv",n,2,20,12)}function VI(e,t,n,r,s,a){we(e,()=>e.bindTexture(e.TEXTURE_2D,t));let o,i,l;s instanceof Uint8Array?(o=new Uint8Array(n*r*4),i=e.UNSIGNED_BYTE,l=e.RGBA):(o=new Float32Array(n*r*4),i=e.FLOAT,l=a.internalFormatPackedFloat),o.set(s),Y().getNumber("WEBGL_VERSION")===2?we(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n,r,e.RGBA,i,o)):we(e,()=>e.texImage2D(e.TEXTURE_2D,0,l,n,r,0,e.RGBA,i,o)),we(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function UI(e,t,n){we(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?Y().getNumber("WEBGL_VERSION")===2?we(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,n.width,n.height,e.RGBA,e.UNSIGNED_BYTE,n.data)):we(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):Y().getNumber("WEBGL_VERSION")===2?we(e,()=>e.texSubImage2D(e.TEXTURE_2D,0,0,0,e.RGBA,e.UNSIGNED_BYTE,n)):we(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),we(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function GI(e,t,n,r){let s=e.createBuffer();we(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,s));let i=4*4*t*n;return we(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,i,e.STREAM_READ)),we(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),we(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),s}function HI(e,t,n){let r=e,s=new Float32Array(n);return r.bindBuffer(r.PIXEL_PACK_BUFFER,t),r.getBufferSubData(r.PIXEL_PACK_BUFFER,0,s),r.bindBuffer(r.PIXEL_PACK_BUFFER,null),s}function jI(e,t,n,r){let[s,a]=zp(t,n),o=4,i=new Uint8Array(mQ(t*n,o));return we(e,()=>e.readPixels(0,0,s,a,r.downloadTextureFormat,e.UNSIGNED_BYTE,i)),new Float32Array(i.buffer)}function qI(e,t,n,r,s,a,o,i){let l=e,u=new Float32Array(gQ(a,o));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,u),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),u}function XI(e,t,n){let r=new Float32Array(t*n*4);return we(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,r)),r}var vu=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,v0(t,e)):this.gl=As(t);let n="WEBGL_color_buffer_float",r="EXT_color_buffer_half_float";if(this.parallelCompilationExtension=this.gl.getExtension("KHR_parallel_shader_compile"),Y().getNumber("WEBGL_VERSION")===1){let s="OES_texture_float",a="OES_texture_half_float";if(this.textureFloatExtension=Nd(this.gl,s),Er(this.gl,a))this.textureHalfFloatExtension=Nd(this.gl,a);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(n),Er(this.gl,r))this.colorBufferHalfFloatExtension=Nd(this.gl,r);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(n="EXT_color_buffer_float",Er(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else if(Er(this.gl,r))this.colorBufferHalfFloatExtension=this.gl.getExtension(r);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=PI(this.gl),this.indexBuffer=FI(this.gl),this.framebuffer=hI(this.gl),this.textureConfig=l3(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(),OI(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),MI(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),zI(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),UI(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,r){this.throwIfDisposed(),VI(this.gl,e,t,n,r,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),BI(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),LI(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(Yg(this.gl,this.framebuffer),this.outputTexture=null),we(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,()=>jI(this.gl,t,n,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,n,r,s,a){return qI(this.gl,e,t,n,r,s,a,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return HI(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);let r=GI(this.gl,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),r}createAndWaitForFence(){let e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n;if(Y().getBool("WEBGL_FENCE_API_ENABLED")){let r=e,s=r.fenceSync(r.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=()=>{let a=r.clientWaitSync(s,0,0);return a===r.ALREADY_SIGNALED||a===r.CONDITION_SATISFIED},t=s}else Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,()=>XI(this.gl,t,n))}createProgram(e){this.throwIfDisposed();let t=this.gl;this.vertexShader==null&&(this.vertexShader=DI(t));let n=iI(t);return we(t,()=>t.attachShader(n,this.vertexShader)),we(t,()=>t.attachShader(n,e)),lI(t,n),this.debug&&lf(t,n),this.vertexAttrsAreBound||(this.setProgram(n),this.vertexAttrsAreBound=WI(t,this.program,this.vertexBuffer)),n}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&we(this.gl,()=>this.gl.deleteProgram(e))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&lf(this.gl,this.program),we(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?mI(this.gl,e,t):gI(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),we(this.gl,()=>this.gl.getAttribLocation(e,t))}getUniformLocationNoThrow(e,t){return this.throwIfDisposed(),this.gl.getUniformLocation(e,t)}setInputMatrixTexture(e,t,n){this.throwIfDisposed(),this.throwIfNoProgram(),yI(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();let[r,s]=kc(t,n);this.setOutputMatrixTextureDriver(e,r,s)}setOutputMatrixWriteRegion(e,t,n,r){this.setOutputMatrixWriteRegionDriver(n,e,r,t)}setOutputPackedMatrixWriteRegion(e,t,n,r){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){this.program!=null&&lf(this.gl,this.program),Ed(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=Nd(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 n=this.gl,r=this.getQueryTimerExtensionWebGL2(),s=n.createQuery();return n.beginQuery(r.TIME_ELAPSED_EXT,s),s}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,n=this.getQueryTimerExtensionWebGL2();t.endQuery(n.TIME_ELAPSED_EXT);return}let e=this.getQueryTimerExtensionWebGL1();e.endQueryEXT(e.TIME_ELAPSED_EXT)}async waitForQueryAndGetTime(e){return await 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 n=this.gl;return n.getQueryParameter(e,n.QUERY_RESULT)/1e6}else{let n=this.getQueryTimerExtensionWebGL1();return n.getQueryObjectEXT(e,n.QUERY_RESULT_EXT)/1e6}}isQueryAvailable(e,t){if(t===0)return!0;if(t===2){let n=this.gl,r=this.getQueryTimerExtensionWebGL2(),s=n.getQueryParameter(e,n.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(r.GPU_DISJOINT_EXT)),s&&!this.disjoint}else{let n=this.getQueryTimerExtensionWebGL1(),r=n.getQueryObjectEXT(e,n.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),r&&!this.disjoint}}pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){let e=bee(this.itemsToPoll.map(t=>t.isDoneFn));for(let t=0;t<=e;++t){let{resolveFn:n}=this.itemsToPoll[t];n()}this.itemsToPoll=this.itemsToPoll.slice(e+1)}addItemToPoll(e,t){this.itemsToPoll.push({isDoneFn:e,resolveFn:t}),!(this.itemsToPoll.length>1)&&w.repeatedTry(()=>(this.pollItems(),this.itemsToPoll.length===0))}bindTextureToFrameBuffer(e){this.throwIfDisposed(),uf(this.gl,e,this.framebuffer),this.debug&&Ed(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(uf(this.gl,this.outputTexture,this.framebuffer),this.debug&&Ed(this.gl)):Yg(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);let n=t();return this.unbindTextureToFrameBuffer(),n}setOutputMatrixTextureDriver(e,t,n){this.throwIfDisposed();let r=this.gl;uf(r,e,this.framebuffer),this.debug&&Ed(r),this.outputTexture=e,we(r,()=>r.viewport(0,0,t,n)),we(r,()=>r.scissor(0,0,t,n))}setOutputMatrixWriteRegionDriver(e,t,n,r){this.throwIfDisposed(),we(this.gl,()=>this.gl.scissor(e,t,n,r))}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 bee(e){let t=0;for(;t<e.length&&e[t]();++t);return t-1}var{addImpl:vee,bincountImpl:KI,bincountReduceImpl:wee,ceilImpl:kee,concatImpl:See,equalImpl:Iee,expImpl:Cee,expm1Impl:Tee,floorImpl:Nee,gatherNdImpl:Eee,gatherV2Impl:Ree,greaterImpl:_ee,greaterEqualImpl:$ee,lessImpl:Dee,lessEqualImpl:Pee,linSpaceImpl:Fee,logImpl:Oee,maxImpl:Mee,maximumImpl:zee,minimumImpl:Lee,multiplyImpl:Bee,negImpl:Wee,notEqualImpl:Vee,prodImpl:Uee,rangeImpl:Gee,rsqrtImpl:Hee,sigmoidImpl:jee,simpleAbsImpl:ZI,sliceImpl:qee,sparseFillEmptyRowsImpl:Xee,sparseReshapeImpl:Kee,sparseSegmentReductionImpl:YI,sqrtImpl:Zee,stridedSliceImpl:Yee,stringNGramsImpl:Jee,stringSplitImpl:Qee,stringToHashBucketFastImpl:ete,subImpl:tte,tileImpl:nte,topKImpl:rte,transposeImpl:A3,uniqueImpl:ste}=x0;function JI(e,t){return["x","y","z","w","u","v"].slice(0,t).map(n=>`${e}.${n}`)}function Un(e,t){return t===1?[e]:JI(e,t)}function ate(e,t){if(e===1)return"rc";let n="";for(let r=0;r<e;r++)n+=t[r],r<e-1&&(n+=",");return n}var ote=class{constructor(e){if(this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outputShape=e,this.rank=e.length,this.enableShapeUniforms=lr(this.outputShape.length),this.rank===0)this.userCode=`
|
|
void main() {
|
|
setOutput(vec4(getA(), 0., 0., 0.));
|
|
}
|
|
`;else{let t=Un("rc",this.rank),n=yt(this.rank),r=this.getOutOfBoundsCondition(t),s=this.getSetup(t),a=this.getOutput(t);this.userCode=`
|
|
void main() {
|
|
${n} rc = getOutputCoords();
|
|
|
|
if(${r}) {
|
|
setOutput(vec4(0));
|
|
} else {
|
|
${s}
|
|
|
|
setOutput(vec4(${a}));
|
|
}
|
|
}
|
|
`}}getSourceCoordsArr(e){let t=[];for(let n=0;n<=1;n++)for(let r=0;r<=1;r++){let s=`${n===0?"r":"rp1"}, ${r===0?"c":"cp1"}`;for(let a=2;a<this.rank;a++)s=`${e[e.length-1-a]},`+s;t.push(s)}return t}getOutOfBoundsCondition(e){if(this.rank===1)return`rc > ${this.enableShapeUniforms?"outShape":this.outputShape[0]}`;let t="";for(let n=this.rank-2;n<this.rank;n++)t+=`${e[n]} >= ${this.enableShapeUniforms?`outShape[${n}]`:this.outputShape[n]}`,n<this.rank-1&&(t+="||");return t}getSetup(e){if(this.rank===1)return"";let t=e.slice(-2),n=this.enableShapeUniforms?`outShape[${this.rank} - 1]`:this.outputShape[this.rank-1],r=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 >= ${n};
|
|
bool rEdge = rp1 >= ${r};
|
|
`}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]})`}},QI=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"inputShape",type:"ivec3"}],this.outputShape=e,this.enableShapeUniforms=lr(this.outputShape.length);let n="";for(let r=0;r<4;r++){let s="thisRC = rc;";r%2===1&&(s+="thisRC.z += 1;"),r>1&&(s+="thisRC.y += 1;"),n+=`
|
|
${s}
|
|
${r>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[${r}] =
|
|
getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims);
|
|
${r>0?"}":""}
|
|
`}this.userCode=`
|
|
${ite(t,this.enableShapeUniforms)}
|
|
${this.enableShapeUniforms?d3():c3(e)}
|
|
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
|
|
vec4 result = vec4(0.);
|
|
|
|
ivec3 thisRC;
|
|
int rows = ${this.enableShapeUniforms?"outShape[1]":e[1]};
|
|
int cols = ${this.enableShapeUniforms?"outShape[2]":e[2]};
|
|
|
|
${n}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}};function ite(e,t){return`
|
|
ivec3 inputCoordsFromReshapedOutCoords(int index) {
|
|
${t?NQ(["r","c","d"],"inputShape"):Ml(["r","c","d"],e)}
|
|
return ivec3(r, c, d);
|
|
}
|
|
`}var lte=class{constructor(e){this.gpgpu=e,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0,this.freeTextures={},this.logEnabled=!1,this.usedTextures={}}acquireTexture(e,t,n){let r=Fv(t,n),s=Ov(e,r,n);s in this.freeTextures||(this.freeTextures[s]=[]),s in this.usedTextures||(this.usedTextures[s]=[]);let a=Pv(e,r,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[s].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=a,this.log();let i=this.freeTextures[s].shift();return this.usedTextures[s].push(i),i}let o;return r===3?o=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):r===4?o=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):r===1?o=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):r===0?o=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):r===2&&(o=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[s].push(o),this.numUsedTextures++,this._numBytesAllocated+=a,this.log(),o}releaseTexture(e,t,n,r){if(this.freeTextures==null)return;let s=Fv(n,r),a=Ov(t,s,r);a in this.freeTextures||(this.freeTextures[a]=[]);let o=Pv(t,s,this.gpgpu.gl,this.gpgpu.textureConfig,r),i=Y().get("WEBGL_DELETE_TEXTURE_THRESHOLD");i!==-1&&this._numBytesAllocated>i?(this.gpgpu.deleteMatrixTexture(e.texture),this._numBytesAllocated-=o):(this.freeTextures[a].push(e),this.numFreeTextures++,this._numBytesFree+=o),this.numUsedTextures--;let l=this.usedTextures[a],u=l.indexOf(e);if(u<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l.splice(u,1),this.log()}log(){if(!this.logEnabled)return;let e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);let t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures!=null){for(let e in this.freeTextures)this.freeTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});for(let e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t.texture)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}};function ute(e,t){let n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F)return 16;if(t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;if(t===n.RGBA8)return 4;throw new Error(`Unknown internal format ${t}`)}function Pv(e,t,n,r,s){let a=cte(t,r),o;if(s){let[l,u]=kc(e[0],e[1]);o=l*u}else{let[l,u]=zp(e[0],e[1]);o=l*u}let i=ute(n,a);return o*i}function cte(e,t){switch(e){case 3:return g3(t);case 4:return y3(t);case 1:return h3(t);case 0:return f3(t);case 2:return m3(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function dte(e){return Y().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?3:1:e?4:0}function Fv(e,t){if(e===1)return 3;if(e===0||e==null)return dte(t);if(e===3||e===2)return 2;throw new Error(`Unknown logical texture type ${e}`)}function Ov(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}var Zs=class{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.enableShapeUniforms=lr(this.outputShape.length),this.userCode=`
|
|
float unaryOperation(float x) {
|
|
${t}
|
|
}
|
|
|
|
void main() {
|
|
float x = getAAtOutCoords();
|
|
float y = unaryOperation(x);
|
|
|
|
setOutput(y);
|
|
}
|
|
`}},Yr="if (isnan(x)) return x;",pte="return x;",Mv="return abs(x);",hte="return (x >= 0.0) ? x : (exp(x) - 1.0);",fte=Yr+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,mte=Yr+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,cu="return x;",gte="return 1.0 / (1.0 + exp(-1.0 * x));",yte="return x;",Ate=`
|
|
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;
|
|
`,xte=`
|
|
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;
|
|
`,bte=`
|
|
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;
|
|
`,vte="return 1.0 / (1.0 + exp(-1.0 * x));",Ci=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.enableShapeUniforms=lr(this.outputShape.length),this.userCode=`
|
|
vec4 unaryOperation(vec4 x) {
|
|
${t}
|
|
}
|
|
|
|
void main() {
|
|
vec4 x = getAAtOutCoords();
|
|
vec4 y = unaryOperation(x);
|
|
|
|
setOutput(y);
|
|
}
|
|
`}},wte=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e,this.enableShapeUniforms=lr(this.outputShape.length);let t=e.length,n=Un("rc",t),r=yt(t),s=ate(t,n),a=n.slice(-2),o=t<=1?"rc":`vec2(${a.join(",")})`;this.userCode=`
|
|
void main() {
|
|
${r} rc = getOutputCoords();
|
|
vec4 packedInput = getA(${s});
|
|
|
|
setOutput(getChannel(packedInput, ${o}));
|
|
}
|
|
`}},kte=Kr.whereImpl,Ste=1e-7,Ite=1e-4,tf={};function Cte(e){return e in tf||(tf[e]={}),tf[e]}var Tte=Y().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),Nte=600;function Ete(){return Y().global.screen==null?1024:Y().global.screen.height*Y().global.screen.width*window.devicePixelRatio*Nte/1024/1024}var e8=class extends Ou{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 vu)t=e;else{let n=As(Y().getNumber("WEBGL_VERSION"),e);t=new vu(n)}this.binaryCache={},this.gpgpuCreatedLocally=!1}else{let n=As(Y().getNumber("WEBGL_VERSION"));t=new vu(n),this.binaryCache=Cte(Y().getNumber("WEBGL_VERSION")),this.gpgpuCreatedLocally=!0}this.gpgpu=t,this.canvas=this.gpgpu.gl.canvas,this.textureManager=new lte(this.gpgpu),this.numMBBeforeWarning=Ete(),this.texData=new Zd(this,sn())}nextDataId(){return e8.nextDataId++}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}write(e,t,n){if((Y().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||Y().getBool("DEBUG"))&&this.checkNumericalProblems(e),n==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let r={id:this.nextDataId()};return this.texData.set(r,{shape:t,dtype:n,values:e,usage:1,refCount:1}),r}refCount(e){return this.texData.has(e)?this.texData.get(e).refCount:0}incRef(e){let t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){let t=this.texData.get(e);t.refCount--}}move(e,t,n,r,s){if(Y().getBool("DEBUG")&&this.checkNumericalProblems(t),r==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:r,values:t,usage:1,refCount:s})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){let t=this.texData.get(e),{values:n,dtype:r,complexTensorInfos:s,slice:a,shape:o,isPacked:i}=t;if(a!=null){let p;i?p=new Ci(o,cu):p=new Zs(o,cu);let d=this.runWebGLProgram(p,[{dataId:e,shape:o,dtype:r}],r),h=this.readSync(d.dataId);return this.disposeIntermediateTensorInfo(d),h}if(n!=null)return this.convertAndCacheOnCPU(e);if(r==="string")return n;let l=this.activeTimers!=null,u;l&&(u=w.now());let c;if(r==="complex64"){let p=this.readSync(s.real.dataId),d=this.readSync(s.imag.dataId);c=C.mergeRealAndImagArrays(p,d)}else c=this.getValuesFromTexture(e);return l&&(this.downloadWaitMs+=w.now()-u),this.convertAndCacheOnCPU(e,c)}async read(e){if(this.pendingRead.has(e)){let h=this.pendingRead.get(e);return new Promise(f=>h.push(f))}let t=this.texData.get(e),{values:n,shape:r,slice:s,dtype:a,complexTensorInfos:o,isPacked:i}=t;if(s!=null){let h;i?h=new Ci(r,cu):h=new Zs(r,cu);let f=this.runWebGLProgram(h,[{dataId:e,shape:r,dtype:a}],a),m=this.read(f.dataId);return this.disposeIntermediateTensorInfo(f),m}if(n!=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(a!=="complex64"&&Y().get("WEBGL_BUFFER_SUPPORTED")){u=this.decode(e);let h=this.texData.get(u.dataId);l=this.gpgpu.createBufferFromTexture(h.texture.texture,...Qh(r))}this.pendingRead.set(e,[]),a!=="complex64"&&await this.gpgpu.createAndWaitForFence();let c;if(a==="complex64"){let h=await Promise.all([this.read(o.real.dataId),this.read(o.imag.dataId)]),f=h[0],m=h[1];c=C.mergeRealAndImagArrays(f,m)}else if(l==null)c=this.getValuesFromTexture(e);else{let h=w.sizeFromShape(r);c=this.gpgpu.downloadFloat32MatrixFromBuffer(l,h)}if(u!=null&&this.disposeIntermediateTensorInfo(u),l!=null){let h=this.gpgpu.gl;we(h,()=>h.deleteBuffer(l))}let p=this.convertAndCacheOnCPU(e,c),d=this.pendingRead.get(e);return this.pendingRead.delete(e),d.forEach(h=>h(p)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&sn().removeDataId(e,this),this.pendingDeletes--),p}readToGPU(e,t={}){let n=this.texData.get(e),{values:r,shape:s,slice:a,dtype:o,isPacked:i,texture:l}=n;if(o==="complex64")throw new Error("Does not support reading texture for complex64 dtype.");if(a!=null){let d;i?d=new Ci(s,cu):d=new Zs(s,cu);let h=this.runWebGLProgram(d,[{dataId:e,shape:s,dtype:o}],o),f=this.readToGPU(h,t);return this.disposeIntermediateTensorInfo(h),f}if(l==null)throw r!=null?new Error("Data is not on GPU but on CPU."):new Error("There is no data on GPU or CPU.");let u=this.decode(e,t.customTexShape),c=sn().makeTensorFromDataId(u.dataId,u.shape,u.dtype),p=this.texData.get(u.dataId);return{tensorRef:c,...p.texture}}bufferSync(e){let t=this.readSync(e.dataId),n=t;if(e.dtype==="string")try{n=t.map(r=>w.decodeString(r))}catch(r){throw new Error("Failed to decode encoded string bytes into utf-8")}return We(e.shape,e.dtype,n)}checkNumericalProblems(e){if(e!=null)for(let t=0;t<e.length;t++){let n=e[t];if(!rI(n))throw Y().getBool("WEBGL_RENDER_FLOAT32_CAPABLE")?Error(`The value ${n} cannot be represented with your current settings. Consider enabling float32 rendering: 'tf.env().set('WEBGL_RENDER_FLOAT32_ENABLED', true);'`):Error(`The value ${n} cannot be represented on this device.`)}}getValuesFromTexture(e){let{shape:t,dtype:n,isPacked:r}=this.texData.get(e),s=w.sizeFromShape(t);if(Y().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")){let p=this.decode(e),d=this.texData.get(p.dataId),h=this.gpgpu.downloadMatrixFromPackedTexture(d.texture.texture,...Qh(t)).subarray(0,s);return this.disposeIntermediateTensorInfo(p),h}let a=Y().getBool("WEBGL_PACK")&&r===!0,o=a?cf(t):t,i=a?new yee(o):new gee(o),l=this.runWebGLProgram(i,[{shape:o,dtype:n,dataId:e}],"float32"),u=this.texData.get(l.dataId),c=this.gpgpu.downloadByteEncodedFloatMatrixFromOutputTexture(u.texture.texture,u.texShape[0],u.texShape[1]).subarray(0,s);return this.disposeIntermediateTensorInfo(l),c}timerAvailable(){return Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0}time(e){let t=this.activeTimers,n=[],r=!1;this.programTimersStack==null?(this.programTimersStack=n,r=!0):this.activeTimers.push(n),this.activeTimers=n,e();let s=w.flatten(this.activeTimers.map(i=>i.query)).filter(i=>i!=null),a=w.flatten(this.activeTimers.map(i=>i.name)).filter(i=>i!=null);this.activeTimers=t,r&&(this.programTimersStack=null);let o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};return(async()=>{if(Y().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){let i=await Promise.all(s);o.kernelMs=w.sum(i),o.getExtraProfileInfo=()=>i.map((l,u)=>({name:a[u],ms:l})).map(l=>`${l.name}: ${l.ms}`).join(", ")}else o.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,o})()}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return 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:n}=this.texData.get(e);return n!=null&&(this.disposeData(n.real.dataId,t),this.disposeData(n.imag.dataId,t)),this.texData.delete(e),!0}releaseGPUData(e){let{texture:t,dtype:n,texShape:r,usage:s,isPacked:a,slice:o}=this.texData.get(e),i=o&&o.origDataId||e,l=this.dataRefCount.get(i);l>1?this.dataRefCount.set(i,l-1):(this.dataRefCount.delete(i),t!=null&&(this.numBytesInGPU-=this.computeBytes(r,n),this.textureManager.releaseTexture(t,r,s,a)));let u=this.texData.get(e);u.texture=null,u.texShape=null,u.isPacked=!1,u.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture.texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=Tte){return Y().getBool("WEBGL_CPU_FORWARD")&&e.every(n=>this.texData.get(n.dataId).texture==null&&w.sizeFromShape(n.shape)<t)}getGPGPUContext(){return this.gpgpu}where(e){C.warn("tf.where() in webgl locks the UI thread. Call tf.whereAsync() instead");let t=e.dataSync();return kte(e.shape,t)}packedUnaryOp(e,t,n){let r=new Ci(e.shape,t),s=this.compileAndRun(r,[e],n);return sn().makeTensorFromDataId(s.dataId,s.shape,s.dtype)}abs(e){if(this.shouldExecuteOnCPU([e])&&e.dtype!=="complex64"){let r=ZI(this.texData.get(e.dataId).values);return this.makeOutput(e.shape,e.dtype,r)}if(Y().getBool("WEBGL_PACK_UNARY_OPERATIONS"))return this.packedUnaryOp(e,Mv,e.dtype);let t=new Zs(e.shape,Mv),n=this.compileAndRun(t,[e]);return sn().makeTensorFromDataId(n.dataId,n.shape,n.dtype)}makeTensorInfo(e,t,n){let r;if(t==="string"&&n!=null&&n.length>0&&w.isString(n[0])){let s=n.map(a=>w.encodeString(a));r=this.write(s,e,t)}else r=this.write(n,e,t);return this.texData.get(r).usage=null,{dataId:r,shape:e,dtype:t}}makeOutput(e,t,n){let{dataId:r}=this.makeTensorInfo(e,t,n);return sn().makeTensorFromDataId(r,e,t,this)}unpackTensor(e){let t=new wte(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){let t=new ote(e.shape),n=!0;return this.runWebGLProgram(t,[e],e.dtype,null,n)}packedReshape(e,t){let n=[Li(e.shape),...Bi(e.shape)],r={dtype:e.dtype,shape:n,dataId:e.dataId},s=[Li(t),...Bi(t)],a=new QI(s,n),o=!0,i=[n],l=this.runWebGLProgram(a,[r],e.dtype,i,o);return{dataId:l.dataId,shape:t,dtype:l.dtype}}decode(e,t){let n=this.texData.get(e),{isPacked:r,shape:s,dtype:a}=n;if(t!=null){let p=w.sizeFromShape(s),d=t[0]*t[1]*4;w.assert(p<=d,()=>"customTexShape is too small. Row * Column * 4 should be equal or larger than the size of the tensor data.")}let o=cf(s),i;r?i=new mee(o):i=new fee(o);let l=!0,u=[t!=null?t:Qh(o)],c=this.runWebGLProgram(i,[{shape:o,dtype:a,dataId:e}],a,u,l,t);return{dtype:a,shape:s,dataId:c.dataId}}runWebGLProgram(e,t,n,r,s=!1,a){let o=this.makeTensorInfo(e.outputShape,n),i=this.texData.get(o.dataId);if(e.packedOutput&&(i.isPacked=!0),e.outPackingScheme===0){let g=a!=null?a:Qh(e.outputShape);i.texShape=g.map(y=>y*2)}if(e.outTexUsage!=null&&(i.usage=e.outTexUsage),w.sizeFromShape(o.shape)===0)return i.values=w.getTypedArrayFromDType(o.dtype,0),o;let l=[],u=t.map(g=>{if(g.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let y=this.texData.get(g.dataId);if(y.texture==null){if(!e.packedInputs&&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&&!Xd(y.shape,g.shape)){let x=g,A=g.shape;g.shape=y.shape,g=this.packedReshape(g,A),l.push(g),y=this.texData.get(g.dataId),x.shape=A}return{shape:g.shape,texData:y,isUniform:!1}});this.uploadToGPU(o.dataId);let c={shape:o.shape,texData:i,isUniform:!1},p=hee(e,u,c),d=this.getAndSaveBinary(p,()=>dee(this.gpgpu,e,u,c)),h=this.activeTimers!=null,f;h&&(f=this.startTimer()),Y().get("ENGINE_COMPILE_ONLY")||pee(this.gpgpu,d,u,c,r),l.forEach(g=>this.disposeIntermediateTensorInfo(g)),h&&(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")&&i.isPacked&&s===!1){let g=this.unpackTensor(o);return this.disposeIntermediateTensorInfo(o),g}return o}compileAndRun(e,t,n,r,s=!1){return n=n||t[0].dtype,this.runWebGLProgram(e,t,n,r,s)}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(t=>{this.gpgpu.deleteProgram(this.binaryCache[t].webGLProgram),delete this.binaryCache[t]}),this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement!="undefined"&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)}floatPrecision(){return this.floatPrecisionValue==null&&(this.floatPrecisionValue=K(()=>{if(!Y().get("WEBGL_RENDER_FLOAT32_ENABLED")){let e=Y().getBool("DEBUG");Y().set("DEBUG",!1);let t=this.abs(Ie(1e-8)).dataSync()[0];if(Y().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?Ste:Ite}uploadToGPU(e){let t=this.texData.get(e),{shape:n,dtype:r,values:s,texture:a,usage:o,isPacked:i}=t;if(a!=null)return;let l=this.activeTimers!=null,u;l&&(u=w.now());let c=t.texShape;if(c==null&&(c=bI(n,i),t.texShape=c),s!=null){let p=cf(n),d,h=c[1],f=c[0],m=s instanceof Uint8Array||s instanceof Uint8ClampedArray;(i||!m)&&([h,f]=kc(c[0],c[1])),i?d=new xee(p,m):d=new Aee(p,m);let g=m?[f,h]:c,y=this.makeTensorInfo(g,r),x=this.texData.get(y.dataId);m?x.usage=2:x.usage=1,x.texShape=g,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(y.dataId),h,f,s);let A=[[f,h]],b=!0,v=this.runWebGLProgram(d,[y],r,A,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 p=this.acquireTexture(c,o,r,i);t.texture=p}}convertAndCacheOnCPU(e,t){let n=this.texData.get(e),{dtype:r}=n;return this.releaseGPUData(e),t!=null&&(n.values=Rte(t,r)),n.values}acquireTexture(e,t,n,r){if(this.numBytesInGPU+=this.computeBytes(e,n),!this.warnedAboutMemory&&this.numBytesInGPU>this.numMBBeforeWarning*1024*1024){let s=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${s} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,r)}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 n=new Promise(r=>{try{this.checkCompletion_(t),r(!0)}catch(s){throw s}});e.push(n)}return Promise.all(e)}}async checkCompletionAsync_(e){return this.gpgpu.gl.getProgramParameter(e.webGLProgram,this.gpgpu.parallelCompilationExtension.COMPLETION_STATUS_KHR)?this.checkCompletion_(e):(await gA(),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?(u3(e.source,this.gpgpu.gl.getShaderInfoLog(e.fragmentShader)),new Error("Failed to compile fragment shader.")):new Error("Failed to link vertex and fragment shaders.");return!0}getUniformLocations(){for(let[,e]of Object.entries(this.binaryCache)){let{uniformLocations:t,customUniformLocations:n,infLoc:r,nanLoc:s,inShapesLocations:a,inTexShapesLocations:o,outShapeLocation:i,outShapeStridesLocation:l,outTexShapeLocation:u}=_I(this.gpgpu,e.program,e.webGLProgram);e.uniformLocations=t,e.customUniformLocations=n,e.infLoc=r,e.nanLoc=s,e.inShapesLocations=a,e.inTexShapesLocations=o,e.outShapeLocation=i,e.outShapeStridesLocation=l,e.outTexShapeLocation=u}}},Bp=e8;Bp.nextDataId=0;function Rte(e,t){if(t==="float32"||t==="complex64")return e;if(t==="int32"||t==="bool"){let n=t==="int32"?new Int32Array(e.length):new Uint8Array(e.length);for(let r=0;r<n.length;++r)n[r]=Math.round(e[r]);return n}else throw new Error(`Unknown dtype ${t}`)}var _te="0.0.0";function t8(){Y().set("WEBGL_FORCE_F16_TEXTURES",!0)}yp.isBrowser()&&Rl("webgl",()=>new Bp,2);var $te={forceHalfFloat:t8},n8=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,Fu=class{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=C.assertAndGetBroadcastShape(t,n),this.enableShapeUniforms=lr(this.outputShape.length),this.userCode=`
|
|
float binaryOperation(float a, float b) {
|
|
${e}
|
|
}
|
|
|
|
void main() {
|
|
float a = getAAtOutCoords();
|
|
float b = getBAtOutCoords();
|
|
setOutput(binaryOperation(a, b));
|
|
}
|
|
`}},k0=`
|
|
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;
|
|
`,Wp=class{constructor(e,t,n,r=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=C.assertAndGetBroadcastShape(t,n);let s=this.outputShape.length;this.enableShapeUniforms=lr(s);let a="";if(r)if(s===0||w.sizeFromShape(this.outputShape)===1)a=`
|
|
result.y = 0.;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;else if(a=`
|
|
${yt(s)} coords = getOutputCoords();
|
|
`,s===1)this.enableShapeUniforms?a+=`
|
|
result.y = (coords + 1) >= outShape ? 0. : result.y;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`:a+=`
|
|
result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y;
|
|
result.z = 0.;
|
|
result.w = 0.;
|
|
`;else{let i=Un("coords",s);this.enableShapeUniforms?a+=`
|
|
bool nextRowOutOfBounds =
|
|
(${i[s-2]} + 1) >= outShape[${s} - 2];
|
|
bool nextColOutOfBounds =
|
|
(${i[s-1]} + 1) >= outShape[${s} - 1];
|
|
result.y = nextColOutOfBounds ? 0. : result.y;
|
|
result.z = nextRowOutOfBounds ? 0. : result.z;
|
|
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
|
|
`:a+=`
|
|
bool nextRowOutOfBounds =
|
|
(${i[s-2]} + 1) >= ${this.outputShape[s-2]};
|
|
bool nextColOutOfBounds =
|
|
(${i[s-1]} + 1) >= ${this.outputShape[s-1]};
|
|
result.y = nextColOutOfBounds ? 0. : result.y;
|
|
result.z = nextRowOutOfBounds ? 0. : result.z;
|
|
result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w;
|
|
`}this.userCode=`
|
|
vec4 binaryOperation(vec4 a, vec4 b) {
|
|
${e}
|
|
}
|
|
|
|
void main() {
|
|
vec4 a = getAAtOutCoords();
|
|
vec4 b = getBAtOutCoords();
|
|
|
|
vec4 result = binaryOperation(a, b);
|
|
${a}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}};function or(e){let{inputs:t,backend:n}=e,{x:r}=t;return n.incRef(r.dataId),{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}var Dte={kernelName:go,backendName:"webgl",kernelFunc:or};function Xo(e){let{inputs:t,backend:n}=e,{real:r,imag:s}=t,a=n.makeTensorInfo(r.shape,"complex64"),o=n.texData.get(a.dataId),i=or({inputs:{x:r},backend:n}),l=or({inputs:{x:s},backend:n});return o.complexTensorInfos={real:i,imag:l},a}var Pte={kernelName:Jd,backendName:"webgl",kernelFunc:Xo},r8="return (a < 0.) ? b * a : a;",s8=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function Fte(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{alpha:a}=r,o=n.makeTensorInfo([],"float32",w.createScalarValue(a,"float32")),i=Y().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Wp(s8,s.shape,o.shape):new Fu(r8,s.shape,o.shape),l=n.runWebGLProgram(i,[s,o],"float32");return n.disposeIntermediateTensorInfo(o),l}var Ote={kernelName:yo,backendName:"webgl",kernelFunc:Fte},a8="return (a < 0.) ? b * a : a;",o8=`
|
|
vec4 aLessThanZero = vec4(lessThan(a, vec4(0.)));
|
|
return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a);
|
|
`;function Mte(e){let{inputs:t,backend:n}=e,{x:r,alpha:s}=t,a=Y().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Wp(o8,r.shape,s.shape):new Fu(a8,r.shape,s.shape);return n.runWebGLProgram(a,[r,s],"float32")}var zte={kernelName:Eo,backendName:"webgl",kernelFunc:Mte},Ec="if (isnan(x)) return x;",Lte=`
|
|
if (isnan(a)) return a;
|
|
if (isnan(b)) return b;
|
|
`,Bte=`
|
|
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 ot({opSnippet:e,packedOpSnippet:t,cpuKernelImpl:n,dtype:r}){return({inputs:s,backend:a})=>{let{x:o}=s,i=a,l=r||o.dtype;if(i.shouldExecuteOnCPU([o])&&n!=null){let p=i.texData.get(o.dataId),d=n(p.values,l);return i.makeTensorInfo(o.shape,l,d)}let u=Y().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,c;return u?c=new Ci(o.shape,t):c=new Zs(o.shape,e),i.runWebGLProgram(c,[o],l)}}function vn({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:r=!1,cpuKernelImpl:s,dtype:a}){return({inputs:o,backend:i})=>{let{a:l,b:u}=o,c=i;if(r&&l.dtype==="complex64"){let f=c.texData.get(l.dataId),m=c.texData.get(u.dataId),[g,y]=[[f.complexTensorInfos.real,m.complexTensorInfos.real],[f.complexTensorInfos.imag,m.complexTensorInfos.imag]].map(A=>{let[b,v]=A,S={dataId:b.dataId,dtype:b.dtype,shape:l.shape},I={dataId:v.dataId,dtype:v.dtype,shape:u.shape},E=new Fu(e,l.shape,u.shape);return c.runWebGLProgram(E,[S,I],Nn(b.dtype,v.dtype))}),x=Xo({inputs:{real:g,imag:y},backend:c});return c.disposeIntermediateTensorInfo(g),c.disposeIntermediateTensorInfo(y),x}let p=a||Nn(l.dtype,u.dtype);if((l.dtype==="string"||u.dtype==="string"||c.shouldExecuteOnCPU([l,u]))&&s!=null){let f=c.texData.get(l.dataId).values,m=c.texData.get(u.dataId).values,g=l.dtype==="string"?C.fromUint8ToStringArray(f):f,y=l.dtype==="string"?C.fromUint8ToStringArray(m):m,[x,A]=s(l.shape,u.shape,g,y,p),b=c.makeTensorInfo(A,p),v=c.texData.get(b.dataId);return v.values=x,b}let d=Y().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,h;return d?h=new Wp(t,l.shape,u.shape,n):h=new Fu(e,l.shape,u.shape),c.runWebGLProgram(h,[l,u],p)}}function S0(e,t=!1){if(e==="linear")return t?yte:pte;if(e==="relu")return t?xte:fte;if(e==="elu")return t?Ate:hte;if(e==="relu6")return t?bte:mte;if(e==="prelu")return t?o8:a8;if(e==="leakyrelu")return t?s8:r8;if(e==="sigmoid")return t?vte:gte;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}var i8=class{constructor(e,t,n,r=!1,s=!1,a=!1,o=null,i=!1,l=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n,this.enableShapeUniforms=lr(this.outputShape.length);let u=r?e[1]:e[2],c=Math.ceil(u/2),p=r?"i * 2, rc.y":"rc.y, i * 2",d=s?"rc.z, i * 2":"i * 2, rc.z",h=r?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],f=s?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],m="",g="";o&&(i?m=`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${o}
|
|
}`:l?m=`vec4 activation(vec4 a) {
|
|
vec4 b = getLeakyreluAlphaAtOutCoords();
|
|
${o}
|
|
}`:m=`vec4 activation(vec4 x) {
|
|
${o}
|
|
}`,g="result = activation(result);");let y=a?"result += getBiasAtOutCoords();":"";a&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),l&&this.variableNames.push("leakyreluAlpha");let x="rc.x",A="rc.x";e[0]<t[0]?x=`int(min(float(rc.x), ${e[0]-1}.))`:t[0]<e[0]&&(A=`int(min(float(rc.x), ${t[0]-1}.))`),this.userCode=`
|
|
${m}
|
|
// Don't use uniform for sharedDimensionPacked for performance.
|
|
const float sharedDimension = ${c}.0;
|
|
|
|
vec4 dot2x2ARowBCol(ivec3 rc) {
|
|
vec4 result = vec4(0);
|
|
for (int i = 0; i < ${c}; i++) {
|
|
int batchA = ${x};
|
|
int batchB = ${A};
|
|
vec4 a = getMatrixA(batchA, ${p});
|
|
vec4 b = getMatrixB(batchB, ${d});
|
|
|
|
// These swizzled products need to be separately added.
|
|
// See: https://github.com/tensorflow/tfjs/issues/1735
|
|
result += (${h[0]} * ${f[0]});
|
|
result += (${h[1]} * ${f[1]});
|
|
}
|
|
return result;
|
|
}
|
|
|
|
void main() {
|
|
ivec3 rc = getOutputCoords();
|
|
vec4 result = dot2x2ARowBCol(rc);
|
|
|
|
${y}
|
|
|
|
${g}
|
|
|
|
setOutput(result);
|
|
}
|
|
`}},zv={REAL:"return areal * breal - aimag * bimag;",IMAG:"return areal * bimag + aimag * breal;"},Lv=class{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.outputShape=C.assertAndGetBroadcastShape(t,n),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));
|
|
}
|
|
`}},Bv="return a * b;";function x3(e){let{inputs:t,backend:n}=e,{a:r,b:s}=t,a=C.upcastType(r.dtype,s.dtype);if(r.dtype==="complex64"){let i=n.texData.get(r.dataId),l=n.texData.get(s.dataId),u=new Lv(zv.REAL,r.shape,s.shape),c=new Lv(zv.IMAG,r.shape,s.shape),p=[{dataId:i.complexTensorInfos.real.dataId,dtype:i.complexTensorInfos.real.dtype,shape:r.shape},{dataId:i.complexTensorInfos.imag.dataId,dtype:i.complexTensorInfos.imag.dtype,shape:r.shape},{dataId:l.complexTensorInfos.real.dataId,dtype:l.complexTensorInfos.real.dtype,shape:s.shape},{dataId:l.complexTensorInfos.imag.dataId,dtype:l.complexTensorInfos.imag.dtype,shape:s.shape}],d=n.runWebGLProgram(u,p,"float32"),h=n.runWebGLProgram(c,p,"float32"),f=Xo({inputs:{real:d,imag:h},backend:n});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h),f}if(n.shouldExecuteOnCPU([r,s])){let i=n.texData.get(r.dataId),l=n.texData.get(s.dataId),[u,c]=Bee(r.shape,s.shape,i.values,l.values,a),p=n.makeTensorInfo(c,a),d=n.texData.get(p.dataId);return d.values=u,p}let o;return Y().getBool("WEBGL_PACK_BINARY_OPERATIONS")?o=new Wp(Bv,r.shape,s.shape):o=new Fu(Bv,r.shape,s.shape),n.runWebGLProgram(o,[r,s],a)}var Wte={kernelName:Co,backendName:"webgl",kernelFunc:x3};function Vte(e,t,n){let r=[Li(e.shape),...Bi(e.shape)],s={dtype:e.dtype,shape:r,dataId:e.dataId},a=[Li(t),...Bi(t)],o=new QI(a,r),i=!0,l=[r],u=n.runWebGLProgram(o,[s],e.dtype,l,i);return{dataId:u.dataId,shape:t,dtype:u.dtype}}function ve(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{shape:a}=r,o=n,i=w.sizeFromShape(s.shape),l=w.inferFromImplicitShape(a,i),u=w.sizeFromShape(l);w.assert(i===u,()=>`The new shape (${l}) has ${u} elements and the old shape (${s.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`);let c=o.texData.get(s.dataId);return c.isPacked&&!Xd(s.shape,l)&&!(c.texture!==null&&Xd(c.shape,l))?Vte(s,l,o):(o.incRef(s.dataId),{dataId:s.dataId,shape:l,dtype:s.dtype})}var Ute={kernelName:hl,backendName:"webgl",kernelFunc:ve},Wv=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:r,inSize:s,outSize:a}=e;this.outputShape=[r,a];let o=Math.floor(n/4)*4,i=n%4,l="sumValue += dot(values, ones);";if(t!=null){let c=1/t;l=`sumValue += dot(values * ${w.isInt(c)?c.toPrecision(2):c}, ones);`}let u="";s%n>0&&(u=`
|
|
if (inIdx < 0 || inIdx >= ${s}) {
|
|
return 0.0;
|
|
}
|
|
`),this.userCode=`
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
${u}
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = outIdx * ${n};
|
|
|
|
float sumValue = 0.0;
|
|
|
|
for (int i = 0; i < ${o}; i += 4) {
|
|
int inIdx = inOffset + i;
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
${l}
|
|
}
|
|
|
|
int inIdx = inOffset + ${o};
|
|
if (${i===1}) {
|
|
vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0);
|
|
|
|
${l}
|
|
} else if (${i===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1), 0.0, 0.0);
|
|
|
|
${l}
|
|
} else if (${i===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2), 0.0);
|
|
|
|
${l}
|
|
}
|
|
setOutput(sumValue);
|
|
}
|
|
`}},Gte=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:r,inSize:s,outSize:a}=e;this.outputShape=[r,a];let o="0.0",i="";t==="prod"?o="1.0":t==="min"?(o="1.0 / 1e-20",i="min"):t==="max"&&(o="-1.0 / 1e-20",i="max");let l=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?l="sumValue":t==="prod"?l="prodValue":t==="all"?l="allValue":t==="any"&&(l="anyValue");let u=Math.floor(n/4)*4,c=n%4,p=`
|
|
if (${t==="sum"}) {
|
|
sumValue += dot(values, ones);
|
|
} else if (${t==="prod"}) {
|
|
vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]);
|
|
prodValue *= tmp[0] * tmp[1];
|
|
} else {
|
|
minMaxValue = ${i}(values, minMaxValue);
|
|
if (${t==="min"} || ${t==="max"}) {
|
|
minMaxValue = ${i}(values, minMaxValue);
|
|
bvec4 isNaN = isnan(values);
|
|
if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) {
|
|
minMaxValue = vec4(NAN);
|
|
}
|
|
}
|
|
}
|
|
`,d="vec4";t==="all"?(o="1.0",p=`
|
|
bool reducedAllValue = all(values);
|
|
float floatedReducedAllValue = float(reducedAllValue);
|
|
allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0);
|
|
`,d="bvec4"):t==="any"&&(o="0.0",p=`
|
|
bool reducedAnyValue = any(values);
|
|
float floatedReducedAnyValue = float(reducedAnyValue);
|
|
anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0);
|
|
`,d="bvec4");let h="";s%n>0&&(h=`
|
|
if (inIdx < 0 || inIdx >= ${s}) {
|
|
return initializationValue;
|
|
}
|
|
`),this.userCode=`
|
|
const float initializationValue = ${o};
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
${h}
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = outIdx * ${n};
|
|
|
|
vec4 minMaxValue = vec4(${o});
|
|
float prodValue = 1.0;
|
|
float sumValue = 0.0;
|
|
float allValue = 1.0;
|
|
float anyValue = 0.0;
|
|
|
|
for (int i = 0; i < ${u}; i += 4) {
|
|
int inIdx = inOffset + i;
|
|
${d} values = ${d}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
${p}
|
|
}
|
|
|
|
int inIdx = inOffset + ${u};
|
|
if (${c===1}) {
|
|
${d} values = ${d}(
|
|
getValue(batch, inIdx),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${p}
|
|
} else if (${c===2}) {
|
|
${d} values = ${d}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${p}
|
|
} else if (${c===3}) {
|
|
${d} values = ${d}(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
initializationValue
|
|
);
|
|
|
|
${p}
|
|
}
|
|
setOutput(${l});
|
|
}
|
|
`}};function Hte(e){let t=[];for(;t.length===0||t[t.length-1].outSize!==1;){let n=t.length?t[t.length-1].outSize:e[1],r=C.computeOptimalWindowSize(n);t.push({inSize:n,windowSize:r,outSize:Math.ceil(n/r)})}return t}function Ll(e,t,n,r){let s=Hte(e.shape),a=e;for(let o=0;o<s.length;o++){let{inSize:i,windowSize:l,outSize:u}=s[o],c,p;n==="mean"?c=o===0?new Wv({windowSize:l,inSize:i,batchSize:e.shape[0],outSize:u},i):new Wv({windowSize:l,inSize:i,batchSize:e.shape[0],outSize:u}):c=new Gte({windowSize:l,inSize:i,batchSize:e.shape[0],outSize:u},n),p=a,a=r.runWebGLProgram(c,[a],t),p.dataId!==e.dataId&&r.disposeIntermediateTensorInfo(p)}return a}var jte=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let a=0;a<n.length;a++)n[a]=e[t[a]];this.outputShape=n,this.rank=n.length;let r=yt(this.rank),s=qte(t);this.userCode=`
|
|
void main() {
|
|
${r} resRC = getOutputCoords();
|
|
setOutput(getA(${s}));
|
|
}
|
|
`}};function qte(e){let t=e.length;if(t>6)throw Error(`Transpose for rank ${t} is not yet supported`);let n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],r=new Array(t);for(let s=0;s<e.length;s++)r[e[s]]=n[s];return r.join()}var Xte=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0;let n=new Array(e.length);for(let u=0;u<n.length;u++)n[u]=e[t[u]];if(this.outputShape=n,this.rank=n.length,this.rank>6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let r=yt(this.rank),s=JI("rc",this.rank),a=new Array(this.rank);for(let u=0;u<t.length;u++)a[t[u]]=s[u];let o=`vec2(${a.slice(-2).join()})`,i=`++${s[this.rank-1]} < ${n[this.rank-1]}`,l=`getChannel(getA(${a.join()}), ${o})`;this.userCode=`
|
|
void main() {
|
|
${r} rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result[0] = ${l};
|
|
if(${i}) {
|
|
result[1] = ${l};
|
|
}
|
|
--${s[this.rank-1]};
|
|
if(++${s[this.rank-2]} < ${n[this.rank-2]}) {
|
|
result[2] = ${l};
|
|
if(${i}) {
|
|
result[3] = ${l};
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}};function I0(e,t,n){let r=Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Xte(e.shape,t):new jte(e.shape,t);return n.runWebGLProgram(r,[e],e.dtype)}function Kte(e,t,n,r){let s=t,a=e.shape.length,o=w.parseAxisParam(s,e.shape),i=o,l=C.getAxesPermutation(i,a),u=l!=null,c=e;u&&(c=I0(e,l,r),i=C.getInnerMostAxes(i.length,a)),C.assertAxesAreInnerMostDims("sum",i,a);let[p,d]=C.computeOutAndReduceShapes(c.shape,i),h=p;n&&(h=C.expandShapeToKeepDim(p,o));let f=w.sizeFromShape(d),g=w.sizeFromShape(e.shape)/f,y=ve({inputs:{x:c},attrs:{shape:[g,f]},backend:r}),x=gp(e.dtype),A=Ll(y,x,"sum",r),b=ve({inputs:{x:A},attrs:{shape:h},backend:r});return r.disposeIntermediateTensorInfo(y),r.disposeIntermediateTensorInfo(A),u&&r.disposeIntermediateTensorInfo(c),b}function C0(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r;return Kte(s,a,o,n)}var Zte={kernelName:zo,backendName:"webgl",kernelFunc:C0};function bn(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{perm:a}=r,o=n,i=s.shape.length,l=new Array(i);for(let c=0;c<l.length;c++)l[c]=s.shape[a[c]];let u;if(o.shouldExecuteOnCPU([s])){let p=o.texData.get(s.dataId).values,d=A3(p,s.shape,s.dtype,a,l);u=o.makeTensorInfo(l,s.dtype);let h=o.texData.get(u.dataId);h.values=d}else u=I0(s,a,o);return u}var Yte={kernelName:Uo,backendName:"webgl",kernelFunc:bn},l8=1e3;function Uf({a:e,b:t,transposeA:n,transposeB:r,backend:s,bias:a=null,preluActivationWeights:o=null,leakyreluAlpha:i=0,activation:l=null}){let u=e.shape.length,c=t.shape.length,p=n?e.shape[u-2]:e.shape[u-1],d=r?t.shape[c-1]:t.shape[c-2],h=n?e.shape[u-1]:e.shape[u-2],f=r?t.shape[c-2]:t.shape[c-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),y=w.sizeFromShape(m),x=w.sizeFromShape(g),b=El.assertAndGetBroadcastShape(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([h,f]);w.assert(p===d,()=>`Error in matMul: inner shapes (${p}) and (${d}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${r} must match.`);let v=n?[y,p,h]:[y,h,p],S=r?[x,f,d]:[x,d,f],I=ve({inputs:{x:e},backend:s,attrs:{shape:v}}),E=ve({inputs:{x:t},backend:s,attrs:{shape:S}}),R=[I,E],P=Math.max(y,x),_=n?I.shape[1]:I.shape[2],D=a!=null,T=o!=null,F=l==="leakyrelu",U=l!=null?S0(l,!0):null,X=D||T||F||U!=null,z;if((h===1||f===1)&&_>l8&&X===!1){let W=I,ee=E;n&&(W=bn({inputs:{x:I},backend:s,attrs:{perm:[0,2,1]}}),R.push(W)),r&&(ee=bn({inputs:{x:E},backend:s,attrs:{perm:[0,2,1]}}),R.push(ee));let Q=f!==1,ae=f===1,J=W;Q&&(J=ve({inputs:{x:W},backend:s,attrs:{shape:[P,_,1]}}),R.push(J));let se=f===1?2:1,ie=ee;ae&&(ie=ve({inputs:{x:ee},backend:s,attrs:{shape:[P,1,_]}}),R.push(ie));let me=x3({inputs:{a:J,b:ie},backend:s});z=C0({inputs:{x:me},backend:s,attrs:{axis:se,keepDims:!0}}),R.push(me)}else{let W=Nn(e.dtype,t.dtype),ee=new i8(v,S,[P,h,f],n,r,D,U,T,F),Q=[I,E];if(a!=null&&Q.push(a),T&&Q.push(o),F){let ae=s.makeTensorInfo([],"float32",w.createScalarValue(i,"float32"));Q.push(ae),R.push(ae)}z=s.runWebGLProgram(ee,Q,W)}let Z=ve({inputs:{x:z},backend:s,attrs:{shape:b}});R.push(z);for(let W of R)s.disposeIntermediateTensorInfo(W);return Z}function Jte(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a,bias:o,preluActivationWeights:i}=t,{transposeA:l,transposeB:u,activation:c,leakyreluAlpha:p}=r;return Uf({a:s,b:a,transposeA:l,transposeB:u,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:p,activation:c})}var Qte={kernelName:Pa,backendName:"webgl",kernelFunc:Jte},Vv="return abs(x);";function ene(e){let{inputs:t,backend:n}=e,{x:r}=t;if(n.shouldExecuteOnCPU([r])&&r.dtype!=="complex64"){let a=n.texData.get(r.dataId),o=ZI(a.values);return n.makeTensorInfo(r.shape,r.dtype,o)}let s;return Y().getBool("WEBGL_PACK_UNARY_OPERATIONS")?s=new Ci(r.shape,Vv):s=new Zs(r.shape,Vv),n.runWebGLProgram(s,[r],r.dtype)}var tne={kernelName:Gi,backendName:"webgl",kernelFunc:ene},nne=Yr+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return acos(x);
|
|
`,rne=ot({opSnippet:nne}),sne={kernelName:zu,backendName:"webgl",kernelFunc:rne},ane=Yr+`
|
|
if (x < 1.0) return NAN;
|
|
return log(x + sqrt(x * x - 1.0));`,one=ot({opSnippet:ane}),ine={kernelName:Lu,backendName:"webgl",kernelFunc:one},Uv="return a + b;",lne=vn({opSnippet:Uv,packedOpSnippet:Uv,supportsComplex:!0,cpuKernelImpl:vee}),une={kernelName:ea,backendName:"webgl",kernelFunc:lne},cne=class{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((s,a)=>`T${a}`);let n=[];this.variableNames.forEach(s=>{n.push(`float v${s} = get${s}AtOutCoords();`)});let r=this.variableNames.map(s=>`v${s}`).join(" + ");this.userCode=`
|
|
void main() {
|
|
${n.join(`
|
|
`)}
|
|
|
|
float result = ${r};
|
|
setOutput(result);
|
|
}
|
|
`}},dne=class{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((s,a)=>`T${a}`);let n=[];this.variableNames.forEach(s=>{n.push(`vec4 v${s} = get${s}AtOutCoords();`)});let r=this.variableNames.map(s=>`v${s}`).join(" + ");this.userCode=`
|
|
void main() {
|
|
${n.join(`
|
|
`)}
|
|
|
|
vec4 result = ${r};
|
|
setOutput(result);
|
|
}
|
|
`}};function hf(e){let{inputs:t,backend:n}=e,r=t;if(r.length===1)return or({inputs:{x:r[0]},backend:n});if(r.length>Y().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let l=Math.floor(r.length/2),u=hf({inputs:r.slice(0,l),backend:n}),c=hf({inputs:r.slice(l),backend:n});return hf({inputs:[u,c],backend:n})}let s=r.map(l=>l.dtype).reduce((l,u)=>Nn(l,u)),a=r.map(l=>l.shape),i=Y().getBool("WEBGL_PACK")?new dne(r[0].shape,a):new cne(r[0].shape,a);return n.runWebGLProgram(i,r,s)}var pne={kernelName:Za,backendName:"webgl",kernelFunc:hf};function hne(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,l=w.parseAxisParam(a,s.shape),u=l,c=C.getAxesPermutation(u,i),p=s;c!=null&&(p=bn({inputs:{x:s},backend:n,attrs:{perm:c}}),u=C.getInnerMostAxes(u.length,i)),C.assertAxesAreInnerMostDims("all",u,i);let[d,h]=C.computeOutAndReduceShapes(p.shape,u),f=w.sizeFromShape(h),m=ve({inputs:{x:p},backend:n,attrs:{shape:[-1,f]}}),g=Ll(m,m.dtype,"all",n),y;if(o){let x=C.expandShapeToKeepDim(d,l);y=ve({inputs:{x:g},backend:n,attrs:{shape:x}})}else y=ve({inputs:{x:g},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),c!=null&&n.disposeIntermediateTensorInfo(p),y}var fne={kernelName:Bu,backendName:"webgl",kernelFunc:hne};function mne(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,l=w.parseAxisParam(a,s.shape),u=l,c=C.getAxesPermutation(u,i),p=s;c!=null&&(p=bn({inputs:{x:s},backend:n,attrs:{perm:c}}),u=C.getInnerMostAxes(u.length,i)),C.assertAxesAreInnerMostDims("any",u,i);let[d,h]=C.computeOutAndReduceShapes(p.shape,u),f=w.sizeFromShape(h),m=ve({inputs:{x:p},backend:n,attrs:{shape:[-1,f]}}),g=Ll(m,m.dtype,"any",n),y;if(o){let x=C.expandShapeToKeepDim(d,l);y=ve({inputs:{x:g},backend:n,attrs:{shape:x}})}else y=ve({inputs:{x:g},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),c!=null&&n.disposeIntermediateTensorInfo(p),y}var gne={kernelName:Wu,backendName:"webgl",kernelFunc:mne},yne=class{constructor(e,t,n){this.variableNames=["A"];let{windowSize:r,batchSize:s,outSize:a}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[s,a];let o=t==="max"?">":"<",i=n?"inOffset + i;":"round(getBestIndicesA(batch, inOffset + i));";this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = outIdx * ${r};
|
|
|
|
int bestIndex = inOffset;
|
|
float bestValue = getA(batch, bestIndex);
|
|
|
|
for (int i = 0; i < ${r}; i++) {
|
|
int inIdx = ${i};
|
|
float candidate = getA(batch, inIdx);
|
|
if (candidate ${o} bestValue) {
|
|
bestValue = candidate;
|
|
bestIndex = inIdx;
|
|
}
|
|
}
|
|
setOutput(float(bestIndex));
|
|
}
|
|
`}},Ane=class{constructor(e,t,n,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,w.assert(e.length>2,()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`);let s=e[e.length-1],a=Math.ceil(s/t);this.outputShape=e.slice(0,-1),a>1&&this.outputShape.push(a),r||this.variableNames.push("bestIndicesA");let o=this.outputShape,i=o.length,l=yt(i),u=Un("coords",i),c,p;if(a===1){p=i+1;let I=yt(p);c=`
|
|
${I} sourceLocR = ${I}(${u.join()}, 0);
|
|
++${u[i-1]};
|
|
${I} sourceLocG = ${I}(${u.join()}, 0);
|
|
++${u[i-2]};
|
|
${I} sourceLocA = ${I}(${u.join()}, 0);
|
|
--${u[i-1]};
|
|
${I} sourceLocB = ${I}(${u.join()}, 0);
|
|
--${u[i-2]};`}else p=i,c=`
|
|
${l} sourceLocR = coords;
|
|
++${u[i-1]};
|
|
${l} sourceLocG = coords;
|
|
++${u[i-2]};
|
|
${l} sourceLocA = coords;
|
|
--${u[i-1]};
|
|
${l} sourceLocB = coords;
|
|
--${u[i-2]};`;let d=["x","y","z","w","u","v"].slice(0,p),h="."+d[p-1],f=d.map(I=>"int "+I),m=Un("sourceLocR",p-1).concat("inIdx.r"),g=Un("sourceLocG",p-1).concat("inIdx.g"),y=Un("sourceLocB",p-1).concat("inIdx.b"),x=Un("sourceLocA",p-1).concat("inIdx.a"),A=n==="max"?"greaterThan":"lessThan",b=r?"":`
|
|
inIdx = round(vec4(getBestIndicesAChannel(${m.join()}),
|
|
getBestIndicesAChannel(${g.join()}),
|
|
getBestIndicesAChannel(${y.join()}),
|
|
getBestIndicesAChannel(${x.join()})));`,v=`vec4(
|
|
getAChannel(${m.join()}),
|
|
hasNextCol ? getAChannel(${g.join()}) : 0.,
|
|
hasNextRow ? getAChannel(${y.join()}) : 0.,
|
|
hasNextRow && hasNextCol ? getAChannel(${x.join()}) : 0.)`,S=r?"":`
|
|
float getBestIndicesAChannel(${f.join()}) {
|
|
return getChannel(getBestIndicesA(${d.join()}),
|
|
vec2(${d.slice(-2).join()}));
|
|
}`;this.userCode=`
|
|
float getAChannel(${f.join()}) {
|
|
return getChannel(getA(${d.join()}),
|
|
vec2(${d.slice(-2).join()}));
|
|
}
|
|
${S}
|
|
void main() {
|
|
${l} coords = getOutputCoords();
|
|
bool hasNextCol = ${u[i-1]} < ${o[i-1]-1};
|
|
bool hasNextRow = ${u[i-2]} < ${o[i-2]-1};
|
|
${c}
|
|
ivec4 srcIdx = ivec4(sourceLocR${h}, sourceLocG${h},
|
|
sourceLocB${h}, sourceLocA${h}) * ${t};
|
|
ivec4 inIdx = srcIdx;
|
|
vec4 bestIndex = vec4(inIdx);
|
|
vec4 bestValue = ${v};
|
|
|
|
for (int i = 0; i < ${t}; i++) {
|
|
inIdx = srcIdx;
|
|
${b}
|
|
vec4 candidate = ${v};
|
|
bvec4 nan = isnan(candidate);
|
|
bvec4 replace = bvec4(
|
|
vec4(${A}(candidate, bestValue)) * (vec4(1.0) - vec4(nan)));
|
|
|
|
bestValue = vec4(replace.x ? candidate.x : bestValue.x,
|
|
replace.y ? candidate.y : bestValue.y,
|
|
replace.z ? candidate.z : bestValue.z,
|
|
replace.w ? candidate.w : bestValue.w);
|
|
bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace));
|
|
srcIdx++;
|
|
}
|
|
setOutput(bestIndex);
|
|
}
|
|
`}};function u8(e,t,n,r=null){let s=t.shape[0],a=t.shape[1];r!=null&&(s=r.shape[0],a=r.shape[1]);let o=C.computeOptimalWindowSize(a),i={windowSize:o,inSize:a,batchSize:s,outSize:Math.ceil(a/o)},l=new yne(i,n,r==null),u=[t];r!=null&&u.push(r);let c=e.runWebGLProgram(l,u,"int32");if(c.shape[1]===1)return c;let p=u8(e,t,n,c);return e.disposeIntermediateTensorInfo(c),p}function c8(e,t,n,r=null){let s=r!=null?r.shape:t.shape,a=s[s.length-1],o=C.computeOptimalWindowSize(a),i=new Ane(s,o,n,r==null),l=r==null?[t]:[t,r],u=e.runWebGLProgram(i,l,"int32");if(u.shape.length===t.shape.length){let c=c8(e,t,n,u);return e.disposeIntermediateTensorInfo(u),c}return u}function d8(e,t,n,r){let s=[n];if(C.assertAxesAreInnerMostDims("arg"+r.charAt(0).toUpperCase()+r.slice(1),s,t.shape.length),!Y().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){let a=[],o=e.texData.get(t.dataId),i=o!==null&&o.isPacked,l=t;i&&(l=e.unpackTensor(t),a.push(l));let[u,c]=C.computeOutAndReduceShapes(l.shape,s),p=w.sizeFromShape(c),d=ve({inputs:{x:l},backend:e,attrs:{shape:[-1,p]}});a.push(d);let h=u8(e,d,r);a.push(h);let f=ve({inputs:{x:h},backend:e,attrs:{shape:u}});return a.forEach(m=>e.disposeIntermediateTensorInfo(m)),f}return c8(e,t,r)}function xne(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r,o=w.parseAxisParam(a,s.shape),i=C.getAxesPermutation(o,s.shape.length),l=s,u=[];i!=null&&(l=bn({inputs:{x:s},backend:n,attrs:{perm:i}}),u.push(l),o=C.getInnerMostAxes(o.length,l.shape.length)),C.assertAxesAreInnerMostDims("argMax",[o[0]],l.shape.length);let c=d8(n,l,o[0],"max");return u.forEach(p=>n.disposeIntermediateTensorInfo(p)),c}var bne={kernelName:Ya,backendName:"webgl",kernelFunc:xne};function vne(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r,o=w.parseAxisParam(a,s.shape),i=C.getAxesPermutation(o,s.shape.length),l=s,u=[];i!=null&&(l=bn({inputs:{x:s},backend:n,attrs:{perm:i}}),u.push(l),o=C.getInnerMostAxes(o.length,l.shape.length)),C.assertAxesAreInnerMostDims("argMin",[o[0]],l.shape.length);let c=d8(n,l,o[0],"min");return u.forEach(p=>n.disposeIntermediateTensorInfo(p)),c}var wne={kernelName:Vu,backendName:"webgl",kernelFunc:vne},kne=Yr+`
|
|
if (abs(x) > 1.) {
|
|
return NAN;
|
|
}
|
|
return asin(x);
|
|
`,Sne=ot({opSnippet:kne}),Ine={kernelName:Uu,backendName:"webgl",kernelFunc:Sne},Cne=Yr+"return log(x + sqrt(x * x + 1.0));",Tne=ot({opSnippet:Cne}),Nne={kernelName:Gu,backendName:"webgl",kernelFunc:Tne},Ene=Yr+`
|
|
return atan(x);
|
|
`,Rne=ot({opSnippet:Ene}),_ne={kernelName:Hu,backendName:"webgl",kernelFunc:Rne},$ne=Lte+`
|
|
return atan(a, b);
|
|
`,Dne=`
|
|
vec4 result = atan(a, b);
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+Bte+`
|
|
return result;
|
|
`,Pne=vn({opSnippet:$ne,packedOpSnippet:Dne}),Fne={kernelName:qu,backendName:"webgl",kernelFunc:Pne},One=Yr+`
|
|
if ((x < -1.0) || (x > 1.0)) return NAN;
|
|
return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,Mne=ot({opSnippet:One}),zne={kernelName:ju,backendName:"webgl",kernelFunc:Mne},Kd=class{constructor(e,t,n,r=!1,s=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,o=e.strideHeight,i=e.strideWidth,l=e.dilationHeight,u=e.dilationWidth,c=e.effectiveFilterHeight,p=e.effectiveFilterWidth,d=e.padInfo.top,h=e.padInfo.left;this.outputShape=e.outShape;let f=t==="avg",m=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`,y="0.0";if(f||(y="-1.0 / 1e-20"),n){let I=">=";this.userCode=`
|
|
const ivec2 strides = ivec2(${o}, ${i});
|
|
const ivec2 pads = ivec2(${d}, ${h});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d = coords[3];
|
|
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// max/min x(?, ?, d) to get y(yR, yC, d).
|
|
// ? = to be determined
|
|
float minMaxValue = 0.0;
|
|
float minMaxValueFound = 0.0;
|
|
int minMaxPosition = 0;
|
|
float avgValue = 0.0;
|
|
|
|
for (int wR = 0; wR < ${c};
|
|
wR += ${l}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${p};
|
|
wC += ${u}) {
|
|
int xC = xCCorner + wC;
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
float value = getX(batch, xR, xC, d);
|
|
|
|
// If a min / max value has already been found, use it. If not,
|
|
// use the current value.
|
|
float currMinMaxValue = mix(
|
|
value, minMaxValue, minMaxValueFound);
|
|
if (value ${I} currMinMaxValue) {
|
|
minMaxValue = value;
|
|
minMaxValueFound = 1.0;
|
|
minMaxPosition = ${r?s?m:g:`wR * ${p} + wC`};
|
|
}
|
|
}
|
|
}
|
|
setOutput(float(minMaxPosition));
|
|
}
|
|
`;return}let x="max",A=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(A="avgValue / count");let b=Math.floor(a/4)*4,v=a%4,S=`
|
|
if (${f}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${x}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec2 strides = ivec2(${o}, ${i});
|
|
const ivec2 pads = ivec2(${d}, ${h});
|
|
const float initializationValue = ${y};
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float count = 0.0;
|
|
|
|
float getValue(int batch, int xR, int xC, int d) {
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
return initializationValue;
|
|
}
|
|
count += 1.0;
|
|
return getX(batch, xR, xC, d);
|
|
}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d = coords[3];
|
|
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// max/min x(?, ?, d) to get y(yR, yC, d).
|
|
// ? = to be determined
|
|
vec4 minMaxValue = vec4(${y});
|
|
float avgValue = 0.0;
|
|
count = 0.0;
|
|
|
|
for (int wR = 0; wR < ${c};
|
|
wR += ${l}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${b}; wC += 4) {
|
|
int xC = xCCorner + wC * ${u};
|
|
|
|
vec4 values = vec4(
|
|
getValue(batch, xR, xC, d),
|
|
getValue(batch, xR, xC + ${u}, d),
|
|
getValue(batch, xR, xC + 2 * ${u}, d),
|
|
getValue(batch, xR, xC + 3 * ${u}, d)
|
|
);
|
|
|
|
${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(${A});
|
|
}
|
|
`}},b3=class{constructor(e,t,n,r=!1,s=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let a=e.filterWidth,o=e.strideDepth,i=e.strideHeight,l=e.strideWidth,u=e.dilationDepth,c=e.dilationHeight,p=e.dilationWidth,d=e.effectiveFilterDepth,h=e.effectiveFilterHeight,f=e.effectiveFilterWidth,m=e.padInfo.front,g=e.padInfo.top,y=e.padInfo.left;this.outputShape=e.outShape;let x=t==="avg",A="0.0";if(x||(A="-1.0 / 1e-20"),n){let R=">=";this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${o}, ${i}, ${l});
|
|
const ivec3 pads = ivec3(${m}, ${g}, ${y});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
|
|
int xDCorner = xCorner.x;
|
|
int xRCorner = xCorner.y;
|
|
int xCCorner = xCorner.z;
|
|
|
|
// max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch).
|
|
// ? = to be determined
|
|
float minMaxValue = 0.0;
|
|
float minMaxValueFound = 0.0;
|
|
int minMaxPosition = 0;
|
|
|
|
for (int wD = 0; wD < ${d};
|
|
wD += ${u}) {
|
|
int xD = xDCorner + wD;
|
|
|
|
if (xD < 0 || xD >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${h};
|
|
wR += ${c}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${f};
|
|
wC += ${p}) {
|
|
int xC = xCCorner + wC;
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
float value = getX(batch, xD, xR, xC, ch);
|
|
|
|
// If a min / max value has already been found, use it. If not,
|
|
// use the current value.
|
|
float currMinMaxValue = mix(
|
|
value, minMaxValue, minMaxValueFound);
|
|
if (value ${R} currMinMaxValue) {
|
|
minMaxValue = value;
|
|
minMaxValueFound = 1.0;
|
|
minMaxPosition = ${r?s?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${h} * ${f} +
|
|
wR * ${f} + wC`};
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(float(minMaxPosition));
|
|
}
|
|
`;return}let b="max",v=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(v="avgValue / count");let S=Math.floor(a/4)*4,I=a%4,E=`
|
|
if (${x}) {
|
|
avgValue += dot(values, ones);
|
|
} else {
|
|
minMaxValue = ${b}(values, minMaxValue);
|
|
}
|
|
`;this.userCode=`
|
|
const ivec3 strides =
|
|
ivec3(${o}, ${i}, ${l});
|
|
const ivec3 pads = ivec3(${m}, ${g}, ${y});
|
|
const float initializationValue = ${A};
|
|
const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0);
|
|
|
|
float count = 0.0;
|
|
|
|
float getValue(int batch, int xD, int xR, int xC, int ch) {
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
return initializationValue;
|
|
}
|
|
count += 1.0;
|
|
return getX(batch, xD, xR, xC, ch);
|
|
}
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
|
|
int xDCorner = xCorner.x;
|
|
int xRCorner = xCorner.y;
|
|
int xCCorner = xCorner.z;
|
|
|
|
// max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch).
|
|
// ? = to be determined
|
|
vec4 minMaxValue = vec4(${A});
|
|
float avgValue = 0.0;
|
|
count = 0.0;
|
|
|
|
for (int wD = 0; wD < ${d};
|
|
wD += ${u}) {
|
|
int xD = xDCorner + wD;
|
|
|
|
if (xD < 0 || xD >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${h};
|
|
wR += ${c}) {
|
|
int xR = xRCorner + wR;
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${S}; wC += 4) {
|
|
int xC = xCCorner + wC * ${p};
|
|
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${p}, ch),
|
|
getValue(batch, xD, xR, xC + 2 * ${p}, ch),
|
|
getValue(batch, xD, xR, xC + 3 * ${p}, ch)
|
|
);
|
|
|
|
${E}
|
|
}
|
|
|
|
int xC = xCCorner + ${S};
|
|
if (${I===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${E}
|
|
} else if (${I===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${p}, ch),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
${E}
|
|
} else if (${I===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, xD, xR, xC, ch),
|
|
getValue(batch, xD, xR, xC + ${p}, ch),
|
|
getValue(batch, xD, xR, xC + 2 * ${p}, ch),
|
|
initializationValue
|
|
);
|
|
|
|
${E}
|
|
}
|
|
}
|
|
setOutput(${v});
|
|
}
|
|
}
|
|
`}};function Lne(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t;Sc(s,"avgPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=r,u=1;w.assert(C.eitherStridesOrDilationsAreOne(o,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${u}'`);let c=C.computePool2DInfo(s.shape,a,o,u,i,l);if(c.filterWidth===1&&c.filterHeight===1&&w.arraysEqual(c.inShape,c.outShape))return or({inputs:{x:s},backend:n});let p=new Kd(c,"avg",!1);return n.runWebGLProgram(p,[s],"float32")}var Bne={kernelName:Ja,backendName:"webgl",kernelFunc:Lne};function Wne(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l,dataFormat:u}=r,c=[1,1,1],p=C.computePool3DInfo(s.shape,a,o,c,i,l,u),d=new b3(p,"avg",!1);return n.runWebGLProgram(d,[s],"float32")}var Vne={kernelName:Yd,backendName:"webgl",kernelFunc:Wne},Une=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=e.dilationHeight,o=e.dilationWidth,i=e.effectiveFilterHeight,l=e.effectiveFilterWidth,u=i-1-e.padInfo.top,c=l-1-e.padInfo.left,p=1/(t*n);this.userCode=`
|
|
const ivec2 pads = ivec2(${u}, ${c});
|
|
const float avgMultiplier = float(${p});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
|
|
ivec2 dyRCCorner = coords.yz - pads;
|
|
int dyRCorner = dyRCCorner.x;
|
|
int dyCCorner = dyRCCorner.y;
|
|
|
|
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < ${i};
|
|
wR += ${a}) {
|
|
float dyR = float(dyRCorner + wR) / ${r}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${l};
|
|
wC+= ${o}) {
|
|
float dyC = float(dyCCorner + wC) / ${s}.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);
|
|
}
|
|
`}},Gne=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,s=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=e.dilationDepth,l=e.dilationHeight,u=e.dilationWidth,c=e.effectiveFilterDepth,p=e.effectiveFilterHeight,d=e.effectiveFilterWidth,h=c-1-e.padInfo.front,f=p-1-e.padInfo.top,m=d-1-e.padInfo.left,g=1/(t*n*r);this.userCode=`
|
|
const ivec3 pads = ivec3(${h}, ${f}, ${m});
|
|
const float avgMultiplier = float(${g});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
|
|
int dyDCorner = dyCorner.x;
|
|
int dyRCorner = dyCorner.y;
|
|
int dyCCorner = dyCorner.z;
|
|
|
|
// Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get
|
|
// dx(xD, xR, xC, ch).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
|
|
for (int wD = 0; wD < ${c};
|
|
wD += ${i}) {
|
|
float dyD = float(dyDCorner + wD) / ${s}.0;
|
|
|
|
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyD = int(dyD);
|
|
|
|
for (int wR = 0; wR < ${p};
|
|
wR += ${l}) {
|
|
float dyR = float(dyRCorner + wR) / ${a}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
|
|
fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${d};
|
|
wC += ${u}) {
|
|
float dyC = float(dyCCorner + wC) / ${o}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
|
|
|
|
dotProd += dyValue * avgMultiplier;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function Hne(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,o=a,{filterSize:i,strides:l,pad:u,dimRoundingMode:c}=r,p=[1,1,1],d=C.computePool3DInfo(o.shape,i,l,p,u,c),h=new Gne(d);return n.runWebGLProgram(h,[s],o.dtype)}var jne={kernelName:Jf,backendName:"webgl",kernelFunc:Hne};function qne(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,o=a;Sc([s,a],"avgPoolGrad");let{filterSize:i,strides:l,pad:u}=r,c=C.computePool2DInfo(o.shape,i,l,1,u),p=new Une(c);return n.runWebGLProgram(p,[s],o.dtype)}var Xne={kernelName:Yf,backendName:"webgl",kernelFunc:qne};function Kne(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a}=t,{transposeA:o,transposeB:i}=r;return Uf({a:s,b:a,transposeA:o,transposeB:i,backend:n})}var Zne={kernelName:Qa,backendName:"webgl",kernelFunc:Kne},Yne=class{constructor(e,t,n,r,s,a){this.outputShape=[],this.variableNames=["x","mean","variance"],C.assertAndGetBroadcastShape(e,t),C.assertAndGetBroadcastShape(e,n);let o="0.0";r!=null&&(C.assertAndGetBroadcastShape(e,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let i="1.0";s!=null&&(C.assertAndGetBroadcastShape(e,s),this.variableNames.push("scale"),i="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
float x = getXAtOutCoords();
|
|
float mean = getMeanAtOutCoords();
|
|
float variance = getVarianceAtOutCoords();
|
|
float offset = ${o};
|
|
float scale = ${i};
|
|
float inv = scale * inversesqrt(variance + float(${a}));
|
|
setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1)));
|
|
}
|
|
`}},Jne=class{constructor(e,t,n,r,s,a){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],C.assertAndGetBroadcastShape(e,t),C.assertAndGetBroadcastShape(e,n);let o="vec4(0.0)";r!=null&&(C.assertAndGetBroadcastShape(e,r),this.variableNames.push("offset"),o="getOffsetAtOutCoords()");let i="vec4(1.0)";s!=null&&(C.assertAndGetBroadcastShape(e,s),this.variableNames.push("scale"),i="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=`
|
|
void main() {
|
|
vec4 offset = ${o};
|
|
vec4 scale = ${i};
|
|
|
|
vec4 x = getXAtOutCoords();
|
|
vec4 mean = getMeanAtOutCoords();
|
|
vec4 variance = getVarianceAtOutCoords();
|
|
|
|
vec4 inv = scale * inversesqrt(variance + vec4(${a}));
|
|
|
|
setOutput((x - mean) * inv + offset);
|
|
}
|
|
`}},Qne=({inputs:e,backend:t,attrs:n})=>{let{x:r,mean:s,variance:a,offset:o,scale:i}=e;w.assert(s.shape.length===a.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),w.assert(o==null||s.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),w.assert(i==null||s.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:l}=n;l==null&&(l=.001);let u=[r,s,a],c=null;o!=null&&(c=o.shape,u.push(o));let p=null;i!=null&&(p=i.shape,u.push(i));let d=Y().getBool("WEBGL_PACK_NORMALIZATION")?new Jne(r.shape,s.shape,a.shape,c,p,l):new Yne(r.shape,s.shape,a.shape,c,p,l);return t.runWebGLProgram(d,u,u[0].dtype)},ere={kernelName:fo,backendName:"webgl",kernelFunc:Qne},tre=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=yt(this.rank);this.customUniforms=[{name:"start",arrayIndex:this.rank,type:"int"}];let n=nre(this.rank),r,s=e.map((a,o)=>`sourceLoc.${ey[o]} = start[${o}] + coords.${ey[o]};`);r=`
|
|
${t} sourceLoc;
|
|
${t} coords = getOutputCoords();
|
|
${s.join(`
|
|
`)}
|
|
`,this.userCode=`
|
|
void main() {
|
|
${r}
|
|
setOutput(getSource(${n}));
|
|
}
|
|
`}},ey=["x","y","z","w","u","v"];function nre(e){if(e===1)return"sourceLoc";if(e<=6)return ey.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}var rre=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=yt(this.rank),n=Un("coords",this.rank),r=Un("sourceLoc",this.rank),s=this.rank===1?"sourceLoc":`vec2(${r.slice(-2).join()})`,a=`getChannel(getSource(${r.join()}), ${s})`,o=`
|
|
result.x = ${a};
|
|
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
|
|
++${r[this.rank-1]};
|
|
result.y = ${a};
|
|
--${r[this.rank-1]};
|
|
}
|
|
`,i=this.rank===1?"":`
|
|
--${n[this.rank-1]};
|
|
if (++${n[this.rank-2]} < ${e[this.rank-2]}) {
|
|
++${r[this.rank-2]};
|
|
result.z = ${a};
|
|
if (++${n[this.rank-1]} < ${e[this.rank-1]}) {
|
|
++${r[this.rank-1]};
|
|
result.w = ${a};
|
|
}
|
|
}
|
|
`,l=this.rank<=4?`sourceLoc = coords +
|
|
${t}(${e.map((u,c)=>`start[${c}]`).join()});`:e.map((u,c)=>`${r[c]} = ${n[c]} + start[${c}];`).join(`
|
|
`);this.userCode=`
|
|
void main() {
|
|
${t} coords = getOutputCoords();
|
|
${t} sourceLoc;
|
|
${l}
|
|
vec4 result = vec4(0.);
|
|
${o}
|
|
${i}
|
|
setOutput(result);
|
|
}
|
|
`}};function sre(e,t,n,r){let s=r.texData.get(e.dataId),a=r.makeTensorInfo(n,e.dtype),o=r.texData.get(a.dataId);Object.assign(o,s),o.refCount=1,o.shape=n,o.dtype=e.dtype;let i=Mt.computeFlatOffset(t,w.computeStrides(e.shape));s.slice&&(i+=s.slice.flatOffset),o.slice={flatOffset:i,origDataId:s.slice&&s.slice.origDataId||e.dataId};let l=r.dataRefCount.get(o.slice.origDataId)||1;return r.dataRefCount.set(o.slice.origDataId,l+1),a}function Rc(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,size:o}=r,[i,l]=Mt.parseSliceParams(s,a,o);if(Mt.assertParamsValid(s,i,l),w.sizeFromShape(l)===0)return n.makeTensorInfo(l,s.dtype,[]);if(n.shouldExecuteOnCPU([s])||s.dtype==="string"){let p=n.texData.get(s.dataId),d=qee(p.values,i,l,s.shape,s.dtype);return n.makeTensorInfo(l,s.dtype,d)}let{isPacked:u}=n.texData.get(s.dataId),c=Mt.isSliceContinous(s.shape,i,l);if(u||!c){let p=Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new rre(l):new tre(l),d=[i];return n.runWebGLProgram(p,[s],s.dtype,d)}return n.uploadToGPU(s.dataId),sre(s,i,l,n)}var are={kernelName:Al,backendName:"webgl",kernelFunc:Rc},ore=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,crops:o}=r;w.assert(s.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let i=a.reduce((x,A)=>x*A),l=C.getReshaped(s.shape,a,i),u=C.getPermuted(l.length,a.length),c=C.getReshapedPermuted(s.shape,a,i),p=C.getSliceBeginCoords(o,a.length),d=C.getSliceSize(c,o,a.length),h=[],f=ve({inputs:{x:s},backend:n,attrs:{shape:l}}),m=bn({inputs:{x:f},backend:n,attrs:{perm:u}}),g=ve({inputs:{x:m},backend:n,attrs:{shape:c}}),y=Rc({inputs:{x:g},backend:n,attrs:{begin:p,size:d}});return h.push(f),h.push(m),h.push(g),h.forEach(x=>n.disposeIntermediateTensorInfo(x)),y},ire={kernelName:Hi,backendName:"webgl",kernelFunc:ore};function lre(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:o}=r,i=n.readSync(s.dataId),l=n.readSync(a.dataId),u=KI(i,l,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,u)}var ure={kernelName:Qf,backendName:"webgl",kernelFunc:lre};function cre(e){let{inputs:t,backend:n}=e,{s0:r,s1:s}=t,a=n.readSync(r.dataId),o=n.readSync(s.dataId),i=C.assertAndGetBroadcastShape(Array.from(a),Array.from(o));return n.makeTensorInfo([i.length],"int32",Int32Array.from(i))}var dre={kernelName:em,backendName:"webgl",kernelFunc:cre},pre="return float(a != b);",p8=vn({opSnippet:pre,cpuKernelImpl:Vee,dtype:"bool"}),hre={kernelName:il,backendName:"webgl",kernelFunc:p8};function Vp(e){let{inputs:t,backend:n}=e,{input:r}=t,s=n.texData.get(r.dataId);return or({inputs:{x:s.complexTensorInfos.real},backend:n})}var fre={kernelName:ip,backendName:"webgl",kernelFunc:Vp},mre="return float(int(x));";function gre(e,t){let n=new Zs(e.shape,mre),r=t.runWebGLProgram(n,[e],"int32");return{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}function ty(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dtype:a}=r;if(a==="complex64"){if(s.dtype==="complex64")return or({inputs:{x:s},backend:n});let o=Ft(s.shape),i=ty({inputs:{x:s},backend:n,attrs:{dtype:"float32"}}),l=Xo({inputs:{real:i,imag:o},backend:n});return o.dispose(),n.disposeIntermediateTensorInfo(i),l}if(s.dtype==="complex64"){let o=Vp({inputs:{input:s},backend:n}),i=ty({inputs:{x:o},backend:n,attrs:{dtype:a}});return n.disposeIntermediateTensorInfo(o),i}if(!w.hasEncodingLoss(s.dtype,a)){let o=or({inputs:{x:s},backend:n});return{dataId:o.dataId,shape:o.shape,dtype:a}}if(a==="int32")return gre(s,n);if(a==="bool"){let o=n.makeTensorInfo([],"bool",w.getTypedArrayFromDType("bool",1)),l=p8({inputs:{a:s,b:o},backend:n});return n.disposeIntermediateTensorInfo(o),l}throw new Error(`Error in Cast: failed to cast ${s.dtype} to ${a}`)}var yre={kernelName:eo,backendName:"webgl",kernelFunc:ty},Gv="return ceil(x);",Are=ot({opSnippet:Gv,packedOpSnippet:Gv,cpuKernelImpl:kee}),xre={kernelName:to,backendName:"webgl",kernelFunc:Are},bre=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));
|
|
}
|
|
`}},vre=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 wre(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{clipValueMin:a,clipValueMax:o}=r,i;Y().getBool("WEBGL_PACK_CLIP")?i=new vre(s.shape):i=new bre(s.shape);let l=[[a],[o]];return n.runWebGLProgram(i,[s],s.dtype,l)}var kre={kernelName:ta,backendName:"webgl",kernelFunc:wre},Sre=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 Hv(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}function Ire(e){let{inputs:t,backend:n}=e,{x:r}=t,s=n.texData.get(r.dataId),a=new Sre(r.shape),o=[Hv(r,s.complexTensorInfos.real),Hv(r,s.complexTensorInfos.imag)];return n.runWebGLProgram(a,o,o[0].dtype)}var Cre={kernelName:Qd,backendName:"webgl",kernelFunc:Ire},Tre=class{constructor(e){this.outputShape=[],this.outputShape=C.computeOutShape(e,1),this.variableNames=e.map((a,o)=>`T${o}`);let t=new Array(e.length-1);t[0]=e[0][1];for(let a=1;a<t.length;a++)t[a]=t[a-1]+e[a][1];let n=[`if (yC < ${t[0]}) setOutput(getT0(yR, yC));`];for(let a=1;a<t.length;a++){let o=t[a-1];n.push(`else if (yC < ${t[a]}) setOutput(getT${a}(yR, yC-${o}));`)}let r=t.length,s=t[t.length-1];n.push(`else setOutput(getT${r}(yR, yC-${s}));`),this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int yR = coords.x;
|
|
int yC = coords.y;
|
|
|
|
${n.join(`
|
|
`)}
|
|
}
|
|
`}},Nre=class{constructor(e,t){this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[],this.outputShape=C.computeOutShape(e,t);let n=this.outputShape,r=n.length,s=yt(r),a=Un("coords",r),o=["x","y","z","w","u","v"].slice(0,r);this.variableNames=e.map((f,m)=>`T${m}`);let i=new Array(e.length-1);i[0]=e[0][t];for(let f=1;f<i.length;f++)i[f]=i[f-1]+e[f][t];let l=o[t],u=o.slice(-2),c=o.join(),p=`if (${l} < ${i[0]}) {
|
|
return getChannel(
|
|
getT0(${c}), vec2(${u.join()}));
|
|
}`;for(let f=1;f<i.length;f++){let m=i[f-1];p+=`
|
|
if (${l} < ${i[f]} && ${l} >= ${i[f-1]}) {
|
|
return getChannel(
|
|
getT${f}(${nf(o,l,m)}),
|
|
vec2(${nf(u,l,m)}));
|
|
}`}let d=i.length,h=i[i.length-1];p+=`
|
|
return getChannel(
|
|
getT${d}(${nf(o,l,h)}),
|
|
vec2(${nf(u,l,h)}));`,this.userCode=`
|
|
float getValue(${o.map(f=>"int "+f)}) {
|
|
${p}
|
|
}
|
|
|
|
void main() {
|
|
${s} coords = getOutputCoords();
|
|
vec4 result = vec4(getValue(${a}), 0., 0., 0.);
|
|
|
|
${a[r-1]} = ${a[r-1]} + 1;
|
|
if (${a[r-1]} < ${n[r-1]}) {
|
|
result.g = getValue(${a});
|
|
}
|
|
|
|
${a[r-2]} = ${a[r-2]} + 1;
|
|
if (${a[r-2]} < ${n[r-2]}) {
|
|
result.a = getValue(${a});
|
|
}
|
|
|
|
${a[r-1]} = ${a[r-1]} - 1;
|
|
if (${a[r-2]} < ${n[r-2]} &&
|
|
${a[r-1]} < ${n[r-1]}) {
|
|
result.b = getValue(${a});
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}};function nf(e,t,n){let r=e.indexOf(t);return e.map((a,o)=>o===r?`${a} - ${n}`:a).join()}function T0(e){let{inputs:t,backend:n}=e,{input:r}=t,s=n.texData.get(r.dataId);return or({inputs:{x:s.complexTensorInfos.imag},backend:n})}var Ere={kernelName:rp,backendName:"webgl",kernelFunc:T0};function gu(e,t,n){let r=e[0].dtype;if(r==="complex64"){let c=e.map(m=>Vp({inputs:{input:m},backend:n})),p=e.map(m=>T0({inputs:{input:m},backend:n})),d=gu(c,t,n),h=gu(p,t,n),f=Xo({inputs:{real:d,imag:h},backend:n});return c.forEach(m=>n.disposeIntermediateTensorInfo(m)),p.forEach(m=>n.disposeIntermediateTensorInfo(m)),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h),f}let s=n.shouldExecuteOnCPU(e);if(r==="string"&&(s=!0),s){let c=e.map(y=>{let x=w.sizeFromShape(y.shape.slice(t));return ve({inputs:{x:y},backend:n,attrs:{shape:[-1,x]}})}),p=c.map(y=>({vals:n.readSync(y.dataId),shape:y.shape})),d=C.computeOutShape(c.map(y=>y.shape),1),h=c[0].shape[0]===1,f=See(p,d,r,h),m=C.computeOutShape(e.map(y=>y.shape),t),g=n.makeTensorInfo(m,r,f);return c.forEach(y=>n.disposeIntermediateTensorInfo(y)),g}if(e.length>Y().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let c=Math.floor(e.length/2),p=gu(e.slice(0,c),t,n),d=gu(e.slice(c),t,n),h=gu([p,d],t,n);return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),h}if(Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].shape.length>1){let c=new Nre(e.map(p=>p.shape),t);return n.runWebGLProgram(c,e,r)}let{tensors2D:a,outShape:o}=Rre(e,t,n),i=new Tre(a.map(c=>c.shape)),l=n.runWebGLProgram(i,a,r);a.forEach(c=>n.disposeIntermediateTensorInfo(c));let u=ve({inputs:{x:l},attrs:{shape:o},backend:n});return n.disposeIntermediateTensorInfo(l),u}function Rre(e,t,n){let r=C.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:n})),outShape:r}}function h8(e){let{inputs:t,backend:n,attrs:r}=e,{axis:s}=r,a=w.parseAxisParam(s,t[0].shape)[0],o=C.computeOutShape(t.map(u=>u.shape),a);if(w.sizeFromShape(o)===0)return n.makeTensorInfo(o,t[0].dtype,[]);let i=t.filter(u=>w.sizeFromShape(u.shape)>0);if(i.length===1)return or({inputs:{x:i[0]},backend:n});let l=i.map(u=>u.shape);return C.assertParamsConsistent(l,a),gu(i,a,n)}var _re={kernelName:ji,backendName:"webgl",kernelFunc:h8},f8=class{constructor(e,t=!1,n=null,r=!1,s=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let a=e.padInfo.top,o=e.padInfo.left,i=e.strideHeight,l=e.strideWidth,u=e.dilationHeight,c=e.dilationWidth,p=e.filterHeight,d=e.filterWidth,h=Math.floor(e.inChannels/4)*4,f=e.inChannels%4,m=e.dataFormat==="channelsLast",g=m?1:2,y=m?2:3,x=m?3:1,A="",b="";n&&(r?A=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${n}
|
|
}`:s?A=`float activation(float a) {
|
|
float b = getLeakyreluAlphaAtOutCoords();
|
|
${n}
|
|
}`:A=`
|
|
float activation(float x) {
|
|
${n}
|
|
}
|
|
`,b="result = activation(result);");let v=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${A}
|
|
|
|
const ivec2 strides = ivec2(${i}, ${l});
|
|
const ivec2 pads = ivec2(${a}, ${o});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d2 = coords[${x}];
|
|
|
|
ivec2 xRCCorner =
|
|
ivec2(coords[${g}], coords[${y}]) * strides - pads;
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < ${p}; wR++) {
|
|
int xR = xRCorner + wR * ${u};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${d}; wC++) {
|
|
int xC = xCCorner + wC * ${c};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int d1 = 0; d1 < ${h}; d1 += 4) {
|
|
vec4 wValues = vec4(
|
|
getW(wR, wC, d1, d2),
|
|
getW(wR, wC, d1 + 1, d2),
|
|
getW(wR, wC, d1 + 2, d2),
|
|
getW(wR, wC, d1 + 3, d2)
|
|
);
|
|
|
|
if (${m}) {
|
|
vec4 xValues = vec4(
|
|
getX(batch, xR, xC, d1),
|
|
getX(batch, xR, xC, d1 + 1),
|
|
getX(batch, xR, xC, d1 + 2),
|
|
getX(batch, xR, xC, d1 + 3)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec4 xValues = vec4(
|
|
getX(batch, d1, xR, xC),
|
|
getX(batch, d1 + 1, xR, xC),
|
|
getX(batch, d1 + 2, xR, xC),
|
|
getX(batch, d1 + 3, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
}
|
|
|
|
if (${f===1}) {
|
|
|
|
if (${m}) {
|
|
dotProd +=
|
|
getX(batch, xR, xC, ${h}) *
|
|
getW(wR, wC, ${h}, d2);
|
|
} else {
|
|
dotProd +=
|
|
getX(batch, ${h}, xR, xC) *
|
|
getW(wR, wC, ${h}, d2);
|
|
}
|
|
|
|
} else if (${f===2}) {
|
|
vec2 wValues = vec2(
|
|
getW(wR, wC, ${h}, d2),
|
|
getW(wR, wC, ${h} + 1, d2)
|
|
);
|
|
|
|
if (${m}) {
|
|
vec2 xValues = vec2(
|
|
getX(batch, xR, xC, ${h}),
|
|
getX(batch, xR, xC, ${h} + 1)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec2 xValues = vec2(
|
|
getX(batch, ${h}, xR, xC),
|
|
getX(batch, ${h} + 1, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
} else if (${f===3}) {
|
|
vec3 wValues = vec3(
|
|
getW(wR, wC, ${h}, d2),
|
|
getW(wR, wC, ${h} + 1, d2),
|
|
getW(wR, wC, ${h} + 2, d2)
|
|
);
|
|
|
|
if (${m}) {
|
|
vec3 xValues = vec3(
|
|
getX(batch, xR, xC, ${h}),
|
|
getX(batch, xR, xC, ${h} + 1),
|
|
getX(batch, xR, xC, ${h} + 2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else {
|
|
vec3 xValues = vec3(
|
|
getX(batch, ${h}, xR, xC),
|
|
getX(batch, ${h} + 1, xR, xC),
|
|
getX(batch, ${h} + 2, xR, xC)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
|
|
float result = dotProd;
|
|
${v}
|
|
${b}
|
|
setOutput(result);
|
|
}
|
|
`}},$re=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let t=e.padInfo.front,n=e.padInfo.top,r=e.padInfo.left,s=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=e.dilationDepth,l=e.dilationHeight,u=e.dilationWidth,c=e.filterDepth,p=e.filterHeight,d=e.filterWidth,h=Math.floor(e.inChannels/4)*4,f=e.inChannels%4;this.userCode=`
|
|
const ivec3 strides = ivec3(${s}, ${a}, ${o});
|
|
const ivec3 pads = ivec3(${t}, ${n}, ${r});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int d2 = coords.u;
|
|
|
|
ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads;
|
|
int xFCorner = xFRCCorner.x;
|
|
int xRCorner = xFRCCorner.y;
|
|
int xCCorner = xFRCCorner.z;
|
|
|
|
// Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get
|
|
// y(yF, yR, yC, d2). ? = to be determined. : = across all
|
|
// values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wF = 0; wF < ${c}; wF++) {
|
|
int xF = xFCorner + wF * ${i};
|
|
|
|
if (xF < 0 || xF >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wR = 0; wR < ${p}; wR++) {
|
|
int xR = xRCorner + wR * ${l};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${d}; wC++) {
|
|
int xC = xCCorner + wC * ${u};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int d1 = 0; d1 < ${h}; d1 += 4) {
|
|
vec4 xValues = vec4(
|
|
getX(batch, xF, xR, xC, d1),
|
|
getX(batch, xF, xR, xC, d1 + 1),
|
|
getX(batch, xF, xR, xC, d1 + 2),
|
|
getX(batch, xF, xR, xC, d1 + 3)
|
|
);
|
|
vec4 wValues = vec4(
|
|
getW(wF, wR, wC, d1, d2),
|
|
getW(wF, wR, wC, d1 + 1, d2),
|
|
getW(wF, wR, wC, d1 + 2, d2),
|
|
getW(wF, wR, wC, d1 + 3, d2)
|
|
);
|
|
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
|
|
if (${f===1}) {
|
|
dotProd +=
|
|
getX(batch, xF, xR, xC, ${h}) *
|
|
getW(wF, wR, wC, ${h}, d2);
|
|
} else if (${f===2}) {
|
|
vec2 xValues = vec2(
|
|
getX(batch, xF, xR, xC, ${h}),
|
|
getX(batch, xF, xR, xC, ${h} + 1)
|
|
);
|
|
vec2 wValues = vec2(
|
|
getW(wF, wR, wC, ${h}, d2),
|
|
getW(wF, wR, wC, ${h} + 1, d2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
} else if (${f===3}) {
|
|
vec3 xValues = vec3(
|
|
getX(batch, xF, xR, xC, ${h}),
|
|
getX(batch, xF, xR, xC, ${h} + 1),
|
|
getX(batch, xF, xR, xC, ${h} + 2)
|
|
);
|
|
vec3 wValues = vec3(
|
|
getW(wF, wR, wC, ${h}, d2),
|
|
getW(wF, wR, wC, ${h} + 1, d2),
|
|
getW(wF, wR, wC, ${h} + 2, d2)
|
|
);
|
|
dotProd += dot(xValues, wValues);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},Dre=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=lr(this.outputShape.length);let{dataFormat:n}=t,r=Kn(),s=n==="channelsLast",a=s?0:1,o=s?1:2,i=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 c=0;c<=1;c++)l+=`
|
|
blockIndex = rc.y + ${c};
|
|
pos = rc.x + ${u};
|
|
|
|
${i}
|
|
offsetY = int(blockIndex / outWidth) * stride[0] - pad[0];
|
|
d0 = offsetY + dilation[0] * (pos / itemsPerBlockRow);
|
|
|
|
if(d0 < inputShape[${a}] && 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[${o}] && d1 >= 0) {
|
|
|
|
ch = imod(pos, inChannels);
|
|
|
|
if (${s}) {
|
|
innerDims = vec2(d1, ch);
|
|
result[${u*2+c}] = getChannel(
|
|
getA(d0, int(innerDims.x),
|
|
int(innerDims.y)), innerDims);
|
|
} else {
|
|
innerDims = vec2(d0, d1);
|
|
result[${u*2+c}] = 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}
|
|
|
|
${r.output} = result;
|
|
}
|
|
`}};function m8({x:e,filter:t,convInfo:n,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let l=e.shape,u=r.texData.get(e.dataId),c=n.inChannels,p=l[0]*l[1]*l[2],d=n.outChannels,h=n.dataFormat==="channelsLast",f=!1,m=!1,g,y=[];if(!((p===1||d===1)&&c>l8)&&u.isPacked&&h&&u.texture!=null&&l[2]%2!==0&&w.arraysEqual(u.shape.slice(-3),l.slice(-3))){let b=l[0]*l[1]*(l[2]+1),v={dataId:e.dataId,shape:[1,b,n.inChannels],dtype:e.dtype},S=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,w.assert(Xd(u.shape,v.shape),()=>`packed reshape ${u.shape} to ${v.shape} isn't free`);let I=ve({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}});y.push(I);let E=Uf({a:v,b:I,backend:r,transposeA:f,transposeB:m,bias:s,activation:i,preluActivationWeights:a,leakyreluAlpha:o}),R=r.texData.get(E.dataId);w.assert(R.isPacked,()=>"batchMatMul result is expected to be packed"),u.shape=S,R.shape=n.outShape,g=or({inputs:{x:E},backend:r}),g.shape=n.outShape,y.push(E)}else{let b=h?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],v=ve({inputs:{x:e},backend:r,attrs:{shape:[1,b,n.inChannels]}}),S=ve({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}}),I=Uf({a:v,b:S,transposeA:f,transposeB:m,backend:r,bias:s,activation:i,preluActivationWeights:a,leakyreluAlpha:o});g=ve({inputs:{x:I},backend:r,attrs:{shape:n.outShape}}),y.push(v),y.push(S),y.push(I)}for(let b of y)r.disposeIntermediateTensorInfo(b);return g}function g8({x:e,filter:t,convInfo:n,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let{filterWidth:l,filterHeight:u,inChannels:c,outWidth:p,outHeight:d,dataFormat:h}=n,f=h==="channelsLast",m=l*u*c,g=d*p,y=[m,g],x=!0,A=!1,b=[],v=ve({inputs:{x:e},backend:r,attrs:{shape:e.shape.slice(1)}}),S=ve({inputs:{x:t},backend:r,attrs:{shape:[1,m,w.sizeFromShape(t.shape)/m]}});b.push(v),b.push(S);let I=new Dre(y,n),E=[v.shape,[n.padInfo.top,n.padInfo.left],[n.strideHeight,n.strideWidth],[n.dilationHeight,n.dilationWidth],[n.inChannels],[n.filterWidth*n.inChannels],[n.outWidth]],R=r.runWebGLProgram(I,[v],"float32",E),P=ve({inputs:{x:R},backend:r,attrs:{shape:[1,y[0],y[1]]}});b.push(R),b.push(P);let _=s!=null,D=a!=null,T=i==="leakyrelu",F=i?S0(i,!0):null,U=new i8(P.shape,S.shape,[1,g,n.outChannels],x,A,_,F,D,T),X=[P,S];if(s&&X.push(s),D&&X.push(a),T){let ee=r.makeTensorInfo([],"float32",w.createScalarValue(o,"float32"));X.push(ee),b.push(ee)}let z=r.runWebGLProgram(U,X,"float32"),Z=f?[1,d,p,n.outChannels]:[1,n.outChannels,d,p],W=ve({inputs:{x:z},backend:r,attrs:{shape:Z}});b.push(z);for(let ee of b)r.disposeIntermediateTensorInfo(ee);return W}function Pre(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dataFormat:l,dilations:u,dimRoundingMode:c}=r,p=C.convertConv2DDataFormat(l),d=C.computeConv2DInfo(s.shape,a.shape,o,u,i,c,!1,p),h;if(d.filterHeight===1&&d.filterWidth===1&&d.dilationHeight===1&&d.dilationWidth===1&&d.strideHeight===1&&d.strideWidth===1&&(d.padInfo.type==="SAME"||d.padInfo.type==="VALID"))h=m8({x:s,filter:a,convInfo:d,backend:n});else if(Y().getBool("WEBGL_CONV_IM2COL")&&s.shape[0]===1)h=g8({x:s,filter:a,convInfo:d,backend:n});else{let m=new f8(d);h=n.runWebGLProgram(m,[s,a],"float32")}let f=ve({inputs:{x:h},backend:n,attrs:{shape:d.outShape}});return n.disposeIntermediateTensorInfo(h),f}var Fre={kernelName:no,backendName:"webgl",kernelFunc:Pre},Ore=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,s=e.padInfo.left,a=e.dataFormat==="channelsLast";this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int wR = coords.x;
|
|
int wC = coords.y;
|
|
int d1 = coords.z;
|
|
int d2 = coords.w;
|
|
|
|
// Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
|
|
for (int b = 0; b < ${e.batchSize}; b++) {
|
|
for (int yR = 0; yR < ${e.outHeight}; yR++) {
|
|
int xR = wR + yR * ${t} - ${r};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${n} - ${s};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
if (${a}) {
|
|
float dyValue = getDy(b, yR, yC, d2);
|
|
float xValue = getX(b, xR, xC, d1);
|
|
dotProd += (xValue * dyValue);
|
|
} else {
|
|
float dyValue = getDy(b, d2, yR, yC);
|
|
float xValue = getX(b, d1, xR, xC);
|
|
dotProd += (xValue * dyValue);
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},Mre=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=e.dataFormat==="channelsLast",o=t-1-e.padInfo.top,i=n-1-e.padInfo.left,l=a?1:2,u=a?2:3,c=a?3:1;this.userCode=`
|
|
const ivec2 pads = ivec2(${o}, ${i});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d1 = coords[${c}];
|
|
|
|
ivec2 dyCorner = ivec2(coords[${l}], coords[${u}]) - pads;
|
|
int dyRCorner = dyCorner.x;
|
|
int dyCCorner = dyCorner.y;
|
|
|
|
// Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < ${t}; wR++) {
|
|
float dyR = float(dyRCorner + wR) / ${r}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
int wRPerm = ${t} - 1 - wR;
|
|
|
|
for (int wC = 0; wC < ${n}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${s}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
int wCPerm = ${n} - 1 - wC;
|
|
|
|
for (int d2 = 0; d2 < ${e.outChannels}; d2++) {
|
|
|
|
if (${a}) {
|
|
float xValue = getDy(batch, idyR, idyC, d2);
|
|
float wValue = getW(wRPerm, wCPerm, d1, d2);
|
|
dotProd += xValue * wValue;
|
|
} else {
|
|
float xValue = getDy(batch, d2, idyR, idyC);
|
|
float wValue = getW(wRPerm, wCPerm, d1, d2);
|
|
dotProd += xValue * wValue;
|
|
}
|
|
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},zre=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,s=e.padInfo.front,a=e.padInfo.top,o=e.padInfo.left;this.userCode=`
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int wF = coords.x;
|
|
int wR = coords.y;
|
|
int wC = coords.z;
|
|
int d1 = coords.w;
|
|
int d2 = coords.u;
|
|
|
|
float dotProd = 0.0;
|
|
|
|
for (int b = 0; b < ${e.batchSize}; b++) {
|
|
for (int yF = 0; yF < ${e.outDepth}; yF++) {
|
|
int xF = wF + yF * ${t} - ${s};
|
|
|
|
if (xF < 0 || xF >= ${e.inDepth}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yR = 0; yR < ${e.outHeight}; yR++) {
|
|
int xR = wR + yR * ${n} - ${a};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${r} - ${o};
|
|
|
|
if (xC < 0 || xC >= ${e.inWidth}) {
|
|
continue;
|
|
}
|
|
|
|
float dyValue = getDy(b, yF, yR, yC, d2);
|
|
float xValue = getX(b, xF, xR, xC, d1);
|
|
dotProd += (xValue * dyValue);
|
|
}
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},Lre=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,r=e.filterWidth,s=e.strideDepth,a=e.strideHeight,o=e.strideWidth,i=t-1-e.padInfo.front,l=n-1-e.padInfo.top,u=r-1-e.padInfo.left;this.userCode=`
|
|
const ivec3 pads = ivec3(${i}, ${l}, ${u});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int d1 = coords.u;
|
|
|
|
|
|
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
|
|
int dyFCorner = dyCorner.x;
|
|
int dyRCorner = dyCorner.y;
|
|
int dyCCorner = dyCorner.z;
|
|
|
|
float dotProd = 0.0;
|
|
for (int wF = 0; wF < ${t}; wF++) {
|
|
float dyF = float(dyFCorner + wF) / ${s}.0;
|
|
|
|
if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyF = int(dyF);
|
|
|
|
int wFPerm = ${t} - 1 - wF;
|
|
|
|
for (int wR = 0; wR < ${n}; wR++) {
|
|
float dyR = float(dyRCorner + wR) / ${a}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
|
|
fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
int wRPerm = ${n} - 1 - wR;
|
|
|
|
for (int wC = 0; wC < ${r}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${o}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
int wCPerm = ${r} - 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 Bre(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,pad:i,dataFormat:l,dimRoundingMode:u,filterShape:c}=r,p=C.convertConv2DDataFormat(l),d=C.computeConv2DInfo(s.shape,c,o,1,i,u,!1,p),h=new Ore(d);return n.runWebGLProgram(h,[s,a],"float32")}var Wre={kernelName:tm,backendName:"webgl",kernelFunc:Bre};function Vre(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{inputShape:o,strides:i,pad:l,dataFormat:u,dimRoundingMode:c}=r,p=C.convertConv2DDataFormat(u),d=C.computeConv2DInfo(o,a.shape,i,1,l,c,!1,p),h=new Mre(d);return n.runWebGLProgram(h,[s,a],"float32")}var Ure={kernelName:ro,backendName:"webgl",kernelFunc:Vre};function Gre(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:l}=r,u=C.computeConv3DInfo(s.shape,a.shape,o,l,i),c=new $re(u);return n.runWebGLProgram(c,[s,a],"float32")}var Hre={kernelName:ep,backendName:"webgl",kernelFunc:Gre};function jre(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,pad:i,filterShape:l}=r,u=C.computeConv3DInfo(s.shape,l,o,1,i),c=new zre(u);return n.runWebGLProgram(c,[s,a],"float32")}var qre={kernelName:nm,backendName:"webgl",kernelFunc:jre};function Xre(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{pad:o,strides:i,inputShape:l}=r,u=C.computeConv3DInfo(l,a.shape,i,1,o),c=new Lre(u);return n.runWebGLProgram(c,[s,a],"float32")}var Kre={kernelName:rm,backendName:"webgl",kernelFunc:Xre},Zre=Ec+`
|
|
return cos(x);
|
|
`,Yre=ot({opSnippet:Zre}),Jre={kernelName:so,backendName:"webgl",kernelFunc:Yre},Qre=`
|
|
float e2x = exp(-x);
|
|
return (e2x + 1.0 / e2x) / 2.0;
|
|
`,ese=ot({opSnippet:Qre}),tse={kernelName:ao,backendName:"webgl",kernelFunc:ese},nse=class{constructor(e,t,n,r,s){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[a,o,i,l]=e,[u]=t,[c,p]=n;this.outputShape=[u,c,p,l];let d=r==="bilinear"?1:0,[h,f]=[`${o-1}.0`,`${i-1}.0`],[m,g,y]=c>1?[`${(o-1)/(c-1)}`,"(y2-y1) * height_ratio",`y1*${h} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${h}`],[x,A,b]=p>1?[`${(i-1)/(p-1)}`,"(x2-x1) * width_ratio",`x1*${f} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${f}`];this.userCode=`
|
|
const float height_ratio = float(${m});
|
|
const float width_ratio = float(${x});
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int y = coords[1];
|
|
int x = coords[2];
|
|
int d = coords[3];
|
|
|
|
// get box vals
|
|
float y1 = getBoxes(b,0);
|
|
float x1 = getBoxes(b,1);
|
|
float y2 = getBoxes(b,2);
|
|
float x2 = getBoxes(b,3);
|
|
|
|
// get image in batch index
|
|
int bInd = round(getBoxInd(b));
|
|
if(bInd < 0 || bInd >= ${a}) {
|
|
return;
|
|
}
|
|
|
|
float height_scale = ${g};
|
|
float width_scale = ${A};
|
|
|
|
float in_y = ${y};
|
|
if( in_y < 0.0 || in_y > ${h} ) {
|
|
setOutput(float(${s}));
|
|
return;
|
|
}
|
|
float in_x = ${b};
|
|
if( in_x < 0.0 || in_x > ${f} ) {
|
|
setOutput(float(${s}));
|
|
return;
|
|
}
|
|
|
|
vec2 sourceFracIndexCR = vec2(in_x,in_y);
|
|
if(${d} == 1) {
|
|
// Compute the four integer indices.
|
|
ivec2 sourceFloorCR = ivec2(sourceFracIndexCR);
|
|
ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR));
|
|
|
|
float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d);
|
|
float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d);
|
|
float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d);
|
|
float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d);
|
|
|
|
vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR);
|
|
|
|
float top = topLeft + (topRight - topLeft) * fracCR.x;
|
|
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x;
|
|
float newValue = top + (bottom - top) * fracCR.y;
|
|
setOutput(newValue);
|
|
} else {
|
|
// Compute the coordinators of nearest neighbor point.
|
|
ivec2 sourceNearestCR = ivec2(floor(
|
|
sourceFracIndexCR + vec2(0.5,0.5)));
|
|
float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d);
|
|
setOutput(newValue);
|
|
}
|
|
}
|
|
`}},rse=e=>{let{inputs:t,backend:n,attrs:r}=e,{image:s,boxes:a,boxInd:o}=t,{cropSize:i,method:l,extrapolationValue:u}=r,c=new nse(s.shape,a.shape,i,l,u);return n.runWebGLProgram(c,[s,a,o],"float32")},sse={kernelName:Xi,backendName:"webgl",kernelFunc:rse},jv=class{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}],this.outputShape=e;let r=e.length,s=t?"1.0":`getX(${qv(r,"coords")})`,a=e[e.length-1],o="",i="";t?(o=n?`end != ${a-1}`:"end != 0",i=n?"end + 1":"end - 1"):(o=n?`end + pow2 < ${a}`:"end >= pow2",i=n?"end + pow2":"end - pow2"),this.userCode=`
|
|
void main() {
|
|
${yt(r)} coords = getOutputCoords();
|
|
int end = ${Xv(r,"coords")};
|
|
float val = ${s};
|
|
int pow2 = int(pow(2.0, index));
|
|
if (${o}) {
|
|
int idx = ${i};
|
|
${Xv(r,"coords")} = idx;
|
|
val *= getX(${qv(r,"coords")});
|
|
}
|
|
setOutput(val);
|
|
}
|
|
`}};function qv(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 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 product for rank ${e} is not yet supported`)}function ase(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:o,reverse:i}=r,l=s.shape.length,u=C.getAxesPermutation([a],l),c=s;u!=null&&(c=bn({inputs:{x:s},backend:n,attrs:{perm:u}}));let p=C.getInnerMostAxes(1,l)[0];if(p!==l-1)throw new Error(`WebGL cumprod shader expects an inner-most axis=${s.shape.length-1} but got axis=${a}`);let d=c.shape[p],h=or({inputs:{x:c},backend:n});for(let f=0;f<=Math.ceil(Math.log2(d))-1;f++){let m=new jv(c.shape,!1,i),g=[[f]],y=h;h=n.runWebGLProgram(m,[h],h.dtype,g),n.disposeIntermediateTensorInfo(y)}if(o){let f=new jv(c.shape,o,i),m=h;h=n.runWebGLProgram(f,[h],h.dtype),n.disposeIntermediateTensorInfo(m)}if(u!=null){let f=C.getUndoAxesPermutation(u),m=bn({inputs:{x:h},backend:n,attrs:{perm:f}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(c),m}return h}var ose={kernelName:qi,backendName:"webgl",kernelFunc:ase},Kv=class{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"index",type:"float"}],this.outputShape=e;let r=e.length,s=t?"0.0":`getX(${Zv(r,"coords")})`,a=e[e.length-1],o="",i="";t?(o=n?`end != ${a-1}`:"end != 0",i=n?"end + 1":"end - 1"):(o=n?`end + pow2 < ${a}`:"end >= pow2",i=n?"end + pow2":"end - pow2"),this.userCode=`
|
|
void main() {
|
|
${yt(r)} coords = getOutputCoords();
|
|
int end = ${Yv(r,"coords")};
|
|
float val = ${s};
|
|
int pow2 = int(pow(2.0, index));
|
|
if (${o}) {
|
|
int idx = ${i};
|
|
${Yv(r,"coords")} = idx;
|
|
val += getX(${Zv(r,"coords")});
|
|
}
|
|
setOutput(val);
|
|
}
|
|
`}};function Zv(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 Yv(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 ise(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:o,reverse:i}=r,l=s.shape.length,u=C.getAxesPermutation([a],l),c=s;u!=null&&(c=bn({inputs:{x:s},backend:n,attrs:{perm:u}}));let p=C.getInnerMostAxes(1,l)[0];if(p!==l-1)throw new Error(`WebGL cumsum shader expects an inner-most axis=${s.shape.length-1} but got axis=${a}`);let d=c.shape[p],h=or({inputs:{x:c},backend:n});for(let f=0;f<=Math.ceil(Math.log2(d))-1;f++){let m=new Kv(c.shape,!1,i),g=[[f]],y=h;h=n.runWebGLProgram(m,[h],h.dtype,g),n.disposeIntermediateTensorInfo(y)}if(o){let f=new Kv(c.shape,o,i),m=h;h=n.runWebGLProgram(f,[h],h.dtype),n.disposeIntermediateTensorInfo(m)}if(u!=null){let f=C.getUndoAxesPermutation(u),m=bn({inputs:{x:h},backend:n,attrs:{perm:f}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(c),m}return h}var lse={kernelName:oo,backendName:"webgl",kernelFunc:ise};function use(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,weights:a}=t,{size:o,binaryOutput:i}=r;if(s.shape.length===1){let l=n.readSync(s.dataId),u=n.readSync(a.dataId),c=KI(l,u,a.dtype,a.shape,o);return n.makeTensorInfo([o],a.dtype,c)}else if(s.shape.length===2){let l=n.bufferSync(s),u=n.bufferSync(a),c=wee(l,u,o,i);return n.makeTensorInfo(c.shape,a.dtype,c.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${s.shape.length}.`)}var cse={kernelName:sm,backendName:"webgl",kernelFunc:use},dse=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=[],this.outputShape=e,this.blockSize=t,this.dataFormat=n,this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int h = ${this.getHeightCoordString()};
|
|
int w = ${this.getWidthCoordString()};
|
|
int d = ${this.getDepthCoordString()};
|
|
|
|
int in_h = h / ${t};
|
|
int offset_h = imod(h, ${t});
|
|
int in_w = w / ${t};
|
|
int offset_w = imod(w, ${t});
|
|
int offset_d = (offset_h * ${t} + offset_w) *
|
|
${this.getOutputDepthSize()};
|
|
int in_d = d + offset_d;
|
|
|
|
float result = ${this.getInputSamplingString()};
|
|
setOutput(result);
|
|
}
|
|
`}getHeightCoordString(){return this.dataFormat==="NHWC"?"coords[1]":"coords[2]"}getWidthCoordString(){return this.dataFormat==="NHWC"?"coords[2]":"coords[3]"}getDepthCoordString(){return this.dataFormat==="NHWC"?"coords[3]":"coords[1]"}getOutputDepthSize(){return this.dataFormat==="NHWC"?this.outputShape[3]:this.outputShape[1]}getInputSamplingString(){return this.dataFormat==="NHWC"?"getX(b, in_h, in_w, in_d)":"getX(b, in_d, in_h, in_w)"}};function pse(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockSize:a,dataFormat:o}=r,i=s.shape[0],l=o==="NHWC"?s.shape[1]:s.shape[2],u=o==="NHWC"?s.shape[2]:s.shape[3],c=o==="NHWC"?s.shape[3]:s.shape[1],p=l*a,d=u*a,h=c/(a*a),f=o==="NHWC"?[i,p,d,h]:[i,h,p,d],m=new dse(f,a,o);return n.runWebGLProgram(m,[s],s.dtype)}var hse={kernelName:Ki,backendName:"webgl",kernelFunc:pse},y8=class{constructor(e,t=!1,n=null,r=!1,s=!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=lr(this.outputShape.length);let a=e.filterHeight,o=e.filterWidth,i=e.outChannels/e.inChannels,l="",u="";n&&(r?l=`float activation(float a) {
|
|
float b = getPreluActivationWeightsAtOutCoords();
|
|
${n}
|
|
}`:s?l=`float activation(float a) {
|
|
float b = getLeakyreluAlphaAtOutCoords();
|
|
${n}
|
|
}`:l=`
|
|
float activation(float x) {
|
|
${n}
|
|
}
|
|
`,u="result = activation(result);");let c=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${l}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int d2 = coords.w;
|
|
int d1 = d2 / ${i};
|
|
int q = d2 - d1 * ${i};
|
|
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
// Convolve x(?, ?, d1) with w(:, :, d1, q) to get y(yR, yC, d2).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
// TO DO(dsmilkov): Flatten the two for loops and vec4 the operations.
|
|
for (int wR = 0; wR < ${a}; wR++) {
|
|
int xR = xRCorner + wR * dilations[0];
|
|
|
|
if (xR < 0 || xR >= inDims[0]) {
|
|
continue;
|
|
}
|
|
|
|
for (int wC = 0; wC < ${o}; wC++) {
|
|
int xC = xCCorner + wC * dilations[1];
|
|
|
|
if (xC < 0 || xC >= inDims[1]) {
|
|
continue;
|
|
}
|
|
|
|
float xVal = getX(batch, xR, xC, d1);
|
|
float wVal = getW(wR, wC, d1, q);
|
|
dotProd += xVal * wVal;
|
|
}
|
|
}
|
|
|
|
float result = dotProd;
|
|
${c}
|
|
${u}
|
|
setOutput(result);
|
|
}
|
|
`}},A8=class{constructor(e,t=!1,n=null,r=!1,s=!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=lr(this.outputShape.length);let a=e.outChannels/e.inChannels,o=e.padInfo.left,i=e.strideWidth,l=e.dilationWidth,u=e.filterHeight,c=e.filterWidth,p=c,d=`
|
|
int xR; int xC; int xCOffset;
|
|
vec4 wTexel; vec4 previous; vec4 final;`;for(let g=0;g<c;g++)d+=`
|
|
vec4 xTexelC${g*2};
|
|
int xTexelC${g*2}Ready;
|
|
vec4 xTexelC${g*2+1};
|
|
int xTexelC${g*2+1}Ready;
|
|
vec4 xC${g};`;d+=`
|
|
for (int r = 0; r < ${u}; r++) {
|
|
`;for(let g=0;g<c;g++)d+=`
|
|
xTexelC${g*2} = vec4(0.0);
|
|
xTexelC${g*2}Ready = 0;
|
|
xTexelC${g*2+1} = vec4(0.0);
|
|
xTexelC${g*2+1}Ready = 0;
|
|
xC${g} = vec4(0.0);`;d+=`
|
|
xR = xRCorner + r * dilations[0];
|
|
if (xR >=0 && xR < inDims[0]) {
|
|
`;for(let g=0;g<(p+1)/2;g++){let y=g*2;if(d+=`
|
|
xC = xCCorner + ${y*l};
|
|
`,i===1){if(y<c&&(o%2===1?(d+=`
|
|
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?d+=`
|
|
xC${y} = vec4(xTexelC${y-2}.zw, xTexelC${y}.xy);
|
|
`:d+=`
|
|
xCOffset = xC + 1 - 2;
|
|
|
|
if (xCOffset >= 0 && xCOffset < inDims[1]) {
|
|
previous = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
previous.zw = vec2(0.0);
|
|
}
|
|
|
|
xC${y} = vec4(previous.zw, xTexelC${y}.xy);
|
|
} else {
|
|
xC${y} = vec4(0.0, 0.0, xTexelC${y}.xy);
|
|
}
|
|
`):d+=`
|
|
if (xC >= 0 && xC < inDims[1] && xTexelC${y}Ready == 0) {
|
|
xTexelC${y} = getX(batch, xR, xC, d1);
|
|
if (xC + 1 >= inDims[1]) {
|
|
xTexelC${y}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${y}Ready = 1;
|
|
}
|
|
|
|
xC${y} = xTexelC${y};
|
|
`,y+1<c)){let x=o%2===0?w.nearestLargerEven(l):l;l%2===0&&o%2===1||l%2!==0&&o%2!==1?(d+=`
|
|
xCOffset = xC + imod(pads[1], 2) + ${x};
|
|
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) {
|
|
xTexelC${y+1} = getX(batch, xR, xCOffset, d1);
|
|
|
|
// Need to manually clear unused channels in case
|
|
// we're reading from recycled texture.
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${y+1}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${y+1}Ready = 1;
|
|
}
|
|
`,l>1&&(d+=`
|
|
xCOffset -= 2;
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y}Ready == 0) {
|
|
xTexelC${y} = getX(batch, xR, xCOffset, d1);
|
|
xTexelC${y}Ready = 1;
|
|
}
|
|
`),d+=`
|
|
xC${y+1} = vec4(xTexelC${y}.zw, xTexelC${y+1}.xy);
|
|
`):x===1?d+=`
|
|
xC${y+1} = xTexelC${y};
|
|
`:d+=`
|
|
xCOffset = xC + ${x};
|
|
|
|
if (xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) {
|
|
xTexelC${y+1} = getX(batch, xR, xCOffset, d1);
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${y+1}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${y+1}Ready = 1;
|
|
}
|
|
|
|
xC${y+1} = xTexelC${y+1};
|
|
`}}else y<c&&(o%2===1?(d+=`
|
|
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<c&&(d+=`
|
|
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);
|
|
`)):(d+=`
|
|
if(xC >= 0 && xC < inDims[1] && xTexelC${y}Ready == 0) {
|
|
xTexelC${y} = getX(batch, xR, xC, d1);
|
|
if (xC + 1 >= inDims[1]) {
|
|
xTexelC${y}.zw = vec2(0.0);
|
|
}
|
|
xTexelC${y}Ready = 1;
|
|
}
|
|
|
|
xCOffset = xC + strides[1];
|
|
if(xCOffset >= 0 && xCOffset < inDims[1] && xTexelC${y+1}Ready == 0) {
|
|
xTexelC${y+1} = getX(batch, xR, xCOffset, d1);
|
|
if (xCOffset + 1 >= inDims[1]) {
|
|
xTexelC${y+1}.zw = vec2(0.);
|
|
}
|
|
xTexelC${y+1}Ready = 1;
|
|
}
|
|
|
|
xC${y} = vec4(
|
|
xTexelC${y}.xy, xTexelC${y+1}.xy);
|
|
`,y+1<c&&(d+=`
|
|
xC${y+1} = vec4(xTexelC${y}.zw, xTexelC${y+1}.zw);
|
|
`)));y<c&&(d+=`
|
|
wTexel = getW(r, ${y}, d1, q);
|
|
dotProd += xC${y} * vec4(wTexel.xz, wTexel.xz);
|
|
`,y+1<c&&(d+=`
|
|
wTexel = getW(r, ${y+1}, d1, q);
|
|
dotProd += xC${y+1} * vec4(wTexel.xz, wTexel.xz);
|
|
`))}d+=`
|
|
}
|
|
`,d+=`
|
|
}
|
|
`;let h="",f="";n&&(r?h=`vec4 activation(vec4 a) {
|
|
vec4 b = getPreluActivationWeightsAtOutCoords();
|
|
${n}
|
|
}`:s?h=`vec4 activation(vec4 a) {
|
|
vec4 b = getLeakyreluAlphaAtOutCoords();
|
|
${n}
|
|
}`:h=`vec4 activation(vec4 x) {
|
|
${n}
|
|
}`,f="result = activation(result);");let m=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),s&&this.variableNames.push("leakyreluAlpha"),this.userCode=`
|
|
${h}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
ivec2 xRCCorner = coords.yz * strides - pads;
|
|
int d2 = coords.w;
|
|
int d1 = d2 / ${a};
|
|
int q = d2 - d1 * ${a};
|
|
int xRCorner = xRCCorner.x;
|
|
int xCCorner = xRCCorner.y;
|
|
|
|
//intialize dotProd with a small epsilon seems to reduce GPU accuracy loss.
|
|
vec4 dotProd = vec4(0.000000000000001);
|
|
|
|
${d}
|
|
|
|
vec4 result = dotProd - vec4(0.000000000000001);
|
|
${m}
|
|
${f}
|
|
setOutput(result);
|
|
}
|
|
`}};function fse(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:l,dimRoundingMode:u}=r,c=l;c==null&&(c=[1,1]),w.assert(C.eitherStridesOrDilationsAreOne(o,c),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${o} and dilations '${c}'`);let p=C.computeConv2DInfo(s.shape,a.shape,o,c,i,u,!0),d;Y().getBool("WEBGL_PACK_DEPTHWISECONV")&&p.strideWidth<=2&&p.outChannels/p.inChannels===1?d=new A8(p):d=new y8(p);let h=[[p.padInfo.top,p.padInfo.left],[p.strideHeight,p.strideWidth],[p.dilationHeight,p.dilationWidth],[p.inHeight,p.inWidth]];return n.runWebGLProgram(d,[s,a],"float32",h)}var mse={kernelName:io,backendName:"webgl",kernelFunc:fse},gse=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,r=e.padInfo.top,s=e.padInfo.left,a=e.outChannels/e.inChannels;this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int wR = coords.x;
|
|
int wC = coords.y;
|
|
int d1 = coords.z;
|
|
int dm = coords.w;
|
|
int d2 = d1 * ${a} + dm;
|
|
|
|
float dotProd = 0.0;
|
|
|
|
// TO DO: Vec4 over the batch size
|
|
for (int b = 0; b < ${e.batchSize}; b++) {
|
|
for (int yR = 0; yR < ${e.outHeight}; yR++) {
|
|
int xR = wR + yR * ${t} - ${r};
|
|
|
|
if (xR < 0 || xR >= ${e.inHeight}) {
|
|
continue;
|
|
}
|
|
|
|
for (int yC = 0; yC < ${e.outWidth}; yC++) {
|
|
int xC = wC + yC * ${n} - ${s};
|
|
|
|
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);
|
|
}
|
|
`}},yse=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,r=e.strideHeight,s=e.strideWidth,a=t-1-e.padInfo.top,o=n-1-e.padInfo.left,i=e.outChannels/e.inChannels;this.userCode=`
|
|
const ivec2 pads = ivec2(${a}, ${o});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int d1 = coords[3];
|
|
ivec2 dyCorner = coords.yz - pads;
|
|
int dyRCorner = dyCorner.x;
|
|
int dyCCorner = dyCorner.y;
|
|
|
|
float dotProd = 0.0;
|
|
|
|
for (int wR = 0; wR < ${t}; wR++) {
|
|
float dyR = float(dyRCorner + wR) / ${r}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
int wRPerm = ${t} - 1 - wR;
|
|
|
|
for (int wC = 0; wC < ${n}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${s}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
int wCPerm = ${n} - 1 - wC;
|
|
|
|
// TO DO: Vec4 over the channelMul
|
|
for (int dm = 0; dm < ${i}; dm++) {
|
|
int d2 = d1 * ${i} + dm;
|
|
float xValue = getDy(batch, idyR, idyC, d2);
|
|
float wValue = getW(wRPerm, wCPerm, d1, dm);
|
|
dotProd += xValue * wValue;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function Ase(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,dy:a}=t,{strides:o,dilations:i,pad:l,dimRoundingMode:u,filterShape:c}=r,p=C.computeConv2DInfo(s.shape,c,o,i,l,u,!0),d=new gse(p);return n.runWebGLProgram(d,[s,a],"float32")}var xse={kernelName:am,backendName:"webgl",kernelFunc:Ase};function bse(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{strides:o,dilations:i,pad:l,dimRoundingMode:u,inputShape:c}=r,p=C.computeConv2DInfo(c,a.shape,o,i,l,u,!0),d=new yse(p);return n.runWebGLProgram(d,[s,a],"float32")}var vse={kernelName:om,backendName:"webgl",kernelFunc:bse},wse=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 kse(e){let{inputs:t,backend:n}=e,{x:r}=t,s=[...r.shape,...r.shape],a=w.sizeFromShape(r.shape),o=ve({inputs:{x:r},backend:n,attrs:{shape:[a]}}),i=new wse(a),l=n.runWebGLProgram(i,[o],o.dtype),u=ve({inputs:{x:l},backend:n,attrs:{shape:s}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(l),u}var Sse={kernelName:im,backendName:"webgl",kernelFunc:kse},Ise=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let{inHeight:t,inWidth:n,padInfo:r,strideHeight:s,strideWidth:a,filterHeight:o,filterWidth:i,dilationHeight:l,dilationWidth:u}=e,{top:c,left:p}=r;this.userCode=`
|
|
const ivec2 strides = ivec2(${s}, ${a});
|
|
const ivec2 pads = ivec2(${c}, ${p});
|
|
const float neg_infinity = -3.4e38;
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int d1 = coords.w;
|
|
ivec2 outTopLeftCorner =
|
|
coords.yz * strides - pads;
|
|
int hBeg = outTopLeftCorner.x;
|
|
int wBeg = outTopLeftCorner.y;
|
|
|
|
float curVal = neg_infinity;
|
|
for (int h = 0; h < ${o}; h++) {
|
|
int hIn = hBeg + h * ${l};
|
|
|
|
if (hIn >= 0 && hIn < ${t}) {
|
|
for (int w = 0; w < ${i}; w++) {
|
|
int wIn = wBeg + w * ${u};
|
|
|
|
if (wIn >= 0 && wIn < ${n}) {
|
|
float xVal = getX(batch, hIn, wIn, d1);
|
|
float wVal = getW(h, w, d1);
|
|
|
|
float val = xVal + wVal;
|
|
if (val > curVal) {
|
|
curVal = val;
|
|
}
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
float result = curVal;
|
|
setOutput(result);
|
|
}
|
|
`}};function Cse(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:l}=r,u=C.computeDilation2DInfo(s.shape,a.shape,o,i,"NHWC",l),c,p=new Ise(u);c=n.runWebGLProgram(p,[s,a],"float32");let d=ve({inputs:{x:c},backend:n,attrs:{shape:u.outShape}});return n.disposeIntermediateTensorInfo(c),d}var Tse={kernelName:tp,backendName:"webgl",kernelFunc:Cse};function Nse(e){let{inputs:t,backend:n,attrs:r}=e,{equation:s}=r,a=t,{allDims:o,summedDims:i,idDims:l}=C.decodeEinsumEquation(s,a.length);C.checkEinsumDimSizes(o.length,l,a);let{path:u,steps:c}=C.getEinsumComputePath(i,l),p=c.length,d=null,h=o.length,f=[];for(let m=0;m<p;++m){for(let g of c[m]){let{permutationIndices:y,expandDims:x}=C.getEinsumPermutation(h,l[g]),A;C.isIdentityPermutation(y)?A=a[g]:(A=bn({inputs:{x:a[g]},backend:n,attrs:{perm:y}}),f.push(A));let b=A.shape.slice();for(let v=0;v<x.length;++v)b.splice(x[v],0,1);w.arraysEqual(A.shape,b)||(A=ve({inputs:{x:A},backend:n,attrs:{shape:b}}),f.push(A)),d===null?d=A:(d=x3({inputs:{a:A,b:d},backend:n}),f.push(d))}m<p-1&&(u[m]>=0&&(d=C0({inputs:{x:d},backend:n,attrs:{axis:u[m]-(o.length-h),keepDims:!1}}),f.push(d)),h--)}for(let m of f)m!==d&&n.disposeIntermediateTensorInfo(m);return d}var Ese={kernelName:np,backendName:"webgl",kernelFunc:Nse},Rse="return (x >= 0.0) ? x : (exp(x) - 1.0);",_se=`
|
|
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;
|
|
`,$se=ot({opSnippet:Rse,packedOpSnippet:_se}),Dse={kernelName:uo,backendName:"webgl",kernelFunc:$se},Pse="return (b >= 1.0) ? a : a * (b + 1.0);",Fse=`
|
|
vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.)));
|
|
return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0))));
|
|
`,Ose=e=>{let{inputs:t,backend:n}=e,{dy:r,y:s}=t,a=Y().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new Wp(Fse,r.shape,s.shape):new Fu(Pse,r.shape,s.shape);return n.runWebGLProgram(a,[r,s],r.dtype)},Mse={kernelName:lm,backendName:"webgl",kernelFunc:Ose},zse=`
|
|
return vec4(equal(a, b));
|
|
`,Lse="return float(a == b);",Bse=vn({opSnippet:Lse,packedOpSnippet:zse,dtype:"bool",cpuKernelImpl:Iee}),Wse={kernelName:Zi,backendName:"webgl",kernelFunc:Bse},Vse=`
|
|
// Error function is calculated approximately with elementary function.
|
|
// See "Handbook of Mathematical Functions with Formulas,
|
|
// Graphs, and Mathematical Tables", Abramowitz and Stegun.
|
|
float p = ${C.ERF_P};
|
|
float a1 = ${C.ERF_A1};
|
|
float a2 = ${C.ERF_A2};
|
|
float a3 = ${C.ERF_A3};
|
|
float a4 = ${C.ERF_A4};
|
|
float a5 = ${C.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));
|
|
`,Use=ot({opSnippet:Vse}),Gse={kernelName:Xu,backendName:"webgl",kernelFunc:Use},Hse=Ec+`
|
|
return exp(x);
|
|
`,jse=`
|
|
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;
|
|
`,x8=ot({opSnippet:Hse,packedOpSnippet:jse,cpuKernelImpl:Cee,dtype:"float32"}),qse={kernelName:co,backendName:"webgl",kernelFunc:x8};function ny(e){let{inputs:t,attrs:n,backend:r}=e,{dim:s}=n,{input:a}=t,o=a.shape.length,i=a.shape.slice(),l=s;return s<0&&(w.assert(-(o+1)<=s,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),l=o+s+1),i.splice(l,0,1),ve({inputs:{x:a},backend:r,attrs:{shape:i}})}var Xse={kernelName:Yi,backendName:"webgl",kernelFunc:ny},Jv="return exp(x) - 1.0;",Kse=ot({opSnippet:Jv,packedOpSnippet:Jv,cpuKernelImpl:Tee}),Zse={kernelName:Ji,backendName:"webgl",kernelFunc:Kse},Qv=class{constructor(e,t,n){this.variableNames=["real","imag"];let r=t[1];this.outputShape=t;let s=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,a=n?`${r}.0`:"1.0",o;if(e==="real")o="return real * expR - imag * expI;";else if(e==="imag")o="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);this.userCode=`
|
|
const float exponentMultiplier = ${s};
|
|
|
|
float unaryOpComplex(float real, float expR, float imag, float expI) {
|
|
${o}
|
|
}
|
|
|
|
float mulMatDFT(int batch, int index) {
|
|
float indexRatio = float(index) / float(${r});
|
|
float exponentMultiplierTimesIndexRatio =
|
|
exponentMultiplier * indexRatio;
|
|
|
|
float result = 0.0;
|
|
|
|
for (int i = 0; i < ${r}; i++) {
|
|
// x = (-2|2 * PI / N) * index * i;
|
|
float x = exponentMultiplierTimesIndexRatio * float(i);
|
|
float expR = cos(x);
|
|
float expI = sin(x);
|
|
float real = getReal(batch, i);
|
|
float imag = getImag(batch, i);
|
|
|
|
result +=
|
|
unaryOpComplex(real, expR, imag, expI) / ${a};
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
setOutput(mulMatDFT(coords[0], coords[1]));
|
|
}
|
|
`}};function b8(e,t,n){let r=n.texData.get(e.dataId),s=w.sizeFromShape(e.shape),a=e.shape[e.shape.length-1],o=s/a,i=ve({inputs:{x:e},backend:n,attrs:{shape:[o,a]}}),l=i.shape,u=new Qv("real",l,t),c=new Qv("imag",l,t),p=[{dataId:r.complexTensorInfos.real.dataId,dtype:r.complexTensorInfos.real.dtype,shape:l},{dataId:r.complexTensorInfos.imag.dataId,dtype:r.complexTensorInfos.imag.dtype,shape:l}],d=n.runWebGLProgram(u,p,"float32"),h=n.runWebGLProgram(c,p,"float32"),f=Xo({inputs:{real:d,imag:h},backend:n});n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h);let m=ve({inputs:{x:f},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(f),m}function Yse(e){let{inputs:t,backend:n}=e,{input:r}=t;return b8(r,!1,n)}var Jse={kernelName:um,backendName:"webgl",kernelFunc:Yse},Qse=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 Up(e){let{backend:t,attrs:n}=e,{shape:r,value:s}=n,{dtype:a}=n;if(a=a||w.inferDtype(s),a==="string"){let o=w.getArrayFromDType(a,w.sizeFromShape(r));return o.fill(s),t.makeTensorInfo(r,a,o)}else{let o=new Qse(r,s),i=[[s]];return t.runWebGLProgram(o,[],a,i)}}var eae={kernelName:Ku,backendName:"webgl",kernelFunc:Up},tae=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);
|
|
}
|
|
`}},nae={kernelName:Qi,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{let{image:n}=e,r=t,s=new tae(n.shape);return r.runWebGLProgram(s,[n],n.dtype)}},e4="return floor(x);",rae=ot({opSnippet:e4,packedOpSnippet:e4,cpuKernelImpl:Nee}),sae={kernelName:po,backendName:"webgl",kernelFunc:rae},aae=`
|
|
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;
|
|
}
|
|
`,oae=`
|
|
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);
|
|
`,iae=vn({opSnippet:aae,packedOpSnippet:oae,dtype:"int32"}),lae={kernelName:ho,backendName:"webgl",kernelFunc:iae},uae=class{constructor(e){this.variableNames=["A"];let t=Kn(),[n,r]=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(${r}.0, ${n}.0);
|
|
|
|
vec4 values = ${t.texture2D}(A, uv);
|
|
float value;
|
|
if (depth == 0) {
|
|
value = values.r;
|
|
} else if (depth == 1) {
|
|
value = values.g;
|
|
} else if (depth == 2) {
|
|
value = values.b;
|
|
} else if (depth == 3) {
|
|
value = values.a;
|
|
}
|
|
|
|
setOutput(floor(value * 255.0 + 0.5));
|
|
}
|
|
`}},cae=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=Kn(),[n,r]=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(${r}.0, ${n}.0);
|
|
vec4 values = ${t.texture2D}(A, uv);
|
|
float value;
|
|
if (depth == 0) {
|
|
value = values.r;
|
|
} else if (depth == 1) {
|
|
value = values.g;
|
|
} else if (depth == 2) {
|
|
value = values.b;
|
|
} else if (depth == 3) {
|
|
value = values.a;
|
|
}
|
|
|
|
result[row * 2 + col] = floor(value * 255.0 + 0.5);
|
|
}
|
|
}
|
|
|
|
${t.output} = result;
|
|
}
|
|
`}},dae={kernelName:Md,backendName:"webgl",kernelFunc:pae},du;function pae(e){let{inputs:t,backend:n,attrs:r}=e,{pixels:s}=t,{numChannels:a}=r,o=typeof HTMLVideoElement!="undefined"&&s instanceof HTMLVideoElement,i=typeof HTMLImageElement!="undefined"&&s instanceof HTMLImageElement,[l,u]=o?[s.videoWidth,s.videoHeight]:[s.width,s.height],c=[u,l],p=[u,l,a];(i||o)&&(du==null&&(du=document.createElement("canvas").getContext("2d")),du.canvas.width=l,du.canvas.height=u,du.drawImage(s,0,0,l,u),s=du.canvas);let d=n.makeTensorInfo(c,"int32");n.texData.get(d.dataId).usage=2,n.gpgpu.uploadPixelDataToTexture(n.getTexture(d.dataId),s);let h=Y().getBool("WEBGL_PACK")?new cae(p):new uae(p),f=n.runWebGLProgram(h,[d],"int32");return n.disposeData(d.dataId),f}function hae(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:d,activation:h,leakyreluAlpha:f}=r,m=C.convertConv2DDataFormat(c),g=C.computeConv2DInfo(s.shape,a.shape,l,p,u,d,!1,m),y,x=[];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=m8({x:s,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});else if(Y().getBool("WEBGL_CONV_IM2COL")&&s.shape[0]===1)y=g8({x:s,filter:a,convInfo:g,backend:n,bias:o,activation:h,preluActivationWeights:i,leakyreluAlpha:f});else{let b=o!=null,v=i!=null,S=h==="leakyrelu",I=h?S0(h,!1):null,E=new f8(g,b,I,v,S),R=[s,a];if(o&&R.push(o),i&&R.push(i),S){let P=n.makeTensorInfo([],"float32",w.createScalarValue(f,"float32"));R.push(P),x.push(P)}y=n.runWebGLProgram(E,R,"float32")}let A=ve({inputs:{x:y},backend:n,attrs:{shape:g.outShape}});return x.push(y),x.forEach(b=>n.disposeIntermediateTensorInfo(b)),A}var fae={kernelName:Fa,backendName:"webgl",kernelFunc:hae};function mae(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:u,dilations:c,dimRoundingMode:p,activation:d,leakyreluAlpha:h}=r,f=[],m=c;m==null&&(m=[1,1]),w.assert(C.eitherStridesOrDilationsAreOne(l,m),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${m}'`);let g=C.computeConv2DInfo(s.shape,a.shape,l,m,u,p,!0),y=Y().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels===1,x=d?S0(d,y):null,A=[s,a],b=o!=null,v=i!=null,S=d==="leakyrelu";if(b&&A.push(o),v&&A.push(i),S){let P=n.makeTensorInfo([],"float32",w.createScalarValue(h,"float32"));A.push(P),f.push(P)}let I;y?I=new A8(g,b,x,v,S):I=new y8(g,b,x,v,S);let E=[[g.padInfo.top,g.padInfo.left],[g.strideHeight,g.strideWidth],[g.dilationHeight,g.dilationWidth],[g.inHeight,g.inWidth]],R=n.runWebGLProgram(I,A,"float32",E);return f.forEach(P=>n.disposeIntermediateTensorInfo(P)),R}var gae={kernelName:Oa,backendName:"webgl",kernelFunc:mae},yae=class{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;let r=yt(t.length),s=yt(n.length),a=this.sliceDim>1?"strides[j]":"strides";this.userCode=`
|
|
${r} strides = ${r}(${this.strides});
|
|
void main() {
|
|
${s} coords = getOutputCoords();
|
|
int flattenIndex = 0;
|
|
for (int j = 0; j < ${this.sliceDim}; j++) {
|
|
int index = round(getIndices(coords[0], j));
|
|
flattenIndex += index * ${a};
|
|
}
|
|
setOutput(getX(flattenIndex, coords[1]));
|
|
}
|
|
`}};function Aae(e){let{inputs:t,backend:n}=e,{params:r,indices:s}=t,a=s.shape,o=a[a.length-1],i=w.sizeFromShape(r.shape),[l,u,c,p]=C.prepareAndValidate(r,s),d=ve({inputs:{x:s},backend:n,attrs:{shape:[u,o]}}),h=ve({inputs:{x:r},backend:n,attrs:{shape:[w.sizeFromShape(r.shape)/c,c]}});if(n.shouldExecuteOnCPU([r,s])||r.dtype==="string"){let y=n.readSync(s.dataId),x=n.bufferSync(r),A=Eee(y,x,r.dtype,u,o,c,p,r.shape,i);return n.makeTensorInfo(l,r.dtype,A.values)}let f=new yae(o,p,[u,c]),m=n.runWebGLProgram(f,[h,d],h.dtype),g=ve({inputs:{x:m},backend:n,attrs:{shape:l}});return n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(m),g}var xae={kernelName:tl,backendName:"webgl",kernelFunc:Aae},bae=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let n=yt(this.rank),r=vae(e,2);this.userCode=`
|
|
void main() {
|
|
${n} resRC = getOutputCoords();
|
|
int index = int(getIndices(resRC.x, resRC.z));
|
|
float inBounds = (index >= 0) && (index < ${e[2]}) ? 1.0 : 0.0;
|
|
setOutput(inBounds * getA(${r}));
|
|
}
|
|
`}};function vae(e,t){let n=["resRC.x","resRC.y","resRC.z","resRC.w"],r=[];for(let s=0;s<e.length;s++)s===2?r.push("index"):r.push(`${n[s]}`);return r.join()}function v8(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,indices:a}=t,{axis:o,batchDims:i}=r,l=w.parseAxisParam(o,s.shape)[0];if(Y().get("DEBUG")){let x=n.readSync(a.dataId),A=s.shape[l];for(let b=0;b<x.length;++b){let v=x[b];w.assert(v<=A-1&&v>=0,()=>`GatherV2: the index value ${v} is not in [0, ${A-1}]`)}}let u=C.segment_util.collectGatherOpShapeInfo(s,a,l,i),c=w.sizeFromShape(a.shape),p=[],d=ve({inputs:{x:s},backend:n,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),h=ve({inputs:{x:a},backend:n,attrs:{shape:[u.batchSize,c/u.batchSize]}});p.push(d),p.push(h);let f=[u.batchSize,u.outerSize,c/u.batchSize,u.sliceSize];if(n.shouldExecuteOnCPU([s,a])||s.dtype==="string"){let x=n.bufferSync(h),A=n.bufferSync(d),b=Ree(A,x,f);return p.forEach(v=>n.disposeIntermediateTensorInfo(v)),n.makeTensorInfo(u.outputShape,b.dtype,b.values)}let m=new bae(d.shape,f),g=n.runWebGLProgram(m,[d,h],d.dtype);p.push(g);let y=ve({inputs:{x:g},backend:n,attrs:{shape:u.outputShape}});return p.forEach(x=>n.disposeIntermediateTensorInfo(x)),y}var wae={kernelName:el,backendName:"webgl",kernelFunc:v8},kae="return float(a > b);",Sae=`
|
|
return vec4(greaterThan(a, b));
|
|
`,Iae=vn({opSnippet:kae,packedOpSnippet:Sae,cpuKernelImpl:_ee,dtype:"bool"}),Cae={kernelName:nl,backendName:"webgl",kernelFunc:Iae},Tae="return float(a >= b);",Nae=`
|
|
return vec4(greaterThanEqual(a, b));
|
|
`,Eae=vn({opSnippet:Tae,packedOpSnippet:Nae,dtype:"bool",cpuKernelImpl:$ee}),Rae={kernelName:mo,backendName:"webgl",kernelFunc:Eae};function _ae(e){let{inputs:t,backend:n}=e,{input:r}=t;return b8(r,!0,n)}var $ae={kernelName:cm,backendName:"webgl",kernelFunc:_ae},Dae="return float(!isnan(x) && !isinf(x));",Pae=ot({opSnippet:Dae,dtype:"bool"}),Fae={kernelName:Zu,backendName:"webgl",kernelFunc:Pae},Oae="return float(isinf(x));",Mae=ot({opSnippet:Oae,dtype:"bool"}),zae={kernelName:Yu,backendName:"webgl",kernelFunc:Mae},Lae="return float(isnan(x));",Bae=ot({opSnippet:Lae,dtype:"bool"}),Wae={kernelName:Ju,backendName:"webgl",kernelFunc:Bae},Vae="return float(a < b);",Uae=`
|
|
return vec4(lessThan(a, b));
|
|
`,Gae=vn({opSnippet:Vae,packedOpSnippet:Uae,cpuKernelImpl:Dee,dtype:"bool"}),Hae={kernelName:rl,backendName:"webgl",kernelFunc:Gae},jae="return float(a <= b);",qae=`
|
|
return vec4(lessThanEqual(a, b));
|
|
`,Xae=vn({opSnippet:jae,packedOpSnippet:qae,cpuKernelImpl:Pee,dtype:"bool"}),Kae={kernelName:sl,backendName:"webgl",kernelFunc:Xae};function Zae(e){let{backend:t,attrs:n}=e,{start:r,stop:s,num:a}=n,o=Fee(r,s,a);return t.makeTensorInfo([o.length],"float32",o)}var Yae={kernelName:dm,backendName:"webgl",kernelFunc:Zae},Jae=Ec+`
|
|
return x < 0.0 ? 0./0. : log(x);
|
|
`,Qae=`
|
|
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;
|
|
`,eoe=ot({opSnippet:Jae,packedOpSnippet:Qae,cpuKernelImpl:Oee}),toe={kernelName:Ao,backendName:"webgl",kernelFunc:eoe},noe=Ec+`
|
|
return log(1.0 + x);
|
|
`,roe=ot({opSnippet:noe}),soe={kernelName:Qu,backendName:"webgl",kernelFunc:roe},aoe="return float(a >= 1.0 && b >= 1.0);",ooe=`
|
|
return vec4(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) *
|
|
vec4(greaterThanEqual(b, vec4(1.0))));
|
|
`,ioe=vn({opSnippet:aoe,packedOpSnippet:ooe,dtype:"bool"}),loe={kernelName:al,backendName:"webgl",kernelFunc:ioe},uoe="return float(!(x >= 1.0));",coe=ot({opSnippet:uoe}),doe={kernelName:ec,backendName:"webgl",kernelFunc:coe},poe="return float(a >= 1.0 || b >= 1.0);",hoe=`
|
|
return min(
|
|
vec4(greaterThanEqual(a, vec4(1.0))) +
|
|
vec4(greaterThanEqual(b, vec4(1.0))),
|
|
vec4(1.0));
|
|
`,foe=vn({opSnippet:poe,packedOpSnippet:hoe,dtype:"bool"}),moe={kernelName:sp,backendName:"webgl",kernelFunc:foe},goe=class{constructor(e,t,n,r,s){this.variableNames=["x"],this.outputShape=[];let a=t,o=e[3]-1;this.outputShape=e;let i,l=`float(${n}) + float(${r}) * sum`;s===.5?i=`inversesqrt(${l})`:s===1?i=`1.0/(${l})`:i=`exp(log(${l}) * float(-${s}));`,this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int r = coords[1];
|
|
int c = coords[2];
|
|
int d = coords[3];
|
|
float x = getX(b, r, c, d);
|
|
float sum = 0.0;
|
|
for (int j = -${a}; j <= ${a}; j++) {
|
|
int idx = d + j;
|
|
if (idx >= 0 && idx <= ${o}) {
|
|
float z = getX(b, r, c, idx);
|
|
sum += z * z;
|
|
}
|
|
}
|
|
float val = x * ${i};
|
|
setOutput(val);
|
|
}
|
|
`}},yoe=class{constructor(e,t,n,r,s){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;let a=t,o=e[3]-1;this.outputShape=e;let i,l=`float(${n}) + float(${r}) * sum`;s===.5?i=`inversesqrt(${l})`:s===1?i=`1.0/(${l})`:i=`exp(log(${l}) * float(-${s}));`,this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords.x;
|
|
int r = coords.y;
|
|
int c = coords.z;
|
|
int d = coords.w;
|
|
|
|
bool hasNextCol = d < ${this.outputShape[3]};
|
|
bool hasNextRow = c < ${this.outputShape[2]};
|
|
|
|
vec4 sum = vec4(0.);
|
|
vec4 xFragAtOutputCoords = getX(b, r, c, d);
|
|
|
|
vec4 xAtOutputCoords = vec4(
|
|
getChannel(xFragAtOutputCoords, vec2(c, d)),
|
|
hasNextCol ?
|
|
getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0,
|
|
hasNextRow ?
|
|
getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0
|
|
);
|
|
|
|
int firstChannel = d - ${a};
|
|
vec2 cache = vec2(0.);
|
|
if(firstChannel >= 0){
|
|
vec4 firstChannelFrag = getX(b, r, c, firstChannel);
|
|
cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel));
|
|
if(hasNextRow){
|
|
cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel));
|
|
}
|
|
}
|
|
|
|
ivec2 depth = ivec2(d, d + 1);
|
|
for (int j = - ${a}; j <= ${a}; j++) {
|
|
ivec2 idx = depth + j;
|
|
bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0));
|
|
bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${o}));
|
|
|
|
bool depthInRange = aboveLowerBound.x && belowUpperBound.x;
|
|
bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y;
|
|
|
|
if(depthInRange || depthPlusOneInRange){
|
|
vec4 z = vec4(0.);
|
|
vec4 xFragAtCurrentDepth;
|
|
z.xz = cache.xy;
|
|
if(depthPlusOneInRange && hasNextCol){
|
|
xFragAtCurrentDepth = idx.y != d ?
|
|
getX(b, r, c, idx.y) : xFragAtOutputCoords;
|
|
z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y));
|
|
if(hasNextRow){
|
|
z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y));
|
|
}
|
|
}
|
|
cache.xy = z.yw;
|
|
sum += z * z;
|
|
}
|
|
}
|
|
vec4 result = xAtOutputCoords * ${i};
|
|
setOutput(result);
|
|
}
|
|
`}},Aoe=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{depthRadius:a,bias:o,alpha:i,beta:l}=r,u=Y().getBool("WEBGL_PACK_NORMALIZATION")?new yoe(s.shape,a,o,i,l):new goe(s.shape,a,o,i,l);return n.runWebGLProgram(u,[s],s.dtype)},xoe={kernelName:ap,backendName:"webgl",kernelFunc:Aoe},boe=class{constructor(e,t,n,r,s){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=r,this.beta=s,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(${r}) * norm + float(${n});
|
|
|
|
for(int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k){
|
|
if (k < depthBegin){
|
|
continue;
|
|
}
|
|
else if (k >= depthBegin && k < depthEnd){
|
|
float dyi = -2.0 * float(${r})
|
|
* float(${s})
|
|
* getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d)
|
|
/ norm;
|
|
if (k == d) {
|
|
dyi += pow(norm, -1.0 * ${s});
|
|
}
|
|
if (k == coords[3]) {
|
|
dyi *= getDy(b, r, c, d);
|
|
result += dyi;
|
|
}
|
|
}
|
|
else {
|
|
break;
|
|
}
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`}},voe=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s,y:a,dy:o}=t,{depthRadius:i,bias:l,alpha:u,beta:c}=r,p=new boe(s.shape,i,l,u,c);return n.runWebGLProgram(p,[s,a,o],s.dtype)},woe={kernelName:pm,backendName:"webgl",kernelFunc:voe};function koe(e,t,n,r){let s=w.sizeFromShape(t),o=w.sizeFromShape(e.shape)/s,i=ve({inputs:{x:e},attrs:{shape:[o,s]},backend:r}),l=Ll(i,e.dtype,"max",r),u=ve({inputs:{x:l},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(l),u}function w8(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reductionIndices:a,keepDims:o}=r,i=s.shape.length,l=w.parseAxisParam(a,s.shape),u=l,c=C.getAxesPermutation(u,i),p=c!=null,d=n.shouldExecuteOnCPU([s]),h=s;if(p){if(d){let A=n.texData.get(h.dataId).values,b=new Array(i);for(let I=0;I<b.length;I++)b[I]=s.shape[c[I]];let v=A3(A,s.shape,s.dtype,c,b);h=n.makeTensorInfo(b,s.dtype);let S=n.texData.get(h.dataId);S.values=v}else h=I0(s,c,n);u=C.getInnerMostAxes(u.length,i)}C.assertAxesAreInnerMostDims("max",u,i);let[f,m]=C.computeOutAndReduceShapes(h.shape,u),g=f;o&&(g=C.expandShapeToKeepDim(f,l));let y;if(d){let A=n.texData.get(h.dataId).values,b=Mee(A,w.sizeFromShape(m),g,s.dtype);y=n.makeTensorInfo(g,s.dtype);let v=n.texData.get(y.dataId);v.values=b}else y=koe(h,m,g,n);return p&&n.disposeIntermediateTensorInfo(h),y}var Soe={kernelName:xo,backendName:"webgl",kernelFunc:w8},Ioe=n8+`
|
|
return max(a, b);
|
|
`,Coe=`
|
|
vec4 result = vec4(max(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+k0+`
|
|
return result;
|
|
`,Toe=vn({opSnippet:Ioe,packedOpSnippet:Coe,cpuKernelImpl:zee}),Noe={kernelName:bo,backendName:"webgl",kernelFunc:Toe};function Eoe(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t;Sc(s,"maxPool");let{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=r,u=1;w.assert(C.eitherStridesOrDilationsAreOne(o,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${o} and dilations '${u}'`);let c=C.computePool2DInfo(s.shape,a,o,u,i,l);if(c.filterWidth===1&&c.filterHeight===1&&w.arraysEqual(c.inShape,c.outShape))return or({inputs:{x:s},backend:n});let p=new Kd(c,"max",!1);return n.runWebGLProgram(p,[s],s.dtype)}var Roe={kernelName:vo,backendName:"webgl",kernelFunc:Eoe};function _oe(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:o,pad:i,dataFormat:l,dimRoundingMode:u}=r,c=[1,1,1],p=C.computePool3DInfo(s.shape,a,o,c,i,u,l),d=new b3(p,"max",!1);return n.runWebGLProgram(d,[s],s.dtype)}var $oe={kernelName:op,backendName:"webgl",kernelFunc:_oe},Doe=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideHeight,n=e.strideWidth,r=e.dilationHeight,s=e.effectiveFilterHeight,a=e.effectiveFilterWidth,o=s-1-e.padInfo.top,i=a-1-e.padInfo.left,l=s*a-1;this.userCode=`
|
|
const ivec2 pads = ivec2(${o}, ${i});
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
|
|
ivec2 dyRCCorner = coords.yz - pads;
|
|
int dyRCorner = dyRCCorner.x;
|
|
int dyCCorner = dyRCCorner.y;
|
|
|
|
// Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
for (int wR = 0; wR < ${s};
|
|
wR += ${r}) {
|
|
float dyR = float(dyRCorner + wR) / ${t}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${a}; wC++) {
|
|
float dyC = float(dyCCorner + wC) / ${n}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(b, idyR, idyC, d);
|
|
int maxPosValue = ${l} - int(getMaxPos(b, idyR, idyC, d));
|
|
|
|
// Get the current value, check it against the value from the
|
|
// position matrix.
|
|
int curPosValue = wR * ${a} + wC;
|
|
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
|
|
|
|
dotProd += dyValue * mask;
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}},Poe=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideDepth,n=e.strideHeight,r=e.strideWidth,s=e.dilationDepth,a=e.dilationHeight,o=e.dilationWidth,i=e.effectiveFilterDepth,l=e.effectiveFilterHeight,u=e.effectiveFilterWidth,c=i-1-e.padInfo.front,p=l-1-e.padInfo.top,d=u-1-e.padInfo.left,h=i*l*u-1;this.userCode=`
|
|
const ivec3 pads = ivec3(${c}, ${p}, ${d});
|
|
|
|
void main() {
|
|
ivec5 coords = getOutputCoords();
|
|
int batch = coords.x;
|
|
int ch = coords.u;
|
|
|
|
ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads;
|
|
int dyDCorner = dyCorner.x;
|
|
int dyRCorner = dyCorner.y;
|
|
int dyCCorner = dyCorner.z;
|
|
|
|
// Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get
|
|
// dx(xD, xR, xC, ch).
|
|
// ? = to be determined. : = across all values in that axis.
|
|
float dotProd = 0.0;
|
|
|
|
for (int wD = 0; wD < ${i};
|
|
wD += ${s}) {
|
|
float dyD = float(dyDCorner + wD) / ${t}.0;
|
|
|
|
if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyD = int(dyD);
|
|
|
|
for (int wR = 0; wR < ${l};
|
|
wR += ${a}) {
|
|
float dyR = float(dyRCorner + wR) / ${n}.0;
|
|
|
|
if (dyR < 0.0 || dyR >= ${e.outHeight}.0 ||
|
|
fract(dyR) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyR = int(dyR);
|
|
|
|
for (int wC = 0; wC < ${u};
|
|
wC += ${o}) {
|
|
float dyC = float(dyCCorner + wC) / ${r}.0;
|
|
|
|
if (dyC < 0.0 || dyC >= ${e.outWidth}.0 ||
|
|
fract(dyC) > 0.0) {
|
|
continue;
|
|
}
|
|
int idyC = int(dyC);
|
|
|
|
float dyValue = getDy(batch, idyD, idyR, idyC, ch);
|
|
int maxPosValue = ${h} -
|
|
int(getMaxPos(batch, idyD, idyR, idyC, ch));
|
|
|
|
// Get the current value, check it against the value from the
|
|
// position matrix.
|
|
int curPosValue =
|
|
wD * ${l} * ${u} +
|
|
wR * ${u} + wC;
|
|
float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0);
|
|
|
|
dotProd += dyValue * mask;
|
|
}
|
|
}
|
|
}
|
|
setOutput(dotProd);
|
|
}
|
|
`}};function Foe(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a}=t,o=a,{filterSize:i,strides:l,pad:u,dimRoundingMode:c}=r,p=[1,1,1],d=C.computePool3DInfo(o.shape,i,l,p,u,c),h=new b3(d,"max",!0),f=n.runWebGLProgram(h,[o],o.dtype),m=new Poe(d),g=n.runWebGLProgram(m,[s,f],o.dtype);return n.disposeIntermediateTensorInfo(f),g}var Ooe={kernelName:fm,backendName:"webgl",kernelFunc:Foe};function Moe(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,input:a,output:o}=t,i=a;Sc([a,o],"maxPoolGrad");let{filterSize:l,strides:u,pad:c,dimRoundingMode:p}=r,d=C.computePool2DInfo(i.shape,l,u,1,c,p),h=!0,f=new Kd(d,"max",h),m=n.runWebGLProgram(f,[i],i.dtype),g=new Doe(d),y=n.runWebGLProgram(g,[s,m],i.dtype);return n.disposeIntermediateTensorInfo(m),y}var zoe={kernelName:hm,backendName:"webgl",kernelFunc:Moe};function Loe(e,t,n,r){let s=new Kd(n,"max",!1),a=r.runWebGLProgram(s,[e],"float32");s=new Kd(n,"max",!0,!0,t);let o=r.runWebGLProgram(s,[e],"float32");return[a,o]}var Boe={kernelName:mm,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:r}=e,{filterSize:s,strides:a,pad:o,includeBatchInIndex:i}=t,l=n;w.assert(r.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${r.shape.length}.`);let u=[1,1];w.assert(C.eitherStridesOrDilationsAreOne(a,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${a} and dilations '${u}'`);let c=C.computePool2DInfo(r.shape,s,a,u,o),[p,d]=Loe(r,i,c,l);return[p,d]}};function Woe(e,t,n,r){let s=w.sizeFromShape(t),o=w.sizeFromShape(e.shape)/s,i=ve({inputs:{x:e},attrs:{shape:[o,s]},backend:r}),l=Ll(i,"float32","mean",r),u=ve({inputs:{x:l},attrs:{shape:n},backend:r});return r.disposeIntermediateTensorInfo(i),r.disposeIntermediateTensorInfo(l),u}var Voe={kernelName:wo,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:r}=e,{keepDims:s,axis:a}=t,o=n,i=r.shape.length,l=w.parseAxisParam(a,r.shape),u=l,c=C.getAxesPermutation(u,i),p=c!=null,d=o.shouldExecuteOnCPU([r]),h=[],f=r;if(p){if(d){let b=o.texData.get(f.dataId).values,v=new Array(i);for(let E=0;E<v.length;E++)v[E]=r.shape[c[E]];let S=A3(b,r.shape,r.dtype,c,v);f=o.makeTensorInfo(v,r.dtype);let I=o.texData.get(f.dataId);I.values=S}else f=I0(r,c,o);h.push(f),u=C.getInnerMostAxes(u.length,i)}C.assertAxesAreInnerMostDims("sum",u,i);let[m,g]=C.computeOutAndReduceShapes(f.shape,u),y=m;s&&(y=C.expandShapeToKeepDim(m,l));let x=Woe(f,g,y,o);for(let A of h)o.disposeIntermediateTensorInfo(A);return x}};function Uoe(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,l=w.parseAxisParam(a,s.shape),u=l,c=C.getAxesPermutation(u,i),p=s;c!=null&&(p=bn({inputs:{x:s},backend:n,attrs:{perm:c}}),u=C.getInnerMostAxes(u.length,s.shape.length)),C.assertAxesAreInnerMostDims("min",u,i);let[d,h]=C.computeOutAndReduceShapes(p.shape,u),f=w.sizeFromShape(h),m=ve({inputs:{x:p},backend:n,attrs:{shape:[-1,f]}}),g=Ll(m,m.dtype,"min",n),y;if(o){let x=C.expandShapeToKeepDim(d,l);y=ve({inputs:{x:g},backend:n,attrs:{shape:x}})}else y=ve({inputs:{x:g},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(g),c!=null&&n.disposeIntermediateTensorInfo(p),y}var Goe={kernelName:ko,backendName:"webgl",kernelFunc:Uoe},Hoe=n8+`
|
|
return min(a, b);
|
|
`,joe=`
|
|
vec4 result = vec4(min(a, b));
|
|
vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0));
|
|
`+k0+`
|
|
return result;
|
|
`,qoe=vn({opSnippet:Hoe,packedOpSnippet:joe,cpuKernelImpl:Lee}),Xoe={kernelName:So,backendName:"webgl",kernelFunc:qoe},Koe=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((u,c)=>u[0]+e[c]+u[1]);let r=e.length,s=yt(r),a=t.map(u=>u[0]).join(","),o=t.map((u,c)=>u[0]+e[c]).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r),l=n==="reflect"?0:1;if(r===1){this.userCode=`
|
|
int start = ${a};
|
|
int end = ${o};
|
|
|
|
void main() {
|
|
int outC = getOutputCoords();
|
|
if (outC < start) {
|
|
outC = start * 2 - outC - ${l};
|
|
} else if(outC >= end) {
|
|
outC = (end - 1) * 2 - outC + ${l};
|
|
}
|
|
setOutput(getX(outC - start));
|
|
}
|
|
`;return}this.userCode=`
|
|
${s} start = ${s}(${a});
|
|
${s} end = ${s}(${o});
|
|
|
|
void main() {
|
|
${s} outC = getOutputCoords();
|
|
for (int i = 0; i < ${r}; 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};
|
|
}
|
|
}
|
|
${s} coords = outC - start;
|
|
setOutput(getX(${i}));
|
|
}
|
|
`}},Zoe=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((h,f)=>h[0]+e[f]+h[1]);let r=e.length,s=yt(r),a=t.map(h=>h[0]).join(","),o=t.map((h,f)=>h[0]+e[f]).join(","),i=Un("rc",r),l=Un("source",r),u=`${i[r-1]} < ${this.outputShape[r-1]}`,c=r===1?"source":`vec2(${l.slice(-2).join()})`,p=n==="reflect"?0:1,d="";if(r===1){let h=`
|
|
${s} source = rc;
|
|
if (source < start) {
|
|
source = start * 2 - source - ${p};
|
|
} else if (source >= end) {
|
|
source = (end - 1) * 2 - source + ${p};
|
|
}
|
|
source -= start;
|
|
`;d=`
|
|
${s} rc = outputLoc;
|
|
${h}
|
|
result[0] = getChannel(getX(${l.join()}), ${c});
|
|
${i[r-1]} += 1;
|
|
if(${u}) {
|
|
${h}
|
|
result[1] = getChannel(getX(${l.join()}), ${c});
|
|
}
|
|
`}else{let h=`
|
|
${s} source = rc;
|
|
${s} lt = ${s}(lessThan(source, start));
|
|
${s} gte = ${s}(greaterThanEqual(source, end));
|
|
${s} orig = 1 - (lt + gte);
|
|
source = orig * source +
|
|
lt * (start * 2 - source - ${p}) +
|
|
gte * ((end - 1) * 2 - source + ${p});
|
|
source -= start;
|
|
`;d=`
|
|
${s} rc = outputLoc;
|
|
${h}
|
|
result[0] = getChannel(getX(${l.join()}), ${c});
|
|
${i[r-1]} += 1;
|
|
if(${u}) {
|
|
${h}
|
|
result[1] = getChannel(getX(${l.join()}), ${c});
|
|
}
|
|
rc = outputLoc;
|
|
${i[r-2]} += 1;
|
|
if(${i[r-2]} < ${this.outputShape[r-2]}) {
|
|
${h}
|
|
result[2] = getChannel(getX(${l.join()}), ${c});
|
|
${i[r-1]} += 1;
|
|
if(${u}) {
|
|
${h}
|
|
result[3] = getChannel(getX(${l.join()}), ${c});
|
|
}
|
|
}
|
|
`}this.userCode=`
|
|
const ${s} start = ${s}(${a});
|
|
const ${s} end = ${s}(${o});
|
|
|
|
void main() {
|
|
${s} outputLoc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
${d}
|
|
setOutput(result);
|
|
}
|
|
`}},Yoe=({inputs:e,backend:t,attrs:n})=>{let{x:r}=e,{paddings:s,mode:a}=n,o=Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new Zoe(r.shape,s,a):new Koe(r.shape,s,a);return t.runWebGLProgram(o,[r],r.dtype)},Joe={kernelName:Io,backendName:"webgl",kernelFunc:Yoe},Qoe=`if (b == 0.0) return NAN;
|
|
return mod(a, b);`,eie=`
|
|
vec4 result = mod(a, b);
|
|
vec4 isNaN = vec4(equal(b, vec4(0.0)));
|
|
`+k0+`
|
|
return result;
|
|
`,tie=vn({opSnippet:Qoe,packedOpSnippet:eie}),nie={kernelName:tc,backendName:"webgl",kernelFunc:tie},rie=class{constructor(e,t,n){this.variableNames=["probs"],this.customUniforms=[{name:"seed",type:"float"}],this.outputShape=[e,n],this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
|
|
float r = random(seed);
|
|
float cdf = 0.0;
|
|
|
|
for (int i = 0; i < ${t-1}; i++) {
|
|
cdf += getProbs(batch, i);
|
|
|
|
if (r < cdf) {
|
|
setOutput(float(i));
|
|
return;
|
|
}
|
|
}
|
|
|
|
// If no other event happened, last event happened.
|
|
setOutput(float(${t-1}));
|
|
}
|
|
`}},sie=`
|
|
if (a == b) {
|
|
return 1.0;
|
|
};
|
|
return a / b;`,aie=`
|
|
// 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;
|
|
`,k8=vn({opSnippet:sie,packedOpSnippet:aie,checkOutOfBounds:!0}),oie={kernelName:lo,backendName:"webgl",kernelFunc:k8},t4="return a - b;",S8=vn({opSnippet:t4,packedOpSnippet:t4,supportsComplex:!0,cpuKernelImpl:tte}),iie={kernelName:Wo,backendName:"webgl",kernelFunc:S8};function I8(e){let{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{dim:a}=r,o=w.parseAxisParam([a],s.shape),i=w8({inputs:{x:s},backend:n,attrs:{reductionIndices:o,keepDims:!1}}),l=C.expandShapeToKeepDim(i.shape,o),u=ve({inputs:{x:i},backend:n,attrs:{shape:l}}),c=S8({inputs:{a:s,b:u},backend:n}),p=x8({inputs:{x:c},backend:n}),d=C0({inputs:{x:p},backend:n,attrs:{axis:o,keepDims:!1}}),h=ve({inputs:{x:d},backend:n,attrs:{shape:l}}),f=k8({inputs:{a:p,b:h},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h),f}var lie={kernelName:Lo,backendName:"webgl",kernelFunc:I8};function uie(e){let{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{numSamples:a,seed:o,normalized:i}=r,l=i?s:I8({inputs:{logits:s},backend:n,attrs:{dim:s.shape.length-1}}),u=l.shape[0],c=l.shape[1],p=new rie(u,c,a),d=[[o]],h=n.runWebGLProgram(p,[l],"int32",d);return i||n.disposeIntermediateTensorInfo(l),h}var cie={kernelName:gm,backendName:"webgl",kernelFunc:uie},die=Yr+`
|
|
return -x;
|
|
`,pie=`
|
|
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 hie(e){let{inputs:t,backend:n}=e,{x:r}=t;if(n.shouldExecuteOnCPU([r])){let a=n.texData.get(r.dataId),[o,i]=Wee(a.values,r.shape,r.dtype);return n.makeTensorInfo(i,r.dtype,o)}let s;return Y().getBool("WEBGL_PACK_UNARY_OPERATIONS")?s=new Ci(r.shape,pie):s=new Zs(r.shape,die),n.runWebGLProgram(s,[r],r.dtype)}var fie={kernelName:ol,backendName:"webgl",kernelFunc:hie},mie=Kr.nonMaxSuppressionV3Impl;function gie(e){C.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:l}=r,u=n.readSync(s.dataId),c=n.readSync(a.dataId),{selectedIndices:p}=mie(u,c,o,i,l);return n.makeTensorInfo([p.length],"int32",new Int32Array(p))}var yie={kernelName:ll,backendName:"webgl",kernelFunc:gie},Aie=Kr.nonMaxSuppressionV4Impl;function xie(e){C.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:l,padToMaxOutputSize:u}=r,c=n.readSync(s.dataId),p=n.readSync(a.dataId),{selectedIndices:d,validOutputs:h}=Aie(c,p,o,i,l,u);return[n.makeTensorInfo([d.length],"int32",new Int32Array(d)),n.makeTensorInfo([],"int32",new Int32Array([h]))]}var bie={kernelName:nc,backendName:"webgl",kernelFunc:xie},vie=Kr.nonMaxSuppressionV5Impl;function wie(e){C.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:l,softNmsSigma:u}=r,c=n.readSync(s.dataId),p=n.readSync(a.dataId),d=o,h=i,f=l,m=u,{selectedIndices:g,selectedScores:y}=vie(c,p,d,h,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var kie={kernelName:ul,backendName:"webgl",kernelFunc:wie},Sie=class{constructor(e,t,n,r){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=`
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int index = round(getIndices(coords.x));
|
|
setOutput(mix(float(${r}), float(${n}),
|
|
float(index == coords.y)));
|
|
}
|
|
`}},Iie=e=>{let{inputs:t,backend:n,attrs:r}=e,{indices:s}=t,{depth:a,onValue:o,offValue:i}=r,l=w.sizeFromShape(s.shape),u=new Sie(l,a,o,i),c=ve({inputs:{x:s},backend:n,attrs:{shape:[l]}}),p=n.runWebGLProgram(u,[c],s.dtype);n.disposeIntermediateTensorInfo(c);let d=[...s.shape,a],h=ve({inputs:{x:p},backend:n,attrs:{shape:d}});return n.disposeIntermediateTensorInfo(p),h},Cie={kernelName:dl,backendName:"webgl",kernelFunc:Iie};function Gf(e){let{inputs:t,backend:n}=e,{x:r}=t;if(r.dtype==="complex64"){let s=Vp({inputs:{input:r},backend:n}),a=Gf({inputs:{x:s},backend:n}),o=T0({inputs:{input:r},backend:n}),i=Gf({inputs:{x:o},backend:n}),l=Xo({inputs:{real:a,imag:i},backend:n});return n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),l}else return Up({attrs:{shape:r.shape,dtype:r.dtype,value:r.dtype==="string"?"":0},backend:n})}var Tie={kernelName:Tl,backendName:"webgl",kernelFunc:Gf};function C8(e){let{inputs:t,backend:n}=e,{x:r}=t;if(r.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(r.dtype==="complex64"){let s=Vp({inputs:{input:r},backend:n}),a=C8({inputs:{x:s},backend:n}),o=T0({inputs:{input:r},backend:n}),i=Gf({inputs:{x:o},backend:n}),l=Xo({inputs:{real:a,imag:i},backend:n});return n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(a),n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(i),l}else return Up({attrs:{shape:r.shape,dtype:r.dtype,value:1},backend:n})}var Nie={kernelName:cl,backendName:"webgl",kernelFunc:C8};function Eie(e){let{inputs:t,backend:n,attrs:r}=e,{axis:s}=r;if(t.length===1)return ny({inputs:{input:t[0]},backend:n,attrs:{dim:s}});let a=t[0].shape,o=t[0].dtype;t.forEach(c=>{w.assertShapesMatch(a,c.shape,"All tensors passed to stack must have matching shapes"),w.assert(o===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=t.map(c=>{let p=ny({inputs:{input:c},backend:n,attrs:{dim:s}});return i.push(p),p}),u=h8({inputs:l,backend:n,attrs:{axis:s}});return i.forEach(c=>n.disposeIntermediateTensorInfo(c)),u}var Rie={kernelName:pl,backendName:"webgl",kernelFunc:Eie},_ie=class{constructor(e,t,n){this.variableNames=["x"],this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((l,u)=>l[0]+e[u]+l[1]);let r=e.length,s=yt(r),a=t.map(l=>l[0]).join(","),o=t.map((l,u)=>l[0]+e[u]).join(","),i=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,r);if(r===1){this.userCode=`
|
|
int start = ${a};
|
|
int end = ${o};
|
|
|
|
void main() {
|
|
int outC = getOutputCoords();
|
|
if (outC < start || outC >= end) {
|
|
setOutput(value);
|
|
} else {
|
|
setOutput(getX(outC - start));
|
|
}
|
|
}
|
|
`;return}this.userCode=`
|
|
${s} start = ${s}(${a});
|
|
${s} end = ${s}(${o});
|
|
|
|
void main() {
|
|
${s} outC = getOutputCoords();
|
|
if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) {
|
|
setOutput(value);
|
|
} else {
|
|
${s} coords = outC - start;
|
|
setOutput(getX(${i}));
|
|
}
|
|
}
|
|
`}},$ie=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.customUniforms=[{name:"value",type:"float"}],this.outputShape=t.map((f,m)=>f[0]+e[m]+f[1]);let r=e.length,s=yt(r),a=t.map(f=>f[0]).join(","),o=t.map((f,m)=>f[0]+e[m]).join(","),i=Un("rc",r),l=Un("source",r),u=`${i[r-1]} < ${this.outputShape[r-1]}`,c=r===1?"source":`vec2(${l.slice(-2).join()})`,p=[`${s} rc = outputLoc;`,`${i[r-1]} += 1;
|
|
if(${u}) {
|
|
`,r===1?"":`}
|
|
rc = outputLoc;
|
|
${i[r-2]} += 1;
|
|
if(${i[r-2]} < ${this.outputShape[r-2]}) {`,r===1?"":` ${i[r-1]} += 1;
|
|
if(${u}) {`],d=r===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",h="";for(let f=0,m=r===1?2:4;f<m;f++)h+=`
|
|
${p[f]}
|
|
if (${d}) {
|
|
result[${f}] = float(value);
|
|
} else {
|
|
${s} source = rc - start;
|
|
result[${f}] = getChannel(getX(${l.join()}), ${c});
|
|
}
|
|
`;h+=r===1?"} ":"}}",this.userCode=`
|
|
const ${s} start = ${s}(${a});
|
|
const ${s} end = ${s}(${o});
|
|
|
|
void main() {
|
|
${s} outputLoc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
${h}
|
|
setOutput(result);
|
|
}
|
|
`}},T8=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{paddings:a,constantValue:o}=r;if(w.sizeFromShape(s.shape)===0){let u=a.map((c,p)=>c[0]+s.shape[p]+c[1]);return Up({backend:n,attrs:{shape:u,value:o,dtype:s.dtype}})}let i=Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new $ie(s.shape,a,o):new _ie(s.shape,a,o),l=[[o]];return n.runWebGLProgram(i,[s],s.dtype,l)},Die={kernelName:To,backendName:"webgl",kernelFunc:T8},Pie=`
|
|
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);
|
|
`,Fie=`
|
|
// 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));
|
|
`+k0+`
|
|
return result;
|
|
`,Oie=vn({opSnippet:Pie,packedOpSnippet:Fie}),Mie={kernelName:No,backendName:"webgl",kernelFunc:Oie};function zie(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r,i=s.shape.length,l=[],u=w.parseAxisParam(a,s.shape),c=u,p=C.getAxesPermutation(c,i),d=s;p!=null&&(d=bn({inputs:{x:s},backend:n,attrs:{perm:p}}),c=C.getInnerMostAxes(c.length,i),l.push(d)),C.assertAxesAreInnerMostDims("prod",c,i);let h;if(n.shouldExecuteOnCPU([d])){let f=n.texData.get(d.dataId).values,{outVals:m,outShape:g,outDtype:y}=Uee(d.shape,d.dtype,f,c);h=n.makeTensorInfo(g,y,m)}else{let[f,m]=C.computeOutAndReduceShapes(d.shape,c),g=w.sizeFromShape(m),y=ve({inputs:{x:d},backend:n,attrs:{shape:[-1,g]}}),x=gp(s.dtype),A=Ll(y,x,"prod",n);h=ve({inputs:{x:A},backend:n,attrs:{shape:f}}),l.push(y),l.push(A)}if(o){l.push(h);let f=C.expandShapeToKeepDim(h.shape,u);h=ve({inputs:{x:h},backend:n,attrs:{shape:f}})}return l.forEach(f=>n.disposeIntermediateTensorInfo(f)),h}var Lie={kernelName:Ro,backendName:"webgl",kernelFunc:zie},N8=e=>{let{backend:t,attrs:n}=e,{start:r,stop:s,step:a,dtype:o}=n,i=Gee(r,s,a,o);return t.makeTensorInfo([i.length],o,i)},Bie={kernelName:rc,backendName:"webgl",kernelFunc:N8},Wie="return 1.0 / x;",Vie=ot({opSnippet:Wie}),Uie={kernelName:sc,backendName:"webgl",kernelFunc:Vie},Gie=Yr+`
|
|
return (x < 0.0) ? 0.0 : x;
|
|
`,Hie=`
|
|
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;
|
|
`,jie=ot({opSnippet:Gie,packedOpSnippet:Hie}),qie={kernelName:_o,backendName:"webgl",kernelFunc:jie},Xie=Yr+`
|
|
return (x < 0.0) ? 0.0 : min(6.0, x);
|
|
`,Kie=`
|
|
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;
|
|
`,Zie=ot({opSnippet:Xie,packedOpSnippet:Kie}),Yie={kernelName:Do,backendName:"webgl",kernelFunc:Zie},Jie=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.outputShape=[];let[a,o,i,l]=e;this.outputShape=[a,t,n,l];let u=[r&&t>1?o-1:o,r&&n>1?i-1:i],c=[r&&t>1?t-1:t,r&&n>1?n-1:n],p;s?p="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":p="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec2 effectiveInputOverOutputRatioRC = vec2(
|
|
${u[0]/c[0]},
|
|
${u[1]/c[1]});
|
|
const vec2 inputShapeRC = vec2(${o}.0, ${i}.0);
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
ivec2 yRC = coords.yz;
|
|
|
|
// Fractional source index.
|
|
vec2 sourceFracIndexRC = ${p};
|
|
|
|
// Compute the four integer indices.
|
|
ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0)));
|
|
ivec2 sourceCeilRC = ivec2(
|
|
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
|
|
|
|
float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d);
|
|
float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d);
|
|
float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d);
|
|
float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d);
|
|
|
|
vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC);
|
|
|
|
float top = topLeft + (topRight - topLeft) * fracRC.y;
|
|
float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y;
|
|
float newValue = top + (bottom - top) * fracRC.x;
|
|
|
|
setOutput(newValue);
|
|
}
|
|
`}},Qie=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[a,o,i,l]=e;this.outputShape=[a,t,n,l];let u=[r&&t>1?o-1:o,r&&n>1?i-1:i],c=[r&&t>1?t-1:t,r&&n>1?n-1:n],p;s?p="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":p="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec3 effectiveInputOverOutputRatioRC = vec3(
|
|
${u[0]/c[0]},
|
|
${u[1]/c[1]},
|
|
${u[1]/c[1]});
|
|
const vec3 inputShapeRC = vec3(${o}.0, ${i}.0,
|
|
${i}.0);
|
|
|
|
float getAValue(int b, int r, int c, int d) {
|
|
return getChannel(getA(b, r, c, d), vec2(c, d));
|
|
}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
// Calculate values for next column in yRC.z.
|
|
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
|
|
|
|
// Fractional source index.
|
|
vec3 sourceFracIndexRC = ${p};
|
|
|
|
// Compute the four integer indices.
|
|
ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0)));
|
|
ivec3 sourceCeilRC = ivec3(
|
|
min(inputShapeRC - 1.0, ceil(sourceFracIndexRC)));
|
|
|
|
// Should we calculate next column and row elements in 2x2 packed cell.
|
|
bool hasNextCol = d < ${l-1};
|
|
bool hasNextRow = coords.z < ${n-1};
|
|
|
|
// In parallel, construct four corners for all four components in
|
|
// packed 2x2 cell.
|
|
vec4 topLeft = vec4(
|
|
getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d),
|
|
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceFloorRC.y, d + 1)
|
|
: 0.0,
|
|
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d)
|
|
: 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getAValue(b, sourceFloorRC.x, sourceFloorRC.z, d + 1) : 0.0);
|
|
|
|
vec4 bottomLeft = vec4(
|
|
getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d),
|
|
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceFloorRC.y, d + 1)
|
|
: 0.0,
|
|
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d)
|
|
: 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getAValue(b, sourceCeilRC.x, sourceFloorRC.z, d + 1) : 0.0);
|
|
|
|
vec4 topRight = vec4(
|
|
getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d),
|
|
hasNextCol ? getAValue(b, sourceFloorRC.x, sourceCeilRC.y, d + 1)
|
|
: 0.0,
|
|
hasNextRow ? getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d)
|
|
: 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getAValue(b, sourceFloorRC.x, sourceCeilRC.z, d + 1) : 0.0);
|
|
|
|
vec4 bottomRight = vec4(
|
|
getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d),
|
|
hasNextCol ? getAValue(b, sourceCeilRC.x, sourceCeilRC.y, d + 1)
|
|
: 0.0,
|
|
hasNextRow ? getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d)
|
|
: 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getAValue(b, sourceCeilRC.x, sourceCeilRC.z, d + 1) : 0.0);
|
|
|
|
vec3 fracRC = sourceFracIndexRC - vec3(sourceFloorRC);
|
|
|
|
vec4 top = mix(topLeft, topRight, fracRC.yyzz);
|
|
vec4 bottom = mix(bottomLeft, bottomRight, fracRC.yyzz);
|
|
vec4 newValue = mix(top, bottom, fracRC.x);
|
|
|
|
setOutput(newValue);
|
|
}
|
|
`}};function ele(e){let{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:o,size:i}=r,[l,u]=i,c=Y().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new Qie(s.shape,l,u,a,o):new Jie(s.shape,l,u,a,o);return n.runWebGLProgram(c,[s],"float32")}var tle={kernelName:$o,backendName:"webgl",kernelFunc:ele},nle=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,r,s]=t,[,a,o]=e,i=[n&&a>1?r-1:r,n&&o>1?s-1:s],l=[n&&a>1?a-1:a,n&&o>1?o-1:o],u=i[0]/l[0],c=i[1]/l[1],p=1/u,d=1/c,h=Math.ceil(p)*2+2,f=Math.ceil(d)*2+2;this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
int r = coords[1];
|
|
int c = coords[2];
|
|
|
|
float accumulator = 0.0;
|
|
|
|
const float heightScale = float(${u});
|
|
const float widthScale = float(${c});
|
|
|
|
const float invHeightScale = float(${p});
|
|
const float invWidthScale = float(${d});
|
|
|
|
const int winHeight = int(${h});
|
|
const int winWidth = int(${f});
|
|
|
|
// Compute bounds for where in dy we will look
|
|
float startRLerp = floor(float(r) * invHeightScale);
|
|
int startDyR = int(startRLerp - float(winHeight / 2));
|
|
|
|
float startCLerp = floor(float(c) * invWidthScale);
|
|
int startDyC = int(startCLerp - float(winWidth / 2));
|
|
|
|
// Loop over dy
|
|
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
|
|
int dyR = dyROffset + startDyR;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyR < 0 || dyR >= ${a}) {
|
|
continue;
|
|
}
|
|
|
|
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
|
|
int dyC = dyCOffset + startDyC;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyC < 0 || dyC >= ${o}) {
|
|
continue;
|
|
}
|
|
|
|
float dxR = float(dyR) * heightScale;
|
|
int topDxRIndex = int(floor(dxR));
|
|
int bottomDxRIndex = int(min(ceil(dxR), ${r-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), ${s-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 rle(e){let{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:o}=r,i=new nle(a.shape,s.shape,o);return n.runWebGLProgram(i,[a],a.dtype)}var sle={kernelName:Am,backendName:"webgl",kernelFunc:rle},ale=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.outputShape=[];let[a,o,i,l]=e;this.outputShape=[a,t,n,l];let u=[r&&t>1?o-1:o,r&&n>1?i-1:i],c=[r&&t>1?t-1:t,r&&n>1?n-1:n],p=r?"0.5":"0.0",d;s?d="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":d="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec2 effectiveInputOverOutputRatioRC = vec2(
|
|
${u[0]/c[0]},
|
|
${u[1]/c[1]});
|
|
const vec2 inputShapeRC = vec2(${o}.0, ${i}.0);
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
ivec2 yRC = coords.yz;
|
|
|
|
// Fractional source index.
|
|
vec2 sourceFracIndexRC = ${d};
|
|
|
|
// Compute the coordinators of nearest neighbor point.
|
|
ivec2 sourceNearestRC = ivec2(
|
|
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${p})));
|
|
float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d);
|
|
|
|
setOutput(newValue);
|
|
}
|
|
`}},ole=class{constructor(e,t,n,r,s){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[a,o,i,l]=e;this.outputShape=[a,t,n,l];let u=[r&&t>1?o-1:o,r&&n>1?i-1:i],c=[r&&t>1?t-1:t,r&&n>1?n-1:n],p=r?"0.5":"0.0",d;s?d="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":d="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=`
|
|
const vec3 effectiveInputOverOutputRatioRC = vec3(
|
|
${u[0]/c[0]},
|
|
${u[1]/c[1]},
|
|
${u[1]/c[1]});
|
|
const vec3 inputShapeRC = vec3(${o}.0, ${i}.0,
|
|
${i}.0);
|
|
|
|
float getAValue(int b, int r, int c, int d) {
|
|
return getChannel(getA(b, r, c, d), vec2(c, d));
|
|
}
|
|
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
// Calculate values for next column in yRC.z.
|
|
ivec3 yRC = coords.yzz + ivec3(0, 0, 1);
|
|
|
|
// Fractional source index.
|
|
vec3 sourceFracIndexRC = ${d};
|
|
|
|
// Compute the coordinators of nearest neighbor point.
|
|
ivec3 sourceNearestRC = ivec3(
|
|
min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${p})));
|
|
|
|
// Should we calculate next column and row elements in 2x2 packed cell.
|
|
bool hasNextCol = d < ${l-1};
|
|
bool hasNextRow = coords.z < ${n-1};
|
|
|
|
vec4 newValue = vec4(
|
|
getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d),
|
|
hasNextCol ? getAValue(b, sourceNearestRC.x, sourceNearestRC.y, d + 1)
|
|
: 0.0,
|
|
hasNextRow ? getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d)
|
|
: 0.0,
|
|
(hasNextRow && hasNextCol) ?
|
|
getAValue(b, sourceNearestRC.x, sourceNearestRC.z, d + 1) : 0.0);
|
|
|
|
setOutput(newValue);
|
|
}
|
|
`}};function ile(e){let{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:o,size:i}=r,[l,u]=i,c=Y().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new ole(s.shape,l,u,a,o):new ale(s.shape,l,u,a,o);return n.runWebGLProgram(c,[s],s.dtype)}var lle={kernelName:ac,backendName:"webgl",kernelFunc:ile},ule=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,r,s]=t,[,a,o]=e,i=[n&&a>1?r-1:r,n&&o>1?s-1:s],l=[n&&a>1?a-1:a,n&&o>1?o-1:o],u=i[0]/l[0],c=i[1]/l[1],p=1/u,d=1/c,h=Math.ceil(p)*2+2,f=Math.ceil(d)*2+2;this.userCode=`
|
|
void main() {
|
|
ivec4 coords = getOutputCoords();
|
|
int b = coords[0];
|
|
int d = coords[3];
|
|
int r = coords[1];
|
|
int c = coords[2];
|
|
|
|
float accumulator = 0.0;
|
|
|
|
const float heightScale = float(${u});
|
|
const float widthScale = float(${c});
|
|
|
|
const float invHeightScale = float(${p});
|
|
const float invWidthScale = float(${d});
|
|
|
|
const int winHeight = int(${h});
|
|
const int winWidth = int(${f});
|
|
|
|
// Compute bounds for where in dy we will look
|
|
float startRLerp = floor(float(r) * invHeightScale);
|
|
int startDyR = int(floor(startRLerp - float(winHeight / 2)));
|
|
|
|
float startCLerp = floor(float(c) * invWidthScale);
|
|
int startDyC = int(floor(startCLerp - float(winWidth / 2)));
|
|
|
|
// Loop over dy
|
|
for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) {
|
|
int dyR = dyROffset + startDyR;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyR < 0 || dyR >= ${a}) {
|
|
continue;
|
|
}
|
|
|
|
for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) {
|
|
int dyC = dyCOffset + startDyC;
|
|
|
|
// Guard against the window exceeding the bounds of dy
|
|
if (dyC < 0 || dyC >= ${o}) {
|
|
continue;
|
|
}
|
|
|
|
float sourceFracRow =
|
|
float(${i[0]}) *
|
|
(float(dyR) / float(${l[0]}));
|
|
|
|
float sourceFracCol =
|
|
float(${i[1]}) *
|
|
(float(dyC) / float(${l[1]}));
|
|
|
|
int sourceNearestRow = int(min(
|
|
float(int(${r}) - 1),
|
|
${n} ? float(round(sourceFracRow)) :
|
|
float(floor(sourceFracRow))));
|
|
|
|
int sourceNearestCol = int(min(
|
|
float(int(${s}) - 1),
|
|
${n} ? float(round(sourceFracCol)) :
|
|
float(floor(sourceFracCol))));
|
|
|
|
if (r == sourceNearestRow && c == sourceNearestCol) {
|
|
accumulator += getDy(b, dyR, dyC, d);
|
|
}
|
|
}
|
|
}
|
|
// End loop over dy
|
|
|
|
setOutput(accumulator);
|
|
}
|
|
`}};function cle(e){let{inputs:t,backend:n,attrs:r}=e,{images:s,dy:a}=t,{alignCorners:o}=r,i=new ule(a.shape,s.shape,o);return n.runWebGLProgram(i,[a],a.dtype)}var dle={kernelName:ym,backendName:"webgl",kernelFunc:cle},ple=class{constructor(e,t){this.variableNames=["x"];let n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);if(this.outputShape=e,n===1){this.userCode=`
|
|
void main() {
|
|
int coord = getOutputCoords();
|
|
setOutput(getX(${e[0]} - coord - 1));
|
|
}
|
|
`;return}let r=o=>t.indexOf(o)!==-1&&e[o]!==1?`${e[o]} - coords[${o}] - 1`:`coords[${o}]`,s=e.map((o,i)=>r(i)).join(","),a=yt(n);this.userCode=`
|
|
void main() {
|
|
${a} coords = getOutputCoords();
|
|
setOutput(getX(${s}));
|
|
}
|
|
`}},hle=class{constructor(e,t){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0;let n=e.length;if(n>4)throw new Error(`WebGL backend: Reverse of rank-${n} tensor is not yet supported`);this.outputShape=e;let r=Un("rc",n),s=`${r[n-1]} + 1 < ${this.outputShape[n-1]}`,a=`${r[n-2]} + 1 < ${this.outputShape[n-2]}`,o=yt(n);n===1?this.userCode=`
|
|
void main(){
|
|
int rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result.r = getChannel(getX(${e[0]} - rc - 1),
|
|
${e[0]} - rc - 1);
|
|
if(${s}){
|
|
result.g = getChannel(getX(${e[0]} - (rc + 1) - 1),
|
|
${e[0]} - (rc + 1) - 1);
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`:this.userCode=`
|
|
void main() {
|
|
${o} rc = getOutputCoords();
|
|
vec4 result = vec4(0.);
|
|
result.r = ${i(r.slice())};
|
|
if(${s}){
|
|
result.g = ${l(r.slice())};
|
|
}
|
|
if(${a}) {
|
|
result.b = ${u(r.slice())};
|
|
if(${s}) {
|
|
result.a = ${c(r.slice())};
|
|
}
|
|
}
|
|
setOutput(result);
|
|
}
|
|
`;function i(h){return p(h)}function l(h){return h[n-1]="("+h[n-1]+" + 1)",p(h)}function u(h){return h[n-2]="("+h[n-2]+" + 1)",p(h)}function c(h){return h[n-1]="("+h[n-1]+" + 1)",h[n-2]="("+h[n-2]+" + 1)",p(h)}function p(h){let f=e.map((y,x)=>d(x,h)),m=f.join(","),g=f.slice(-2).join(",");return`getChannel(getX(${m}), vec2(${g}))`}function d(h,f){return t.indexOf(h)!==-1&&e[h]!==1?`${e[h]} - ${f[h]} - 1`:`${f[h]}`}}};function fle(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dims:a}=r,o=s.shape.length,i=w.parseAxisParam(a,s.shape);if(o===0)return or({inputs:{x:s},backend:n});let l=Y().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new hle(s.shape,i):new ple(s.shape,i);return n.runWebGLProgram(l,[s],s.dtype)}var mle={kernelName:fl,backendName:"webgl",kernelFunc:fle},gle=class{constructor(e,t){this.variableNames=["Image"],this.outputShape=[],this.customUniforms=[{name:"params",type:"vec4"}];let n=e[1],r=e[2];this.outputShape=e;let s="";typeof t=="number"?s=`float outputValue = ${t.toFixed(2)};`:s=`
|
|
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]));
|
|
${s}
|
|
if(coordX >= 0 && coordX < ${r} && coordY >= 0 && coordY < ${n}) {
|
|
outputValue = getImage(coords[0], coordY, coordX, coords[3]);
|
|
}
|
|
setOutput(outputValue);
|
|
}
|
|
`}},yle={kernelName:Nl,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:r}=e,{radians:s,fillValue:a,center:o}=t,i=n,l=new gle(r.shape,a),[u,c]=C.getImageCenter(o,r.shape[1],r.shape[2]),p=[[u,c,Math.sin(s),Math.cos(s)]];return i.runWebGLProgram(l,[r],r.dtype,p)}},Ale=`
|
|
// 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;
|
|
}
|
|
}
|
|
`,xle=ot({opSnippet:Ale}),ble={kernelName:ml,backendName:"webgl",kernelFunc:xle},vle="return inversesqrt(x);",wle=ot({opSnippet:vle,cpuKernelImpl:Hee}),kle={kernelName:Po,backendName:"webgl",kernelFunc:wle},E8=class{constructor(e,t,n,r,s,a,o=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=a;let i=yt(s.length),l=yt(a.length),u="";n===1?u="i":n===2&&(u="i, j");let c=`getIndices(${u})`,p="";r===1?p="i":r===2&&(p="i, coords[1]");let d=`getUpdates(${p})`,h=t>1?"strides[j]":"strides";this.userCode=`
|
|
${i} strides = ${i}(${s});
|
|
|
|
void main() {
|
|
${l} coords = getOutputCoords();
|
|
float sum = 0.0;
|
|
bool found = false;
|
|
for (int i = 0; i < ${e}; i++) {
|
|
int flattenedIndex = 0;
|
|
for (int j = 0; j < ${t}; j++) {
|
|
int index = round(${c});
|
|
flattenedIndex += index * ${h};
|
|
}
|
|
if (flattenedIndex == coords[0]) {
|
|
sum += ${d};
|
|
found = true;
|
|
}
|
|
}
|
|
setOutput(mix(getDefaultValue(), sum, float(found)));
|
|
}
|
|
`}};function Sle(e){let{inputs:t,backend:n,attrs:r}=e,{indices:s,updates:a}=t,{shape:o}=r,{sliceRank:i,numUpdates:l,sliceSize:u,strides:c,outputSize:p}=C.calculateShapes(a,s,o),d=[p/u,u];if(p===0)return n.makeTensorInfo(o,s.dtype);let h=ve({inputs:{x:s},backend:n,attrs:{shape:[l,i]}}),f=ve({inputs:{x:a},backend:n,attrs:{shape:[l,u]}}),m=n.makeTensorInfo([],"float32",new Float32Array([0])),g=new E8(l,i,h.shape.length,f.shape.length,c,d),y=n.runWebGLProgram(g,[f,h,m],f.dtype),x=ve({inputs:{x:y},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(m),x}var Ile={kernelName:gl,backendName:"webgl",kernelFunc:Sle},Cle=class{constructor(e,t,n){this.variableNames=["c","a","b"],this.outputShape=t;let r,s;if(n>4)throw Error(`Where for rank ${n} is not yet supported`);if(n===1)s="resRC",r="resRC";else{let o=["resRC.x","resRC.y","resRC.z","resRC.w"],i=[],l=[];for(let u=0;u<t.length;u++)l.push(`${o[u]}`),u<e&&i.push(`${o[u]}`);r=i.join(),s=l.join()}let a=yt(n);this.userCode=`
|
|
void main() {
|
|
${a} resRC = getOutputCoords();
|
|
float cVal = getC(${r});
|
|
if (cVal >= 1.0) {
|
|
setOutput(getA(${s}));
|
|
} else {
|
|
setOutput(getB(${s}));
|
|
}
|
|
}
|
|
`}};function Tle(e){let{inputs:t,backend:n}=e,{condition:r,t:s,e:a}=t,o=new Cle(r.shape.length,s.shape,s.shape.length);return n.runWebGLProgram(o,[r,s,a],Nn(s.dtype,a.dtype))}var Nle={kernelName:yl,backendName:"webgl",kernelFunc:Tle},Ele=`
|
|
// Stable and Attracting Fixed Point (0, 1) for Normalized Weights.
|
|
// see: https://arxiv.org/abs/1706.02515
|
|
float scaleAlpha = ${C.SELU_SCALEALPHA};
|
|
float scale = ${C.SELU_SCALE};
|
|
return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0);
|
|
`,Rle=ot({opSnippet:Ele}),_le={kernelName:oc,backendName:"webgl",kernelFunc:Rle},$le=Ec+`
|
|
return 1.0 / (1.0 + exp(-1.0 * x));
|
|
`,Dle=`
|
|
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;
|
|
`,Ple=ot({opSnippet:$le,packedOpSnippet:Dle,cpuKernelImpl:jee}),Fle={kernelName:Oo,backendName:"webgl",kernelFunc:Ple},Ole=`
|
|
if (isnan(x)) { return 0.0; }
|
|
return sign(x);
|
|
`,Mle=ot({opSnippet:Ole}),zle={kernelName:ic,backendName:"webgl",kernelFunc:Mle},Lle=Ec+`
|
|
return sin(x);
|
|
`,Ble=ot({opSnippet:Lle}),Wle={kernelName:Fo,backendName:"webgl",kernelFunc:Ble},Vle=`
|
|
float e2x = exp(x);
|
|
return (e2x - 1.0 / e2x) / 2.0;
|
|
`,Ule=ot({opSnippet:Vle}),Gle={kernelName:xl,backendName:"webgl",kernelFunc:Ule},Hle=`
|
|
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;
|
|
`,jle=ot({opSnippet:Hle}),qle={kernelName:lc,backendName:"webgl",kernelFunc:jle},Xle=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,paddings:o}=r;w.assert(s.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let i=a.reduce((y,x)=>y*x),l=[[0,0]];l.push(...o);for(let y=1+a.length;y<s.shape.length;++y)l.push([0,0]);let u=[],c=T8({inputs:{x:s},backend:n,attrs:{paddings:l,constantValue:0}}),p=C.getReshaped(c.shape,a,i,!1),d=C.getPermuted(p.length,a.length,!1),h=C.getReshapedPermuted(c.shape,a,i,!1),f=ve({inputs:{x:c},backend:n,attrs:{shape:p}}),m=bn({inputs:{x:f},backend:n,attrs:{perm:d}}),g=ve({inputs:{x:m},backend:n,attrs:{shape:h}});return u.push(c),u.push(f),u.push(m),u.forEach(y=>n.disposeIntermediateTensorInfo(y)),g},Kle={kernelName:bl,backendName:"webgl",kernelFunc:Xle};function Zle(e){let{inputs:t,backend:n}=e,{indices:r,values:s,denseShape:a,defaultValue:o}=t;if(a.shape.length!==1)throw new Error(`Dense shape must be a vector, saw:
|
|
${a.shape}`);if(r.shape.length!==2)throw new Error(`Indices must be a matrix, saw:
|
|
${r.shape}`);if(s.shape.length!==1)throw new Error(`Values must be a vector, saw:
|
|
${s.shape}`);if(o.shape.length!==0)throw new Error(`Default value must be a scalar, saw:
|
|
${o.shape}`);let i=n.readSync(r.dataId),l=n.readSync(s.dataId),u=n.readSync(a.dataId),c=n.readSync(o.dataId)[0],[p,d,h,f,m]=Xee(i,r.shape,r.dtype,l,s.dtype,u,c);return[n.makeTensorInfo(d,r.dtype,p),n.makeTensorInfo([d[0]],s.dtype,h),n.makeTensorInfo([f.length],"bool",new Uint8Array(f.map(g=>Number(g)))),n.makeTensorInfo([m.length],r.dtype,new Int32Array(m))]}var Yle={kernelName:lp,backendName:"webgl",kernelFunc:Zle};function Jle(e){let{inputs:t,backend:n}=e,{inputIndices:r,inputShape:s,newShape:a}=t;if(r.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape ${r.shape}`);if(s.shape.length!==1)throw new Error(`Input shape should be a vector but received shape ${s.shape}`);if(a.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);let o=Array.from(n.readSync(s.dataId)),i=n.readSync(r.dataId),l=Array.from(n.readSync(a.dataId)),[u,c,p]=Kee(i,r.shape,r.dtype,o,l);return[n.makeTensorInfo(c,r.dtype,u),n.makeTensorInfo([p.length],a.dtype,new Int32Array(p))]}var Qle={kernelName:uc,backendName:"webgl",kernelFunc:Jle};function eue(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${s.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${a.shape}`);let o=n.readSync(r.dataId),i=n.readSync(s.dataId),l=n.readSync(a.dataId),[u,c]=YI(o,r.shape,r.dtype,i,l,!0);return n.makeTensorInfo(c,r.dtype,u)}var tue={kernelName:up,backendName:"webgl",kernelFunc:eue};function nue(e){let{inputs:t,backend:n}=e,{data:r,indices:s,segmentIds:a}=t;if(r.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(s.shape.length!==1)throw new Error(`Indices should be a vector but received shape
|
|
${s.shape}`);if(a.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape
|
|
${a.shape}`);let o=n.readSync(r.dataId),i=n.readSync(s.dataId),l=n.readSync(a.dataId),[u,c]=YI(o,r.shape,r.dtype,i,l);return n.makeTensorInfo(c,r.dtype,u)}var rue={kernelName:cp,backendName:"webgl",kernelFunc:nue};function sue(e){let{inputs:t,backend:n,attrs:r}=e,{sparseIndices:s,sparseValues:a,defaultValue:o}=t,{outputShape:i}=r,{sliceRank:l,numUpdates:u,strides:c,outputSize:p}=C.calculateShapes(a,s,i),d=!1,h=new E8(u,l,s.shape.length,a.shape.length,c,[p,1],d),f=n.runWebGLProgram(h,[a,s,o],a.dtype),m=ve({inputs:{x:f},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(f),m}var aue={kernelName:dp,backendName:"webgl",kernelFunc:sue};function oue(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{numOrSizeSplits:a,axis:o}=r,i=w.parseAxisParam(o,s.shape)[0],l=C.prepareSplitSize(s,a,i),u=s.shape.length,c=new Array(u).fill(0),p=s.shape.slice();return l.map(d=>{let h=[...p];h[i]=d;let f=Rc({inputs:{x:s},backend:n,attrs:{begin:c,size:h}});return c[i]+=d,f})}var iue={kernelName:vl,backendName:"webgl",kernelFunc:oue},n4="return sqrt(x);",lue=ot({opSnippet:n4,packedOpSnippet:n4,cpuKernelImpl:Zee}),uue={kernelName:Mo,backendName:"webgl",kernelFunc:lue},cue="return x * x;",due=ot({opSnippet:cue}),pue={kernelName:cc,backendName:"webgl",kernelFunc:due},r4="return (a - b) * (a - b);",hue=vn({opSnippet:r4,packedOpSnippet:r4}),fue={kernelName:Bo,backendName:"webgl",kernelFunc:hue};function mue({inputs:e,attrs:t,backend:n}){let{x:r}=e,s=Yr+`
|
|
return x > 0.0 ? 1.0 : float(${t.alpha});
|
|
`,a=new Zs(r.shape,s);return n.runWebGLProgram(a,[r],r.dtype)}var gue={kernelName:Go,backendName:"webgl",kernelFunc:mue},yue=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;let r=n.length,s=yt(n.length),a=yt(n.length),o="";if(r===1)o="coords * strides + begin";else{let i=0;o=n.map((l,u)=>(i++,n.length===1?`coords * strides[${u}] + begin[${u}]`:`coords[${i-1}] * strides[${u}] + begin[${u}]`)).join(",")}this.userCode=`
|
|
${s} begin = ${s}(${e});
|
|
${s} strides = ${s}(${t});
|
|
|
|
void main() {
|
|
${a} coords = getOutputCoords();
|
|
setOutput(getX(${o}));
|
|
}
|
|
`}};function Aue(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,end:o,strides:i,beginMask:l,endMask:u,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:d}=r,{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:x,end:A,strides:b}=Mt.sliceInfo(s.shape,a,o,i,l,u,c,p,d),v;if(m)v=ve({inputs:{x:s},backend:n,attrs:{shape:f}});else if(g||y){w.assert(s.shape.length>=1,()=>`Input must have rank at least 1, got: ${s.shape.length}`);let I=Mt.computeOutShape(x,A,b),E=Rc({inputs:{x:s},backend:n,attrs:{begin:x,size:I}});v=ve({inputs:{x:E},backend:n,attrs:{shape:f}}),n.disposeIntermediateTensorInfo(E)}else if(n.shouldExecuteOnCPU([s])){let E=n.readSync(s.dataId),R=We(s.shape,s.dtype,E),P=Yee(h,R,b,x);v=n.makeTensorInfo(f,s.dtype,P.values)}else{let E=new yue(x,b,h);v=n.runWebGLProgram(E,[s],s.dtype)}let S=ve({inputs:{x:v},backend:n,attrs:{shape:f}});return n.disposeIntermediateTensorInfo(v),S}var xue={kernelName:wl,backendName:"webgl",kernelFunc:Aue};function bue(e){let{inputs:t,backend:n,attrs:r}=e,{separator:s,nGramWidths:a,leftPad:o,rightPad:i,padWidth:l,preserveShortSequences:u}=r,{data:c,dataSplits:p}=t,d=n.readSync(c.dataId),h=n.readSync(p.dataId),[f,m]=Jee(d,h,s,a,o,i,l,u);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(p.shape,"int32",m)]}var vue={kernelName:pp,backendName:"webgl",kernelFunc:bue};function wue(e){let{inputs:t,backend:n,attrs:r}=e,{skipEmpty:s}=r,{input:a,delimiter:o}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(a.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${a.shape}`);if(o.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${o.shape}`);let i=n.readSync(a.dataId),l=n.readSync(o.dataId)[0],[u,c,p]=Qee(i,l,s),d=c.length;return[n.makeTensorInfo([d,2],"int32",u),n.makeTensorInfo([d],"string",c),n.makeTensorInfo([2],"int32",new Int32Array(p))]}var kue={kernelName:xm,backendName:"webgl",kernelFunc:wue};function Sue(e){let{inputs:t,backend:n,attrs:r}=e,{numBuckets:s}=r,{input:a}=t;if(a.dtype!=="string")throw new Error("Input must be of datatype string");if(s<=0)throw new Error("Number of buckets must be at least 1");let o=n.readSync(a.dataId),i=ete(o,s);return n.makeTensorInfo(a.shape,"int32",i)}var Iue={kernelName:bm,backendName:"webgl",kernelFunc:Sue},Cue="return tan(x);",Tue=ot({opSnippet:Cue}),Nue={kernelName:kl,backendName:"webgl",kernelFunc:Tue},Eue=`
|
|
float e2x = exp(-2.0 * abs(x));
|
|
return sign(x) * (1.0 - e2x) / (1.0 + e2x);
|
|
`,Rue=ot({opSnippet:Eue}),_ue={kernelName:Vo,backendName:"webgl",kernelFunc:Rue},$ue=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let a=0;a<n.length;a++)n[a]=e[a]*t[a];this.outputShape=n,this.rank=n.length;let r=yt(this.rank),s=Due(e);this.userCode=`
|
|
void main() {
|
|
${r} resRC = getOutputCoords();
|
|
setOutput(getA(${s}));
|
|
}
|
|
`}};function Due(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 n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u"],r=[];for(let s=0;s<e.length;s++)r.push(`imod(${n[s]}, ${e[s]})`);return r.join()}function R8(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reps:a}=r;if(s.dtype==="string"||s.shape.length>5){let l=n.readSync(s.dataId),u=s.dtype==="string"?l.map(d=>w.decodeString(d)):l,c=We(s.shape,s.dtype,u),p=nte(c,a);return n.makeTensorInfo(p.shape,p.dtype,p.values)}let o=new $ue(s.shape,a);return n.runWebGLProgram(o,[s],s.dtype)}var Pue={kernelName:na,backendName:"webgl",kernelFunc:R8},Fue=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));
|
|
}
|
|
}
|
|
`}},Oue=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 gi(e,t){t!==null&&e.disposeIntermediateTensorInfo(t)}function s4(e){let t=1;for(;t<e;)t*=2;return t}function Mue(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{k:a,sorted:o}=r,i=Y().getNumber("TOPK_LAST_DIM_CPU_HANDOFF_SIZE_THRESHOLD"),l=Y().getNumber("TOPK_K_CPU_HANDOFF_THRESHOLD"),u=s.shape,c=u[u.length-1];if(n.shouldExecuteOnCPU([s])||c<i||a>l){let P=n.readSync(s.dataId),[_,D]=rte(P,u,s.dtype,a,o);return[n.makeTensorInfo(_.shape,_.dtype,_.values),n.makeTensorInfo(D.shape,D.dtype,D.values)]}if(a===0)return u[u.length-1]=0,[n.makeTensorInfo(u,s.dtype,[]),n.makeTensorInfo(u,"int32",[])];if(c===1)return[s,Up({attrs:{shape:u,dtype:"int32",value:0},backend:n})];let p=n.texData.get(s.dataId),d=p!==null&&p.isPacked,h=d?n.unpackTensor(s):s,m=w.sizeFromShape(u)/c,g=ve({inputs:{x:h},attrs:{shape:[m,c]},backend:n});d&&gi(n,h);let y=s4(a),x=s4(c),A=null,b=()=>A===null?[g,g]:[g,A],v=(P,_,D)=>{let T=b(),F=new Fue(D),X=[[c],[A===null?1:0],[Number.NEGATIVE_INFINITY],[P],[_]],z=A;A=n.runWebGLProgram(F,T,"int32",X),gi(n,z)};for(let P=1;P<y;P*=2){let _=P*2;for(let D=P;D>=1;D/=2)v(_,D,[m,x])}for(let P=x;P>y;P/=2){let _=b(),D=new Oue([m,P/2]),F=[[c],[A===null?1:0],[y]],U=A;A=n.runWebGLProgram(D,_,"int32",F),gi(n,U);let X=y/2,z=X*2;for(let Z=X;Z>=1;Z/=2)v(z,Z,A.shape)}let S=A;A=Rc({inputs:{x:A},backend:n,attrs:{begin:0,size:[m,a]}}),gi(n,S);let I=v8({inputs:{x:g,indices:A},backend:n,attrs:{axis:1,batchDims:1}});gi(n,g);let E=u.slice(0,-1);E.push(a),S=A,A=ve({inputs:{x:A},attrs:{shape:E},backend:n}),gi(n,S);let R=I;return I=ve({inputs:{x:I},attrs:{shape:E},backend:n}),gi(n,R),[I,A]}var zue={kernelName:Sl,backendName:"webgl",kernelFunc:Mue},Lue=class{constructor(e,t,n,r,s,a){this.variableNames=["Image","Transforms"],this.outputShape=a;let o=n==="nearest"?1:2,i;switch(r){case"constant":i=1;break;case"reflect":i=2;break;case"wrap":i=3;break;case"nearest":i=4;break;default:i=1;break}this.userCode=`
|
|
float mapCoord(float outCoord, float len) {
|
|
float inCoord = outCoord;
|
|
if(${i} == 2) {
|
|
if (inCoord < 0.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz2 = 2.0 * len;
|
|
if (inCoord < sz2) {
|
|
inCoord = sz2 * float(int(float(-inCoord / sz2))) +
|
|
inCoord;
|
|
}
|
|
inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0;
|
|
}
|
|
} else if (inCoord > len - 1.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz2 = 2.0 * len;
|
|
inCoord -= sz2 * float(int(float(inCoord / sz2)));
|
|
if (inCoord >= len) {
|
|
inCoord = sz2 - inCoord - 1.0;
|
|
}
|
|
}
|
|
}
|
|
return clamp(inCoord, 0.0, len - 1.0);
|
|
} else if (${i} == 3) {
|
|
if (inCoord < 0.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz = len - 1.0;
|
|
inCoord += len * (float(int(float(-inCoord / sz))) + 1.0);
|
|
}
|
|
} else if (inCoord > len - 1.0) {
|
|
if (len <= 1.0) {
|
|
inCoord = 0.0;
|
|
} else {
|
|
float sz = len - 1.0;
|
|
inCoord -= len * float(int(float(inCoord / sz)));
|
|
}
|
|
}
|
|
return clamp(inCoord, 0.0, len - 1.0);
|
|
} else if (${i} == 4) {
|
|
return clamp(outCoord, 0.0, len - 1.0);
|
|
} else {
|
|
return outCoord;
|
|
}
|
|
}
|
|
|
|
float readWithFillValue(int batch, int coordY, int coordX,
|
|
int channel) {
|
|
float outputValue;
|
|
if (0 <= coordY && coordY < ${e} && 0 <= coordX && coordX < ${t}) {
|
|
outputValue = getImage(batch, coordY, coordX, channel);
|
|
} else {
|
|
outputValue = float(${s});
|
|
}
|
|
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(${s});
|
|
} else {
|
|
float inX = (a1 * xf + a2 * yf + a3) / projection;
|
|
float inY = (b1 * xf + b2 * yf + b3) / projection;
|
|
float mapX = mapCoord(inX, float(${t}));
|
|
float mapY = mapCoord(inY, float(${e}));
|
|
|
|
if (${o} == 1) {
|
|
int coordY = int(round(mapY));
|
|
int coordX = int(round(mapX));
|
|
outputValue = readWithFillValue(batch, coordY, coordX,
|
|
channel);
|
|
} else {
|
|
float yFloor = floor(mapY);
|
|
float xFloor = floor(mapX);
|
|
float yCeil = yFloor + 1.0;
|
|
float xCeil = xFloor + 1.0;
|
|
float valueYFloor = (xCeil - mapX) *
|
|
readWithFillValue(batch, int(yFloor), int(xFloor), channel) +
|
|
(mapX - xFloor) *
|
|
readWithFillValue(batch, int(yFloor), int(xCeil), channel);
|
|
float valueYCeil = (xCeil - mapX) *
|
|
readWithFillValue(batch, int(yCeil), int(xFloor), channel) +
|
|
(mapX - xFloor) *
|
|
readWithFillValue(batch, int(yCeil), int(xCeil), channel);
|
|
outputValue = (yCeil - mapY) * valueYFloor +
|
|
(mapY - yFloor) * valueYCeil;
|
|
}
|
|
}
|
|
setOutput(outputValue);
|
|
}
|
|
`}};function Bue(e){let{inputs:t,backend:n,attrs:r}=e,{image:s,transforms:a}=t,{interpolation:o,fillMode:i,fillValue:l,outputShape:u}=r,[c,p,d,h]=s.shape,[f,m]=u!=null?u:[p,d],g=[c,f,m,h],y=new Lue(p,d,o,i,l,g);return n.runWebGLProgram(y,[s,a],"float32")}var Wue={kernelName:Il,backendName:"webgl",kernelFunc:Bue};function Vue(e){let{inputs:t,attrs:n,backend:r}=e,{axis:s}=n,{x:a}=t;Sc(a,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let o=r.readSync(a.dataId),{outputValues:i,outputShape:l,indices:u}=ste(o,s,a.shape,a.dtype);return[r.makeTensorInfo(l,a.dtype,i),r.makeTensorInfo([u.length],"int32",u)]}var Uue={kernelName:vm,backendName:"webgl",kernelFunc:Vue};function Gue(e){let{inputs:t,backend:n,attrs:r}=e,{value:s}=t,{axis:a}=r;a<0&&(a+=s.shape.length);let o=s,i=o.shape.length,l=s.shape[a],u=new Array(i-1),c=0;for(let m=0;m<i;m++)m!==a&&(u[c++]=o.shape[m]);let p=[],d=new Array(i).fill(0),h=o.shape.slice();h[a]=1;let f=new Array(l);for(let m=0;m<f.length;m++){d[a]=m;let g=Rc({inputs:{x:o},backend:n,attrs:{begin:d,size:h}}),y=ve({inputs:{x:g},backend:n,attrs:{shape:u}});f[m]=y,p.push(g)}return p.forEach(m=>n.disposeIntermediateTensorInfo(m)),f}var Hue={kernelName:Cl,backendName:"webgl",kernelFunc:Gue},jue=class{constructor(e,t){this.variableNames=["x","segmentIds"];let n=e.windowSize,r=e.batchSize,s=e.inSize,a=e.numSegments,o=a*Math.ceil(s/n);this.outputShape=[r,o];let i="0.0",l="sumValue",u=Math.floor(n/4)*4,c=n%4,p=`
|
|
sumValue += dot(values, segFilter);
|
|
`,d="";s%n>0&&(d=`
|
|
if (inIdx < 0 || inIdx >= ${s}) {
|
|
return initializationValue;
|
|
}
|
|
`);let h="";s%n>0&&(h=`
|
|
if (inIdx < 0 || inIdx >= ${s}) {
|
|
return -1.0;
|
|
}
|
|
`),this.userCode=`
|
|
const float initializationValue = ${i};
|
|
|
|
float getValue(int batch, int inIdx) {
|
|
${d}
|
|
return getX(batch, inIdx);
|
|
}
|
|
|
|
float getSegmentIdAtIndex(int inIdx) {
|
|
${h}
|
|
return getSegmentIds(inIdx);
|
|
}
|
|
|
|
void main() {
|
|
ivec2 coords = getOutputCoords();
|
|
int batch = coords[0];
|
|
int outIdx = coords[1];
|
|
int inOffset = int(floor(float(outIdx) / float(
|
|
${a})) * float(${n}));
|
|
int currentSeg = int(mod(float(outIdx), float(${a})));
|
|
|
|
float sumValue = 0.0;
|
|
|
|
for (int i = 0; i < ${u}; i += 4) {
|
|
int inIdx = inOffset + i;
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
getValue(batch, inIdx + 3)
|
|
);
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0
|
|
);
|
|
|
|
${p}
|
|
}
|
|
|
|
int inIdx = inOffset + ${u};
|
|
if (${c===1}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
initializationValue,
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
int inIdxSeg = int(getSegmentIdAtIndex(inIdx));
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
0,
|
|
0,
|
|
0
|
|
);
|
|
|
|
${p}
|
|
} else if (${c===2}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
initializationValue,
|
|
initializationValue
|
|
);
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
|
|
0,
|
|
0
|
|
);
|
|
|
|
${p}
|
|
} else if (${c===3}) {
|
|
vec4 values = vec4(
|
|
getValue(batch, inIdx),
|
|
getValue(batch, inIdx + 1),
|
|
getValue(batch, inIdx + 2),
|
|
initializationValue
|
|
);
|
|
|
|
vec4 segFilter = vec4(
|
|
int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0,
|
|
int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0,
|
|
0
|
|
);
|
|
|
|
${p}
|
|
}
|
|
setOutput(${l});
|
|
}
|
|
`}};function que(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,segmentIds:a}=t,{numSegments:o}=r,i=s.shape.length,l=[],u=0,c=C.getAxesPermutation([u],i),p=s;c!=null&&(p=bn({inputs:{x:s},backend:n,attrs:{perm:c}}),l.push(p),u=C.getInnerMostAxes(1,i)[0]);let d=C.segment_util.computeOutShape(p.shape,u,o),h=w.sizeFromShape([p.shape[u]]),f=ve({inputs:{x:p},backend:n,attrs:{shape:[-1,h]}});l.push(f);let m=gp(s.dtype),g=(b,v,S,I,E)=>{let R=b.shape[0],P=b.shape[1],_=C.segment_util.segOpComputeOptimalWindowSize(P,E),D={windowSize:_,inSize:P,batchSize:R,numSegments:E},T=new jue(D,v),F=n.compileAndRun(T,[b,S],I);if(l.push(F),F.shape[1]===E)return F;let U=N8({backend:n,attrs:{start:0,stop:E,step:1,dtype:"float32"}}),X=R8({inputs:{x:U},backend:n,attrs:{reps:[P/_]}});return l.push(U),l.push(X),g(F,v,X,I,E)},y=g(f,"unsortedSegmentSum",a,m,o),x=ve({inputs:{x:y},backend:n,attrs:{shape:d}}),A=x;if(c!=null){l.push(x);let b=C.getUndoAxesPermutation(c);A=bn({inputs:{x:A},backend:n,attrs:{perm:b}})}return l.forEach(b=>n.disposeIntermediateTensorInfo(b)),A}var Xue={kernelName:hp,backendName:"webgl",kernelFunc:que},Kue=[Qte,tne,sne,ine,une,pne,fne,gne,bne,wne,Ine,Nne,_ne,Fne,zne,Bne,Vne,jne,Xne,Zne,ere,ire,ure,dre,yre,xre,kre,Pte,Cre,_re,Fre,Wre,Ure,Hre,qre,Kre,Jre,tse,sse,ose,lse,cse,hse,mse,xse,vse,Sse,Tse,Ese,Dse,Mse,Wse,Gse,qse,Xse,Zse,Jse,eae,nae,sae,lae,dae,fae,gae,xae,wae,Cae,Rae,Dte,$ae,Ere,Fae,zae,Wae,Ote,Hae,Kae,Yae,toe,soe,loe,doe,moe,xoe,woe,Soe,Noe,Roe,$oe,Ooe,zoe,Boe,Voe,Goe,Xoe,Joe,nie,cie,Wte,fie,yie,bie,kie,hre,Cie,Nie,Rie,Die,Mie,zte,Lie,Bie,fre,oie,Uie,qie,Yie,Ute,tle,sle,lle,dle,mle,yle,ble,kle,Ile,Nle,_le,Fle,zle,Wle,Gle,are,lie,qle,Kle,Yle,Qle,tue,rue,aue,iue,uue,pue,fue,gue,xue,vue,kue,Iue,iie,Zte,Nue,_ue,Pue,zue,Wue,Yte,Uue,Hue,Xue,Tie];for(let e of Kue)qr(e);var Ms=Y();Ms.registerFlag("WEBGPU_DEFERRED_SUBMIT_BATCH_SIZE",()=>15);Ms.registerFlag("WEBGPU_CPU_FORWARD",()=>!0);Ms.registerFlag("WEBGPU_MATMUL_WORK_PER_THREAD",()=>4);Ms.registerFlag("WEBGPU_USE_NAIVE_CONV2D",()=>!1);Ms.registerFlag("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE",()=>!1);Ms.registerFlag("WEBGPU_CONV_SEPARATE_IM2COL_SHADER",()=>!1);Ms.registerFlag("WEBGPU_USE_LOW_POWER_GPU",()=>!1);Ms.registerFlag("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD",()=>1e3);Ms.registerFlag("WEBGPU_USE_PROFILE_TOOL",()=>!1);Ms.registerFlag("WEBGPU_USE_IMPORT",()=>!1);var Zue="return a + b;",Yue="return areal * breal - aimag * bimag;",Jue="return areal * bimag + aimag * breal;",Que="return a / b;",ece="return a * b;",tce="return (a - b) * (a - b);",nce="return a - b;",rce="return f32(a == b);",sce="return vec4<f32>(a == b);",ace="return f32(a > b);",oce="return vec4<f32>(a > b);",ice="return f32(a >= b);",lce="return vec4<f32>(a >= b);",uce="return f32(a < b);",cce="return vec4<f32>(a < b);",dce="return f32(a <= b);",pce="return vec4<f32>(a <= b);",hce="return f32(f32(a) >= 1.0 && f32(b) >= 1.0);",fce=`return (vec4<f32>(a >= vec4<f32>(1.0)) *
|
|
vec4<f32>(b >= vec4<f32>(1.0)));`,mce=`
|
|
if (isnan(a)) { return a; }
|
|
if (isnan(b)) { return b; }
|
|
`,_8=`
|
|
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;
|
|
}
|
|
`,gce=`
|
|
let s = sign(a) * sign(b);
|
|
let ia = i32(round(a));
|
|
let ib = i32(round(b));
|
|
return f32(idiv(ia, ib, s));
|
|
`,yce=`
|
|
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);
|
|
`,Ace="return f32(a != b);",xce="return vec4<f32>(a != b);",bce=`
|
|
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);
|
|
`,vce=`
|
|
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;
|
|
${_8}
|
|
return resultTemp;
|
|
`,wce="if (a < 0.0) { return b * a; } return a;",kce=`
|
|
let aLessThanZero = vec4<f32>(a < vec4<f32>(0.0));
|
|
return (aLessThanZero * (b * a)) + ((vec4<f32>(1.0) - aLessThanZero) * a);
|
|
`;function a4(e,t){let n=t?_8:mce;return t?`
|
|
var resultTemp = vec4<f32>(${e}(a, b));
|
|
let isNaN = isnanVec4(a) | isnanVec4(b);
|
|
`+n+`
|
|
return resultTemp;
|
|
`:n+`
|
|
return ${e}(a, b);
|
|
`}function Gp(e,t){switch(e){case 0:return ece;case 1:return Zue;case 2:return nce;case 3:return Que;case 4:return t?sce:rce;case 5:return t?oce:ace;case 6:return t?lce:ice;case 7:return t?cce:uce;case 8:return t?pce:dce;case 9:return t?fce:hce;case 10:return t?xce:Ace;case 11:return tce;case 12:return t?yce:gce;case 14:return t?kce:wce;case 15:return a4("max",t);case 16:return a4("min",t);case 13:return t?vce:bce;case 17:return Yue;case 18:return Jue;default:throw new Error(`BinaryType ${e} is not implemented!`)}}var Sce="return abs(a);",Ice="return ceil(a);",Cce="return cos(a);",Tce=`
|
|
let e2x = exp(-a);
|
|
return (e2x + 1.0 / e2x) / 2.0;
|
|
`,Nce="return exp(a) - 1.0;",Ece="if (a >= 0.0) { return a; } return (exp(a) - 1.0);",Rce=`
|
|
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;
|
|
`,_ce="return exp(a);",$ce="return floor(a);",Dce="return a;",Pce=`if (a < 0.0) { return 1.0/0.0; }
|
|
return log(a);`,Fce="return f32(!(a >= 1.0));",Oce="return -a;",Mce="if (a < 0.0) { return uniforms.alpha * a; } return a;",zce=`
|
|
let aLessThanZero = vec4<f32>(a < vec4<f32>(0.0));
|
|
return (aLessThanZero * (uniforms.alpha * a)) + ((vec4<f32>(1.0) - aLessThanZero) * a);
|
|
`,Lce="if(a < 0.0) { return 0.0; } return a;",Bce="return clamp(a, 0.0, 6.0);",Wce="return clamp(a, vec4<f32>(0.0, 0.0, 0.0, 0.0), vec4<f32>(6.0, 6.0, 6.0, 6.0));",Vce=`
|
|
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;
|
|
`,Uce="return 1.0/sqrt(a);",Gce="return 1.0 / (1.0 + exp(-1.0 * a));",Hce="return sin(a);",jce=`
|
|
let e2x = exp(a);
|
|
return (e2x - 1.0 / e2x) / 2.0;
|
|
`,qce="return sqrt(a);",Xce="return a * a;",Kce=`
|
|
let e2x = exp(-2.0 * abs(a));
|
|
return sign(a) * (1.0 - e2x) / (1.0 + e2x);
|
|
`,Zce="return f32(i32((a)));";function xi(e,t){switch(e){case 0:return Sce;case 2:return Cce;case 3:return Tce;case 1:return Ice;case 4:return t?Rce:Ece;case 5:return _ce;case 6:return Nce;case 7:return $ce;case 8:return Dce;case 9:return Pce;case 10:return Fce;case 11:return Oce;case 14:return t?zce:Mce;case 12:return t?Vce:Lce;case 13:return t?Wce:Bce;case 15:return Uce;case 18:return Gce;case 16:return Hce;case 17:return jce;case 19:return qce;case 20:return Xce;case 21:return Kce;case 22:return Zce;default:throw new Error(`BinaryType ${e} is not implemented!`)}}function la(e,t=!1){if(e===null)return null;if(e==="linear")return xi(8);if(e==="relu")return xi(12,t);if(e==="elu")return xi(4,t);if(e==="relu6")return xi(13,t);if(e==="prelu")return Gp(14,t);if(e==="sigmoid")return xi(18,t);if(e==="leakyrelu")return xi(14,t);throw new Error(`Activation ${e} has not been implemented for the WebGPU backend.`)}function Yce(e,t){if(Math.max(...e)>3)throw new Error("Cannot symbolically compute strides for rank > 4 tensor.");let n=e.length,r=e.map(a=>`${t}[${a}]`),s=new Array(n-1);s[n-2]=r[n-1];for(let a=n-3;a>=0;--a)s[a]=`(${s[a+1]} * ${r[a+1]})`;return s}function yn(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 ff(e,t){return e==="float32"?t?"vec4<f32>":"f32":e==="int32"||e==="bool"?t?"vec4<i32>":"i32":e}function v3(){return`
|
|
@stage(compute) @workgroup_size(workGroupSizeX, workGroupSizeY, workGroupSizeZ)
|
|
`}function Ko(){return`
|
|
${v3()}
|
|
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 Qe(){return`
|
|
${Ko()}
|
|
let index = getGlobalIndex();
|
|
`}function Jce(e,t,n,r=!1){let s=[];if(s.push(`
|
|
let workGroupSizeX = ${n.workGroupSize[0]}u;
|
|
let workGroupSizeY = ${n.workGroupSize[1]}u;
|
|
let workGroupSizeZ = ${n.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);
|
|
}
|
|
`),r===!0)return s.push(`
|
|
struct Uniform {
|
|
size : i32,
|
|
numChannels : i32,
|
|
outShapeStrides : vec2<i32>,
|
|
dispatchSize : vec3<u32>,
|
|
};
|
|
|
|
@group(0) @binding(0) var<storage, write> result: array<${ff(t.dtype,n.isVec4)}>;
|
|
@group(0) @binding(2) var<uniform> uniforms: Uniform;
|
|
`),[o4,s.join(`
|
|
`),i4(t.shape),n.getUserCode()].join(`
|
|
`);let a="struct Uniforms { NAN : f32, ";n.variableNames.forEach((p,d)=>{a+=`${p.charAt(0).toLowerCase()+p.slice(1)}Shape : ${yn(e[d].shape.length)}, `}),a+=`outShape : ${yn(t.shape.length)}, `;let o=t.shape.length-1;a+=`
|
|
outShapeStrides: ${yn(o)}, `,n.size&&(a+="size : i32, "),n.uniforms&&(a+=n.uniforms),a+="};",s.push(a),n.atomic?s.push(`
|
|
@group(0) @binding(0) var<storage, read_write> result: array<atomic<i32>>;
|
|
`):s.push(`
|
|
@group(0) @binding(0) var<storage, write> result: array<${ff(t.dtype,n.isVec4)}>;
|
|
`),n.variableNames.forEach((p,d)=>{s.push(`
|
|
@group(0) @binding(${1+d}) var<storage, read> ${p}: array<${ff(e[d].dtype,n.isVec4)}>;
|
|
`)}),a!==""&&s.push(`
|
|
@group(0) @binding(${1+n.variableNames.length}) var<uniform> uniforms: Uniforms;
|
|
`);let[i,l]=sde(t.shape,n.dispatchLayout),u=[o4,s.join(`
|
|
`),i4(t.shape),i,Qce(t.shape.length)];if(n.atomic||u.push(ede(t.shape,t.dtype,n.isVec4)),l===t.shape.length){let p=e.map(d=>tde(d,t.shape,n.isVec4,n.dispatchLayout.x.length===t.shape.length)).join(`
|
|
`);u.push(p)}return u.push(n.getUserCode()),u.join(`
|
|
`)}var o4=`
|
|
// 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 Qce(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 ede(e,t,n){let r=e.length,s=ff(t,n),a;if(n?a=`fn setOutputAtIndex(flatIndex : i32, value : vec4<f32>) {
|
|
result[flatIndex] = ${s}(value);
|
|
}
|
|
fn setOutputAtIndexI32(flatIndex : i32, value : vec4<i32>) {
|
|
result[flatIndex] = ${s}(value);
|
|
}`:a=`fn setOutputAtIndex(flatIndex : i32, value : f32) {
|
|
result[flatIndex] = ${s}(value);
|
|
}
|
|
fn setOutputAtIndexI32(flatIndex : i32, value : i32) {
|
|
result[flatIndex] = ${s}(value);
|
|
}`,r>=2){let o=["d0","d1","d2","d3"].slice(0,r),i=yn(r);n?a+=`
|
|
fn setOutputAtCoords(${o.map(l=>`${l} : i32`).join(", ")}, value : vec4<f32>) {
|
|
let flatIndex = getOutputIndexFromCoords(${i}(${o.join(", ")}));
|
|
setOutputAtIndex(flatIndex / 4, value);
|
|
}
|
|
fn setOutputAtCoordsI32(${o.map(l=>`${l} : i32`).join(", ")}, value : vec4<i32>) {
|
|
let flatIndex = getOutputIndexFromCoords(${i}(${o.join(", ")}));
|
|
setOutputAtIndexI32(flatIndex / 4, value);
|
|
}
|
|
`:a+=`
|
|
fn setOutputAtCoords(${o.map(l=>`${l} : i32`).join(", ")}, value : f32) {
|
|
let flatIndex = getOutputIndexFromCoords(${i}(${o.join(", ")}));
|
|
setOutputAtIndex(flatIndex, value);
|
|
}
|
|
fn setOutputAtCoordsI32(${o.map(l=>`${l} : i32`).join(", ")}, value : i32) {
|
|
let flatIndex = getOutputIndexFromCoords(${i}(${o.join(", ")}));
|
|
setOutputAtIndexI32(flatIndex, value);
|
|
}
|
|
`}return a}function tde(e,t,n,r){let s=nde(e,n);return e.shape.length<=t.length&&(s+=rde(e,t,n,r)),s}function nde(e,t){let n=e.name,r=e.shape.length,s=yn(r),a="get"+n.charAt(0).toUpperCase()+n.slice(1),o=["d0","d1","d2","d3"].slice(0,r),i=o.map(c=>`${c} : i32`).join(", ");if(r<1)return t?`
|
|
fn ${a}() -> vec4<f32> {
|
|
return vec4<f32>(${n}[0]);
|
|
}
|
|
`:`
|
|
fn ${a}() ->f32 {
|
|
return f32(${n}[0]);
|
|
}
|
|
`;let l=`uniforms.${n.charAt(0).toLowerCase()+n.slice(1)}Shape`,u=`${r}D`;return r===0&&(u="1D"),t?`
|
|
fn ${a}(${i}) -> vec4<f32> {
|
|
return vec4<f32>(${n}[getIndexFromCoords${u}(${s}(${o.join(",")}),
|
|
${l}) / 4]);
|
|
}
|
|
`:`
|
|
fn ${a}(${i}) -> f32 {
|
|
return f32(${n}[getIndexFromCoords${u}(${s}(${o.join(",")}),
|
|
${l})]);
|
|
}
|
|
`}function rde(e,t,n,r){let s=e.name,a=s.charAt(0).toUpperCase()+s.slice(1),o="get"+a+"ByOutput",i=e.shape.length,l=t.length,u=yn(l);if(w.arraysEqual(e.shape,t)&&r)return n?`
|
|
fn ${o}Index(globalIndex : i32) -> vec4<f32> {
|
|
return vec4<f32>(${s}[globalIndex]);
|
|
}
|
|
|
|
fn ${o}Coords(coords : ${u}) -> vec4<f32> {
|
|
return vec4<f32>(${s}[${l>1?"getOutputIndexFromCoords(coords)":"coords"} / 4]);
|
|
}
|
|
`:`
|
|
fn ${o}Index(globalIndex : i32) -> f32 {
|
|
return f32(${s}[globalIndex]);
|
|
}
|
|
|
|
fn ${o}Coords(coords : ${u}) -> f32 {
|
|
return f32(${s}[${l>1?"getOutputIndexFromCoords(coords)":"coords"}]);
|
|
}
|
|
`;let c=C.getBroadcastDims(e.shape,t),p=l-i,d="";if(i===0)return n?`
|
|
fn ${o}Index(globalIndex : i32) -> vec4<f32> {
|
|
return get${a}();
|
|
}
|
|
|
|
fn ${o}Coords(coords : ${u}) -> vec4<f32> {
|
|
return get${a}();
|
|
}
|
|
`:`
|
|
fn ${o}Index(globalIndex : i32) -> f32{
|
|
return get${a}();
|
|
}
|
|
|
|
fn ${o}Coords(coords : ${u}) -> f32{
|
|
return get${a}();
|
|
}
|
|
`;l<2&&c.length>=1?d="coords = 0;":d=c.map(g=>`coords[${g+p}] = 0;`).join(`
|
|
`);let h="";if(l<2&&i>0)h="coords";else if(l>1){let g=yn(i),y=e.shape.map((x,A)=>`coords[${A+p}]`).join(", ");h=`${g}(${y})`}else h="coords";let f=`uniforms.${s.charAt(0).toLowerCase()+s.slice(1)}Shape`,m=`${i}D`;return n?`
|
|
fn ${o}Index(globalIndex : i32) -> vec4<f32> {
|
|
var coords = getCoordsFromIndex(globalIndex);
|
|
${d}
|
|
return ${s}[getIndexFromCoords${m}(${h}, ${f}) / 4];
|
|
}
|
|
|
|
fn ${o}Coords(coordsIn : ${u}) -> vec4<f32> {
|
|
var coords = coordsIn;
|
|
${d}
|
|
return ${s}[getIndexFromCoords${m}(${h}, ${f}) / 4];
|
|
}
|
|
`:`
|
|
fn ${o}Index(globalIndex : i32) -> f32 {
|
|
var coords = getCoordsFromIndex(globalIndex);
|
|
${d}
|
|
return f32(${s}[getIndexFromCoords${m}(${h}, ${f})]);
|
|
}
|
|
|
|
fn ${o}Coords(coordsIn : ${u}) -> f32 {
|
|
var coords = coordsIn;
|
|
${d}
|
|
return f32(${s}[getIndexFromCoords${m}(${h}, ${f})]);
|
|
}
|
|
`}function sde(e,t){let{x:n,y:r=[],z:s=[]}=t,a=e.length;if(n.length===a)return[`fn getOutputCoords() -> ${yn(a)}{
|
|
let globalIndex = getGlobalIndex();
|
|
return getCoordsFromIndex(globalIndex);
|
|
}
|
|
`,a];let o="",i=[n,r,s],l=0;for(let d=0;d<i.length;d++){let h=i[d];if(h.length!==0)if(l+=h.length,h.length===1)o+=`let d${h[0]} = i32(globalId[${d}]);`;else{let f=Yce(h,"uniforms.outShape");o+=`var index${d} = i32(globalId[${d}]);`;for(let m=0;m<f.length;m++)o+=`let d${h[m]} = index${d} / ${f[m]};`,m===f.length-1?o+=`let d${h[m+1]} = index${d} - d${h[m]} * ${f[m]};`:o+=`index${d} = index${d} - d${h[m]} * ${f[m]};`}}let u=[];for(let d=0;d<l;d++)u.push(`d${d}`);let c=yn(l),p=`fn getOutputCoords() -> ${c} {
|
|
${o}
|
|
`;return u.length===0?p+=`return ${c}(0); }`:p+=`return ${c}(${u.join(",")}); }`,[p,l]}function i4(e){let t=e.length;if(t<=1)return"fn getCoordsFromIndex(index : i32) -> i32 { return index; }";let n=w.computeStrides(e),r=yn(t),s=[];for(let o=0;o<t;o++)s.push(`d${o}`);if(n.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 a="var index2 = index;"+n.map((o,i)=>{let l=`let ${s[i]} = index2 / uniforms.outShapeStrides[${i}]`,u=i===n.length-1?`let ${s[i+1]} = index2 - ${s[i]} * uniforms.outShapeStrides[${i}]`:`index2 = index2 - ${s[i]} * uniforms.outShapeStrides[${i}]`;return`${l}; ${u};`}).join("");return`
|
|
fn getCoordsFromIndex(index : i32) -> ${r} {
|
|
${a}
|
|
return ${r}(${s.join(",")});
|
|
}
|
|
`}var $8={};Le($8,{ArrayBufferToTypedArray:()=>P8,GPUBytesPerElement:()=>ry,computeDispatch:()=>Oe,computeWorkGroupSizeForConv2d:()=>w3,computeWorkGroupSizeForMatMul:()=>D8,computeWorkPerThreadForConv2d:()=>k3,flatDispatchLayout:()=>Xe,isWebGPUSupported:()=>S3,tilesFitEvenlyIntoShape:()=>Js});var Ri=e=>{let t=1;for(let n=0;n<e.length;n++)t*=e[n];return t};function Js(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((n,r)=>n%e[r]===0)}function Oe(e,t,n=[1,1,1],r=[1,1,1]){let[s,a,o]=[Math.ceil(Ri(e.x.map(i=>t[i]))/(n[0]*r[0])),e.y?Math.ceil(Ri(e.y.map(i=>t[i]))/(n[1]*r[1])):1,e.z?Math.ceil(Ri(e.z.map(i=>t[i]))/(n[2]*r[2])):1];return[s,a,o]}function w3(e,t){let n=Ri(e.x.map(s=>t[s])),r=Ri(e.y.map(s=>t[s]));return n<=4?[4,16,1]:r<=4?[16,4,1]:[16,16,1]}function D8(e,t,n){return e===1?[32,1,1]:n===1?[1,32,1]:[8,8,1]}function k3(e,t){let n=Ri(e.x.map(s=>t[s])),r=Ri(e.y.map(s=>t[s]));return n<=4?[1,2,1]:r<=4?[2,1,1]:[2,2,1]}function Xe(e){return{x:e.map((t,n)=>n)}}function ry(e){if(e==="float32"||e==="int32"||e==="bool"||e==="string")return 4;if(e==="complex64")return 8;throw new Error(`Unknown dtype ${e}`)}function P8(e,t){if(t==="float32")return new Float32Array(e);if(t==="int32")return new Int32Array(e);if(t==="bool"||t==="string")return Uint8Array.from(new Int32Array(e));throw new Error(`Unknown dtype ${t}`)}function S3(){return(typeof window!="undefined"||typeof WorkerGlobalScope!="undefined")&&!!navigator.gpu}function F8(e,t,n,r){return w.assert(r%4===0&&e[0]===4,()=>"tileInner must be divisible by 4. And ColPerThread must be 4"),`
|
|
var<workgroup> mm_Asub : array<array<vec4<f32>, ${r/e[0]}>, ${t}>;
|
|
var<workgroup> mm_Bsub : array<array<vec4<f32>, ${n/e[0]}>, ${r}>;
|
|
|
|
let RowPerThread = ${e[1]};
|
|
let ColPerThread = ${e[0]};
|
|
let TileInner = ${r};
|
|
|
|
${Ko()}
|
|
|
|
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 ade=class{constructor(e,t,n,r=null,s=null,a=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=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize,this.elementsPerThread);let o=r!=null,i=a!=null;o&&this.variableNames.push("bias"),i&&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=o,this.activation=s,this.hasPreluActivationWeights=i,[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],n=[this.outputShape[0],e,t],r=[this.tileAOuter,this.tileInner],s=[this.tileInner,this.tileBOuter];return[Js(r,this.aShape.slice(1)),Js(s,n.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)`,n="",r="";if(this.activation){let o=la(this.activation,this.isVec4);this.hasPreluActivationWeights?n=`fn activation(a : vec4<f32>, outCoord : vec3<i32>) -> vec4<f32> {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${o}
|
|
}`:n=`
|
|
fn activation(a : vec4<f32>, outCoord : vec3<i32>) -> vec4<f32> {
|
|
${o}
|
|
}`,r="value = activation(value, outCoord);"}let s=this.addBias?"value = value + getBiasByOutputCoords(outCoord);":"";return`
|
|
${n}
|
|
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);
|
|
${s}
|
|
${r}
|
|
setOutputAtCoords(outCoord[0], outCoord[1], outCoord[2], value);
|
|
}
|
|
}
|
|
${F8(this.elementsPerThread,this.tileAOuter,this.tileBOuter,this.tileInner)}
|
|
`}};function I3(e,t){let n=t[1]*e[1],r=t[0]*e[0],s=n>r?n:r;return`
|
|
var<workgroup> mm_Asub : array<array<f32, ${s}>, ${n}>;
|
|
var<workgroup> mm_Bsub : array<array<f32, ${r}>, ${s}>;
|
|
${Ko()}
|
|
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) / ${s} + 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 = ${s} / ${t[0]};
|
|
let tileColA = i32(localId.x) * ColPerThreadA;
|
|
let RowPerThreadB = ${s} / ${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 * ${s} + 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 * ${s} + inputRow,
|
|
globalCol + innerCol, globalId);
|
|
}
|
|
}
|
|
|
|
workgroupBarrier();
|
|
|
|
// Compute acc values for a single thread.
|
|
for (var k = 0; k < ${s}; 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 ode(e){return`
|
|
let TileSize = ${e[0]*4};
|
|
var<workgroup> mm_Asub : array<vec4<f32>, ${e[0]}>;
|
|
|
|
${Ko()}
|
|
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 O8=class{constructor(e,t,n,r=!1,s=!1,a=null,o=null,i=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=r?e[1]:e[2];this.workGroupSize=D8(t[1],l,t[2]),(t[1]===1||t[2]===1)&&(n=1),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize,[n,n,1]),w.arraysEqual(this.dispatch,[1,1,1])&&(n=1,this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize,[n,n,1]));let u=a!=null,c=i!=null;u&&this.variableNames.push("bias"),c&&this.variableNames.push("preluActivationWeights"),this.workPerThread=n,this.aShape=e,this.transposeA=r,this.transposeB=s,this.addBias=u,this.activation=o,this.hasPreluActivationWeights=c;let p=this.outputShape[2],d=this.transposeB?[this.outputShape[0],p,l]:[this.outputShape[0],l,p];[this.fitA,this.fitB]=this.getShapeFit(d),this.shaderKey=`matMulPacked_${this.workPerThread}_${r}_${s}_${this.activation}_${this.fitA}_${this.fitB}_${this.outputShape[1]>1}`}getShapeFit(e){let t=this.workGroupSize[1]*this.workPerThread,n=this.workGroupSize[0]*this.workPerThread,r=t>n?t:n;this.outputShape[1]===1&&(r*=4),w.assert(r%this.workGroupSize[0]===0&&r%this.workGroupSize[1]===0,()=>"tileInner must be multiple of workgroupsize.x and workgroupsize.y");let s=[t,r],a=[r,n];return[Js(s,this.aShape.slice(1)),Js(a,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 n="",r="";if(this.activation){let o=la(this.activation,!1);this.hasPreluActivationWeights?n=`fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${o}
|
|
}`:n=`
|
|
fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
|
|
${o}
|
|
}
|
|
`,r="value = activation(value, outCoord);"}let s=this.addBias?"value = value + getBiasByOutputCoords(outCoord);":"";return`
|
|
${n}
|
|
|
|
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);
|
|
${s}
|
|
${r}
|
|
setOutputAtCoords(batch, row, col, value);
|
|
}
|
|
${this.outputShape[1]>1?I3([this.workPerThread,this.workPerThread,1],this.workGroupSize):ode(this.workGroupSize)}
|
|
`}};function ide(){return`
|
|
var<workgroup> sumValues : array<f32, workGroupSizeX>;
|
|
${Ko()}
|
|
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 lde=class{constructor(e,t=!1,n=!1,r=null,s=null,a=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=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize);let o=r!=null,i=a!=null;o&&this.variableNames.push("bias"),i&&this.variableNames.push("preluActivationWeights"),this.transposeA=t,this.transposeB=n,this.addBias=o,this.activation=s,this.hasPreluActivationWeights=i,this.shaderKey=`matMulReduce_${this.activation}_${t}_${n}`}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 n="",r="";if(this.activation){let o=la(this.activation,!1);this.hasPreluActivationWeights?n=`fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${o}
|
|
}`:n=`
|
|
fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
|
|
${o}
|
|
}
|
|
`,r="value = activation(value, outCoord);"}let s=this.addBias?"value = value + getBiasByOutputCoords(outCoord);":"";return`
|
|
${n}
|
|
|
|
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);
|
|
${s}
|
|
${r}
|
|
setOutputAtCoords(batch, row, col, value);
|
|
}
|
|
${ide()}
|
|
`}};function ude(e){let t=e[1]/2,n=e[0],r=t>n?t:n;return`
|
|
var<workgroup> mm_Asub1 : array<array<f32, ${r}>, ${t}>;
|
|
var<workgroup> mm_Bsub1 : array<array<f32, ${n}>, ${r}>;
|
|
var<workgroup> mm_Asub2 : array<array<f32, ${r}>, ${t}>;
|
|
var<workgroup> mm_Bsub2 : array<array<f32, ${n}>, ${r}>;
|
|
|
|
// 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.
|
|
${Ko()}
|
|
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) / ${r} + 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 + ${r};
|
|
mm_Bsub1[tileRow][tileCol] = mm_readB(globalRowB, globalCol, globalId);
|
|
globalRowB = globalRowB + ${r};
|
|
}
|
|
} 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 + ${r};
|
|
mm_Bsub1[tileRow][tileCol] = mm_readB(globalRowB, globalCol, globalId);
|
|
globalRowB = globalRowB + ${r};
|
|
} else {
|
|
// Compute acc values for a single thread.
|
|
for (var k = 0; k < ${r}; 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 + ${r};
|
|
mm_Bsub2[tileRow][tileCol] = mm_readB(globalRowB, globalCol, globalId);
|
|
globalRowB = globalRowB + ${r};
|
|
} else {
|
|
// Compute acc values for a single thread.
|
|
for (var k = 0; k < ${r}; 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 cde=class{constructor(e,t,n,r=null,s=null,a=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=n,this.dispatchLayout={x:[2],y:[1],z:[0]},this.dispatch=[Math.ceil(n[2]/this.workGroupSize[0]),Math.ceil(n[1]*2/this.workGroupSize[1]),n[0]];let o=r!=null;o&&this.variableNames.push("bias");let i=a!=null;i&&this.variableNames.push("preluActivationWeights"),this.addBias=o,this.activation=s,this.hasPreluActivationWeights=i,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;`,n="",r="";if(this.activation){let o=la(this.activation,!1);this.hasPreluActivationWeights?n=`fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${o}
|
|
}`:n=`fn activation(a : f32, outCoord : vec3<i32>) -> f32 {
|
|
${o}
|
|
}`,r="value = activation(value, outCoord);"}let s=this.addBias?"value = value + getBiasByOutputCoords(outCoord);":"";return`
|
|
${n}
|
|
|
|
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;
|
|
${s}
|
|
${r}
|
|
setOutputAtCoords(batch, row, col, value);
|
|
}
|
|
}
|
|
${ude(this.workGroupSize)}
|
|
`}};function qe(e){let{inputs:t,attrs:n}=e,{x:r}=t,{shape:s}=n,a=w.sizeFromShape(r.shape),o=w.inferFromImplicitShape(s,a),i=w.sizeFromShape(o);return w.assert(a===i,()=>`The new shape (${o}) has ${i} elements and the old shape (${r.shape}) has ${a} elements. The new shape and old shape must have the same number of elements.`),e.backend.incRef(r.dataId),{dataId:r.dataId,shape:o,dtype:r.dtype}}var dde={kernelName:hl,backendName:"webgpu",kernelFunc:qe};function C3({a:e,b:t,transposeA:n,transposeB:r,backend:s,bias:a=null,preluActivationWeights:o=null,leakyreluAlpha:i=0,activation:l=null}){let u=e.shape.length,c=t.shape.length,p=n?e.shape[u-2]:e.shape[u-1],d=r?t.shape[c-1]:t.shape[c-2],h=n?e.shape[u-1]:e.shape[u-2],f=r?t.shape[c-2]:t.shape[c-1],m=e.shape.slice(0,-2),g=t.shape.slice(0,-2),y=w.sizeFromShape(m),x=w.sizeFromShape(g),b=El.assertAndGetBroadcastShape(e.shape.slice(0,-2),t.shape.slice(0,-2)).concat([h,f]);w.assert(p===d,()=>`Error in matMul: inner shapes (${p}) and (${d}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${r} must match.`);let v=n?[y,p,h]:[y,h,p],S=r?[x,f,d]:[x,d,f],I=qe({inputs:{x:e},backend:s,attrs:{shape:v}}),E=qe({inputs:{x:t},backend:s,attrs:{shape:S}}),R=[I,E],P=Math.max(y,x),_=p%4===0&&f%4===0&&!n&&!r&&f>=32,D;h*f<=32?D=new lde([P,h,f],n,r,a,l,o):!n&&!r&&(h<=16&&(f<=512||d>=2*f)||f<=16&&(h<=512||p>=2*h))?D=new cde(v,S,[P,h,f],a,l,o):_?D=new ade(v,[P,h,f],Y().get("WEBGPU_MATMUL_WORK_PER_THREAD"),a,l,o):D=new O8(v,[P,h,f],Y().get("WEBGPU_MATMUL_WORK_PER_THREAD"),n,r,a,l,o);let T=[I,E];a&&T.push(a),o&&T.push(o);let F=[{type:"int32",data:[h]},{type:"int32",data:[f]},{type:"int32",data:[p]}];l==="leakyrelu"&&(F.push({type:"float32",data:[i]}),D.uniforms+=" alpha : f32,");let U=s.runWebGPUProgram(D,T,e.dtype,F),X=qe({inputs:{x:U},backend:s,attrs:{shape:b}});R.push(U);for(let z of R)s.disposeData(z.dataId);return X}function pde(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a,bias:o,preluActivationWeights:i}=t,{transposeA:l,transposeB:u,activation:c,leakyreluAlpha:p}=r;return C3({a:s,b:a,transposeA:l,transposeB:u,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:p,activation:c})}var hde={kernelName:Pa,backendName:"webgpu",kernelFunc:pde},l4=class{constructor(e,t,n){this.variableNames=["AReal","AImag","BReal","BImag"],this.workGroupSize=[128,1,1],this.size=!0,this.outputShape=C.assertAndGetBroadcastShape(t,n),this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(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 {
|
|
${Gp(this.op,!1)}
|
|
}
|
|
|
|
${Qe()}
|
|
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));
|
|
}
|
|
}
|
|
`}},fde=class{constructor(e,t,n,r){this.variableNames=["A","B"],this.size=!0;let s=256;this.workGroupSize=[s,1,1],this.outputShape=C.assertAndGetBroadcastShape(t,n),this.dispatchLayout=Xe(this.outputShape),this.lastDimensionSize=r?n[0]:t[0],this.lastDimensionSize<256?this.workPerThread=1:this.lastDimensionSize<512?this.workPerThread=2:this.workPerThread=4,this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.useSharedMemoryWithB=r,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 {
|
|
${Gp(this.op,!1)}
|
|
}
|
|
var<workgroup> sharedBuf : array<f32, ${this.lastDimensionSize}>;
|
|
${Qe()}
|
|
|
|
// 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));
|
|
}
|
|
}
|
|
}
|
|
`}},mde=class{constructor(e,t,n){this.variableNames=["A","B"],this.workPerThread=4,this.isVec4=!0,this.size=!0;let r=128;this.workGroupSize=[r,1,1],this.outputShape=C.assertAndGetBroadcastShape(t,n),this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(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> {
|
|
${Gp(this.op,this.isVec4)}
|
|
}
|
|
${Qe()}
|
|
if (index < uniforms.size) {
|
|
let a = getAByOutputIndex(index);
|
|
let b = getBByOutputIndex(index);
|
|
setOutputAtIndex(index, binaryOperation(a, b));
|
|
}
|
|
}
|
|
`}},M8=class{constructor(e,t,n){this.variableNames=["A","B"],this.size=!0;let r=128;this.workGroupSize=[r,1,1],this.outputShape=C.assertAndGetBroadcastShape(t,n),this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`binary_${e}`,this.op=e}getUserCode(){return`
|
|
fn binaryOperation(a : f32, b : f32) -> f32 {
|
|
${Gp(this.op,!1)}
|
|
}
|
|
${Qe()}
|
|
if (index < uniforms.size) {
|
|
let a = getAByOutputIndex(index);
|
|
let b = getBByOutputIndex(index);
|
|
setOutputAtIndex(index, binaryOperation(a, b));
|
|
}
|
|
}
|
|
`}};function u4(e,t,n){if(w.arraysEqual(t,n)&&w.sizeFromShape(t)%4===0)return new mde(e,t,n);let s=t.length===1&&n.length>1&&t[0]<1024,a=n.length===1&&t.length>1&&n[0]<1024;return s||a?new fde(e,t,n,a):new M8(e,t,n)}function Or(e){let{inputs:t}=e,{x:n}=t;return e.backend.incRef(n.dataId),{dataId:n.dataId,shape:n.shape,dtype:n.dtype}}var gde={kernelName:go,backendName:"webgpu",kernelFunc:Or};function _c(e){let{inputs:t,backend:n}=e,{real:r,imag:s}=t,a=n.makeTensorInfo(r.shape,"complex64"),o=n.tensorMap.get(a.dataId),i=Or({inputs:{x:r},backend:n}),l=Or({inputs:{x:s},backend:n});return o.complexTensorInfos={real:i,imag:l},a}var yde={kernelName:Jd,backendName:"webgpu",kernelFunc:_c},Hp=class{constructor(e,t){this.variableNames=["A"],this.size=!0;let n=128;this.workGroupSize=[n,1,1],this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.op=t,this.shaderKey=`unary_${t}`}getUserCode(){return`
|
|
fn unaryOperation(a : f32) -> f32 {
|
|
${xi(this.op,!1)}
|
|
}
|
|
${Qe()}
|
|
if (index < uniforms.size) {
|
|
let a = getAByOutputIndex(index);
|
|
setOutputAtIndex(index, unaryOperation(a));
|
|
}
|
|
}
|
|
`}};function wn({opType:e,cpuKernelImpl:t,dtype:n}){return({inputs:r,backend:s})=>{let{x:a}=r,o=s,i=n||a.dtype;if(o.shouldExecuteOnCPU([a])&&t!=null){let u=o.tensorMap.get(a.dataId),c=t(u.values,i);return o.makeTensorInfo(a.shape,i,c)}let l=new Hp(a.shape,e);return o.runWebGPUProgram(l,[a],i)}}function Zn({opSnippet:e,cpuKernelImpl:t,supportsComplex:n=!1,dtype:r}){return({inputs:s,backend:a})=>{let{a:o,b:i}=s,l=a;if(n&&o.dtype==="complex64"){let p=l.tensorMap.get(o.dataId),d=l.tensorMap.get(i.dataId),h,f;if(e!==0)[h,f]=[[p.complexTensorInfos.real,d.complexTensorInfos.real],[p.complexTensorInfos.imag,d.complexTensorInfos.imag]].map(g=>{let[y,x]=g,A={dataId:y.dataId,dtype:y.dtype,shape:o.shape},b={dataId:x.dataId,dtype:x.dtype,shape:i.shape},v=u4(e,o.shape,i.shape);return l.runWebGPUProgram(v,[A,b],Nn(y.dtype,x.dtype))});else{let g=new l4(17,o.shape,i.shape),y=new l4(18,o.shape,i.shape),x=[{dataId:p.complexTensorInfos.real.dataId,dtype:p.complexTensorInfos.real.dtype,shape:o.shape},{dataId:p.complexTensorInfos.imag.dataId,dtype:p.complexTensorInfos.imag.dtype,shape:o.shape},{dataId:d.complexTensorInfos.real.dataId,dtype:d.complexTensorInfos.real.dtype,shape:i.shape},{dataId:d.complexTensorInfos.imag.dataId,dtype:d.complexTensorInfos.imag.dtype,shape:i.shape}];h=l.runWebGPUProgram(g,x,"float32"),f=l.runWebGPUProgram(y,x,"float32")}let m=_c({inputs:{real:h,imag:f},backend:l});return l.disposeData(h.dataId),l.disposeData(f.dataId),m}let u=r||Nn(o.dtype,i.dtype);if((o.dtype==="string"||i.dtype==="string"||l.shouldExecuteOnCPU([o,i]))&&t!=null){let p=l.tensorMap.get(o.dataId).values,d=l.tensorMap.get(i.dataId).values,h=o.dtype==="string"?C.fromUint8ToStringArray(p):p,f=o.dtype==="string"?C.fromUint8ToStringArray(d):d,[m,g]=t(o.shape,i.shape,h,f,u);return l.makeTensorInfo(g,u,m)}let c=u4(e,o.shape,i.shape);return l.runWebGPUProgram(c,[o,i],u)}}var{addImpl:Ade,ceilImpl:xde,concatImpl:bde,equalImpl:vde,expImpl:wde,expm1Impl:kde,floorImpl:Sde,gatherNdImpl:Ide,gatherV2Impl:Cde,greaterEqualImpl:Tde,greaterImpl:Nde,lessEqualImpl:Ede,lessImpl:Rde,logImpl:_de,maxImpl:$de,maximumImpl:Dde,minimumImpl:Pde,multiplyImpl:Fde,negImpl:Ode,notEqualImpl:Mde,prodImpl:zde,rangeImpl:Lde,rsqrtImpl:Bde,simpleAbsImpl:Wde,sliceImpl:Vde,stridedSliceImpl:Ude,stringNGramsImpl:Gde,subImpl:Hde,tileImpl:jde,topKImpl:qde,transposeImpl:Xde,uniqueImpl:Axe}=x0,Kde=wn({opType:0,cpuKernelImpl:Wde}),Zde={kernelName:Gi,backendName:"webgpu",kernelFunc:Kde},Yde=Zn({opSnippet:1,cpuKernelImpl:Ade,supportsComplex:!0}),Jde={kernelName:ea,backendName:"webgpu",kernelFunc:Yde},Qde=class{constructor(e){this.workPerThread=4,this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e[0],this.variableNames=e.map((t,n)=>`T${n}`),this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(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`
|
|
${Qe()}
|
|
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 epe(e){let{inputs:t,backend:n}=e,r=t;if(r.length===1)return Or({inputs:{x:r[0]},backend:n});let s=r.map(i=>i.dtype).reduce((i,l)=>Nn(i,l)),a=r.map(i=>i.shape),o=new Qde(a);return n.runWebGPUProgram(o,r,s)}var tpe={kernelName:Za,backendName:"webgpu",kernelFunc:epe},z8=class{constructor(e,t,n){this.workGroupSize=[64,1,1],this.variableNames=["x"],this.uniforms="axis : i32, infinityValue : f32,",this.size=!0;let r=[t];C.assertAxesAreInnerMostDims("arg"+n.charAt(0).toUpperCase()+n.slice(1),r,e.length),this.op=n==="min"?"<":">";let[s]=C.computeOutAndReduceShapes(e,r);this.outputShape=s.length===0?[1]:s,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(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=(s,a)=>this.outputShape.length===1?s:`${s}[${a}]`,n=s=>this.inputShape.length===1?"uniforms.xShape":`uniforms.xShape[${s}]`;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 = ${n(`${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;
|
|
}
|
|
|
|
${Qe()}
|
|
let outputIndex = index / i32(workGroupSizeX);
|
|
let coordInfo = getInputCoordInfo(outputIndex);
|
|
let Length = ${n("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]);
|
|
}
|
|
}
|
|
`}},npe=class{constructor(e,t){this.variableNames=["A"],this.workGroupSize=[16,16,1];let n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=e[t[r]];this.outputShape=n,this.dispatchLayout={x:[0],y:[1]},this.dispatch=Oe(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]}>;
|
|
${v3()}
|
|
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]);
|
|
}
|
|
}
|
|
`}},rpe=class{constructor(e,t){this.variableNames=["A"],this.workPerThread=4,this.workGroupSize=[64,1,1],this.size=!0;let n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=e[t[r]];this.outputShape=n,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.newDim=t,this.shaderKey=`transpose_${t}`}getUserCode(){let e=yn(this.outputShape.length),t=spe(this.newDim);return`
|
|
${Qe()}
|
|
|
|
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 spe(e){let t=e.length;if(t>4)throw Error(`Transpose for rank ${t} is not yet supported`);let n=new Array(t);for(let r=0;r<e.length;r++)n[e[r]]=`resRC[${r}]`;return n.join()}function Qs(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{perm:a}=r,o=n,i=s.shape.length,l=new Array(i);for(let c=0;c<l.length;c++)l[c]=s.shape[a[c]];if(n.shouldExecuteOnCPU([s])){let p=o.tensorMap.get(s.dataId).values,d=Xde(p,s.shape,s.dtype,a,l);return n.makeTensorInfo(l,s.dtype,d)}if(s.shape.length===2&&w.arraysEqual(a,[1,0])){let c=new npe(s.shape,a);return o.runWebGPUProgram(c,[s],s.dtype)}let u=new rpe(s.shape,a);return o.runWebGPUProgram(u,[s],s.dtype)}var ape={kernelName:Uo,backendName:"webgpu",kernelFunc:Qs};function ope(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r,o=w.parseAxisParam(a,s.shape),i=C.getAxesPermutation(o,s.shape.length),l=s,u=[];i!=null&&(l=Qs({inputs:{x:s},backend:n,attrs:{perm:i}}),u.push(l),o=C.getInnerMostAxes(o.length,l.shape.length)),C.assertAxesAreInnerMostDims("argMax",[o[0]],l.shape.length);let c=new z8(l.shape,o[0],"max"),p=[{type:"int32",data:[o[0]]},{type:"float32",data:[Number.NEGATIVE_INFINITY]}],d=n.runWebGPUProgram(c,[l],"int32",p);return u.forEach(h=>n.disposeData(h.dataId)),d}var ipe={kernelName:Ya,backendName:"webgpu",kernelFunc:ope};function lpe(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a}=r,o=w.parseAxisParam(a,s.shape),i=C.getAxesPermutation(o,s.shape.length),l=s,u=[];i!=null&&(l=Qs({inputs:{x:s},backend:n,attrs:{perm:i}}),u.push(l),o=C.getInnerMostAxes(o.length,l.shape.length)),C.assertAxesAreInnerMostDims("argMin",[o[0]],l.shape.length);let c=new z8(l.shape,o[0],"min"),p=[{type:"int32",data:[o[0]]},{type:"float32",data:[Number.POSITIVE_INFINITY]}],d=n.runWebGPUProgram(c,[l],"int32",p);return u.forEach(h=>n.disposeData(h.dataId)),d}var upe={kernelName:Vu,backendName:"webgpu",kernelFunc:lpe},L8=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=Xe(this.outputShape),this.dispatch=Oe(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"),`
|
|
${Qe()}
|
|
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});
|
|
}
|
|
}
|
|
`}},B8=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=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="poolWithFilterSizeEqualsOne"}getUserCode(){return`
|
|
${Qe()}
|
|
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 cpe(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=r,u=1,c=C.computePool2DInfo(s.shape,a,o,u,i,l);if(c.filterWidth===1&&c.filterHeight===1&&w.arraysEqual(c.inShape,c.outShape))return Or({inputs:{x:s},backend:n});let p,d=[{type:"int32",data:[c.strideHeight,c.strideWidth]}];return c.filterHeight===1&&c.filterWidth===1?p=new B8(c):(p=new L8(c,"avg"),d.push({type:"int32",data:[c.padInfo.top,c.padInfo.left]},{type:"int32",data:[c.dilationHeight,c.dilationWidth]},{type:"int32",data:[c.inHeight,c.inWidth]},{type:"int32",data:[c.effectiveFilterHeight,c.effectiveFilterWidth]})),n.runWebGPUProgram(p,[s],s.dtype,d)}var dpe={kernelName:Ja,backendName:"webgpu",kernelFunc:cpe};function ppe(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a}=t,{transposeA:o,transposeB:i}=r;return C3({a:s,b:a,transposeA:o,transposeB:i,backend:n})}var hpe={kernelName:Qa,backendName:"webgpu",kernelFunc:ppe},fpe=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=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.start=e,this.uniforms=`start : ${yn(e.length)}, `,this.shaderKey="slice"}getUserCode(){let e=yn(this.rank),t=mpe(this.rank),n;return this.start.length===1?n=this.outputShape.map((s,a)=>"sourceLoc = uniforms.start + coords;"):n=this.outputShape.map((s,a)=>`sourceLoc.${sy[a]} = uniforms.start[${a}] + coords.${sy[a]};`),`
|
|
${Qe()}
|
|
if (index < uniforms.size) {
|
|
var sourceLoc : ${e};
|
|
let coords = getCoordsFromIndex(index);
|
|
${n.join(`
|
|
`)}
|
|
setOutputAtIndex(index, getSource(${t}));
|
|
}
|
|
}
|
|
`}},sy=["x","y","z","w","u","v"];function mpe(e){if(e===1)return"sourceLoc";if(e<=6)return sy.slice(0,e).map(t=>`sourceLoc.${t}`).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}function $c(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,size:o}=r,[i,l]=Mt.parseSliceParams(s,a,o);if(Mt.assertParamsValid(s,i,l),n.shouldExecuteOnCPU([s])||s.dtype==="string"){let p=n.tensorMap.get(s.dataId),d=Vde(p.values,i,l,s.shape,s.dtype);return n.makeTensorInfo(l,s.dtype,d)}if(w.sizeFromShape(l)===0)return n.makeTensorInfo(l,s.dtype,[]);let u=new fpe(i,l),c=[{type:"int32",data:i}];return n.runWebGPUProgram(u,[s],s.dtype,c)}var gpe={kernelName:Al,backendName:"webgpu",kernelFunc:$c},ype=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,crops:o}=r;w.assert(s.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGPU backend not implemented yet");let i=a.reduce((x,A)=>x*A),l=C.getReshaped(s.shape,a,i),u=C.getPermuted(l.length,a.length),c=C.getReshapedPermuted(s.shape,a,i),p=C.getSliceBeginCoords(o,a.length),d=C.getSliceSize(c,o,a.length),h=[],f=qe({inputs:{x:s},backend:n,attrs:{shape:l}}),m=Qs({inputs:{x:f},backend:n,attrs:{perm:u}}),g=qe({inputs:{x:m},backend:n,attrs:{shape:c}}),y=$c({inputs:{x:g},backend:n,attrs:{begin:p,size:d}});return h.push(f),h.push(m),h.push(g),h.forEach(x=>n.disposeData(x.dataId)),y},Ape={kernelName:Hi,backendName:"webgpu",kernelFunc:ype},W8=Zn({opSnippet:10,dtype:"bool",cpuKernelImpl:Mde}),xpe={kernelName:il,backendName:"webgpu",kernelFunc:W8};function jp(e){let{inputs:t,backend:n}=e,{input:r}=t,s=n.tensorMap.get(r.dataId);return Or({inputs:{x:s.complexTensorInfos.real},backend:n})}var bpe={kernelName:ip,backendName:"webgpu",kernelFunc:jp};function vpe(e,t){let n=new Hp(e.shape,22),r=t.runWebGPUProgram(n,[e],"int32");return{dataId:r.dataId,shape:r.shape,dtype:r.dtype}}function ay(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dtype:a}=r;if(a==="complex64"){if(s.dtype==="complex64")return Or({inputs:{x:s},backend:n});let o=Ft(s.shape),i=ay({inputs:{x:s},backend:n,attrs:{dtype:"float32"}}),l=_c({inputs:{real:i,imag:o},backend:n});return o.dispose(),n.disposeData(i.dataId),l}if(s.dtype==="complex64"){let o=jp({inputs:{input:s},backend:n}),i=ay({inputs:{x:o},backend:n,attrs:{dtype:a}});return n.disposeData(o.dataId),i}if(!w.hasEncodingLoss(s.dtype,a)){let o=Or({inputs:{x:s},backend:n});return{dataId:o.dataId,shape:o.shape,dtype:a}}if(a==="int32")return vpe(s,n);if(a==="bool"){let o=n.makeTensorInfo([],"bool",w.getTypedArrayFromDType("bool",1)),l=W8({inputs:{a:s,b:o},backend:n});return n.disposeData(o.dataId),l}throw new Error(`Error in Cast: failed to cast ${s.dtype} to ${a}`)}var wpe={kernelName:eo,backendName:"webgpu",kernelFunc:ay},kpe=wn({opType:1,cpuKernelImpl:xde}),Spe={kernelName:to,backendName:"webgpu",kernelFunc:kpe},Ipe=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=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]),this.shaderKey="clipVec4"}getUserCode(){return`
|
|
${Qe()}
|
|
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);
|
|
}
|
|
}
|
|
`}},Cpe=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=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="clip"}getUserCode(){return`
|
|
${Qe()}
|
|
if(index < uniforms.size) {
|
|
let value = getAByOutputIndex(index);
|
|
if (isnan(value)) {
|
|
setOutputAtIndex(index, value);
|
|
return;
|
|
}
|
|
setOutputAtIndex(index, clamp(value, uniforms.minVal, uniforms.maxVal));
|
|
}
|
|
}
|
|
`}};function Tpe(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{clipValueMin:a,clipValueMax:o}=r,i,l=[{type:"float32",data:[a]},{type:"float32",data:[o]}];return w.sizeFromShape(s.shape)%4===0?i=new Ipe(s.shape):i=new Cpe(s.shape),n.runWebGPUProgram(i,[s],s.dtype,l)}var Npe={kernelName:ta,backendName:"webgpu",kernelFunc:Tpe},Epe=class{constructor(e){this.uniforms="",this.workPerThread=4,this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=C.computeOutShape(e,1),this.variableNames=e.map((t,n)=>`T${n}`),this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(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 s=1;s<this.offsetLength;s++)e.push(`else if (yC < uniforms.offset${[s]}){ setOutputAtCoords(coords.x, coords.y, getT${s}(yR, yC - uniforms.offset${s-1})); }`);let n=this.offsetLength,r=this.offsetLength-1;e.push(`else { setOutputAtCoords(coords.x, coords.y, getT${n}(yR, yC - uniforms.offset${r})); }`)}else e.push("setOutputAtCoords(coords.x, coords.y, getT0(yR, yC));");return`
|
|
${Qe()}
|
|
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 N0(e){let{inputs:t,backend:n}=e,{input:r}=t,s=n.tensorMap.get(r.dataId);return Or({inputs:{x:s.complexTensorInfos.imag},backend:n})}var Rpe={kernelName:rp,backendName:"webgpu",kernelFunc:N0};function oy(e,t,n){let r=e[0].dtype;if(r==="complex64"){let h=e.map(x=>jp({inputs:{input:x},backend:n})),f=e.map(x=>N0({inputs:{input:x},backend:n})),m=oy(h,t,n),g=oy(f,t,n),y=_c({inputs:{real:m,imag:g},backend:n});return h.forEach(x=>n.disposeData(x.dataId)),f.forEach(x=>n.disposeData(x.dataId)),n.disposeData(m.dataId),n.disposeData(g.dataId),y}let s=n.shouldExecuteOnCPU(e);if(r==="string"&&(s=!0),s){let h=e.map(b=>{let v=w.sizeFromShape(b.shape.slice(t));return qe({inputs:{x:b},backend:n,attrs:{shape:[-1,v]}})}),f=h.map(b=>({vals:n.readSync(b.dataId),shape:b.shape})),m=C.computeOutShape(h.map(b=>b.shape),1),g=h[0].shape[0]===1,y=bde(f,m,r,g),x=C.computeOutShape(e.map(b=>b.shape),t),A=n.makeTensorInfo(x,r,y);return h.forEach(b=>n.disposeData(b.dataId)),A}let{tensors2D:a,outShape:o}=_pe(e,t,n),i=a.map(h=>h.shape),l=new Epe(i),u=[],c=new Array(i.length-1);if(c.length>0){c[0]=i[0][1],u.push({type:"int32",data:[c[0]]});for(let h=1;h<c.length;h++)c[h]=c[h-1]+i[h][1],u.push({type:"int32",data:[c[h]]})}let p=n.runWebGPUProgram(l,a,a[0].dtype,u);a.forEach(h=>n.disposeData(h.dataId));let d=qe({inputs:{x:p},backend:n,attrs:{shape:o}});return n.disposeData(p.dataId),d}function _pe(e,t,n){let r=C.computeOutShape(e.map(a=>a.shape),t);return{tensors2D:e.map(a=>qe({inputs:{x:a},backend:n,attrs:{shape:[w.sizeFromShape(a.shape.slice(0,t)),w.sizeFromShape(a.shape.slice(t))]}})),outShape:r}}function V8(e){let{inputs:t,backend:n,attrs:r}=e,{axis:s}=r,a=w.parseAxisParam(s,t[0].shape)[0],o=C.computeOutShape(t.map(u=>u.shape),a);if(w.sizeFromShape(o)===0)return n.makeTensorInfo(o,t[0].dtype,[]);let i=t.filter(u=>w.sizeFromShape(u.shape)>0);if(i.length===1)return Or({inputs:{x:i[0]},backend:n});let l=i.map(u=>u.shape);return C.assertParamsConsistent(l,a),oy(i,a,n)}var $pe={kernelName:ji,backendName:"webgpu",kernelFunc:V8},Dpe=class{constructor(e,t=!1,n=null,r=!1,s=!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=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize,this.elementsPerThread),this.convInfo=e,this.addBias=t,this.activation=n,this.hasPreluActivationWeights=r,this.hasLeakyreluAlpha=s,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],n=this.outputShape[1]*this.outputShape[2],r=this.outputShape[3],s=this.convInfo.filterHeight*this.convInfo.filterWidth*this.convInfo.inChannels;return[Js(e,[n,s]),Js(t,[s,r])]}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=F8(this.elementsPerThread,this.tileAOuter,this.tileBOuter,this.tileInner),r=`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;`,s=this.fitA?`${r}`:`if (r < uniforms.dimAOuter && c < uniforms.dimInner) {
|
|
${r}
|
|
}
|
|
return vec4<f32>(0.0);
|
|
`,a=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);
|
|
`,o="",i="";if(this.activation){let c=la(this.activation,this.isVec4);if(this.hasPreluActivationWeights)o=`fn activation(a : vec4<f32>, outCoord : vec4<i32>) -> vec4<f32> {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${c}
|
|
}`;else{if(this.hasLeakyreluAlpha)throw o=`fn activation(outCoord: vec4<f32>) -> vec4<f32> {
|
|
let b = getLeakyreluAlphaByOutputCoords(outCoord);
|
|
${c}
|
|
}`,new Error("Leakyrelu is not supported.");o=`
|
|
fn activation(a : vec4<f32>, outCoord : vec4<i32>) -> vec4<f32> {
|
|
${c}
|
|
}`}i="value = activation(value, outCoord);"}let l=this.addBias?"value = value + getBiasByOutputCoords(outCoord);":"";return`
|
|
${o}
|
|
fn mm_readA(row : i32, col : i32, globalId : vec3<u32>) -> vec4<f32> {
|
|
let r = row;
|
|
let c = col * 4;
|
|
var batch = i32(globalId.z);
|
|
${s}
|
|
}
|
|
|
|
fn mm_readB(row : i32, col : i32, globalId : vec3<u32>) -> vec4<f32> {
|
|
${a}
|
|
}
|
|
|
|
fn mm_write(row : i32, col : i32, valueInput : vec4<f32>, globalId : vec3<u32>) {
|
|
var batch = i32(globalId.z);
|
|
var value = valueInput;
|
|
if (row < uniforms.dimAOuter && col * 4 < uniforms.dimBOuter)
|
|
{
|
|
let outCoord = vec4<i32>(
|
|
batch,
|
|
row / uniforms.outShape[2],
|
|
row % uniforms.outShape[2],
|
|
col * 4);
|
|
${l}
|
|
${i}
|
|
setOutputAtCoords(outCoord[0], outCoord[1], outCoord[2], outCoord[3],
|
|
value);
|
|
}
|
|
}
|
|
${e}
|
|
`}},Ppe=class{constructor(e,t=!1,n=null,r=!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=w3(this.dispatchLayout,this.outputShape),this.elementsPerThread=k3(this.dispatchLayout,this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize,this.elementsPerThread),t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=n,this.hasPreluActivationWeights=r,[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],n=e>t?e:t;w.assert(n%this.workGroupSize[0]===0&&n%this.workGroupSize[1]===0,()=>"tileInner must be multiple of workgroupsize.x and workgroupsize.y");let r=[e,n],s=[n,t],a=this.outputShape[1]*this.outputShape[2],o=this.outputShape[3],i=this.convInfo.filterHeight*this.convInfo.filterWidth*this.convInfo.inChannels;return[Js(r,[a,i]),Js(s,[i,o])]}getUserCode(){let e=I3(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;`,n=this.fitA?`${t}`:`if (row < uniforms.dimAOuter && col < uniforms.dimInner) {
|
|
${t}
|
|
}
|
|
return 0.0;
|
|
`,r=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;
|
|
`,s="",a="";if(this.activation){let l=la(this.activation,!1);this.hasPreluActivationWeights?s=`fn activation(a: f32, outCoord : vec4<i32>) -> f32 {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${l}
|
|
}`:s=`
|
|
fn activation(a : f32, outCoord : vec4<i32>) -> f32 {
|
|
${l}
|
|
}
|
|
`,a="value = activation(value, outCoord);"}let o=this.addBias?"value = value + getBiasByOutputCoords(outCoord);":"";return`
|
|
${s}
|
|
fn mm_readA(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
|
|
var batch = i32(globalId.z);
|
|
${n}
|
|
}
|
|
|
|
fn mm_readB(row : i32, col : i32, globalId : vec3<u32>) -> f32 {
|
|
${r}
|
|
}
|
|
|
|
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);
|
|
${o}
|
|
${a}
|
|
result[getIndexFromCoords4D(outCoord, uniforms.outShape)] = value;
|
|
}
|
|
${e}
|
|
`}},Fpe=class{constructor(e,t=!1,n=null,r=!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=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize),w.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=n,this.hasPreluActivationWeights=r,this.shaderKey=`conv2DNaive_${this.activation}`}getUserCode(){let e="",t="";if(this.activation){let s=la(this.activation);this.hasPreluActivationWeights?e=`fn activation(a : f32, outCoord : vec4<i32>) -> f32{
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${s}
|
|
}`:e=`
|
|
fn activation(a : f32, outCoord : vec4<i32>) -> f32{
|
|
${s}
|
|
}
|
|
`,t="value = activation(value, outCoord);"}let n=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)) {
|
|
${n}
|
|
${t}
|
|
setOutputAtCoords(batch, row, col, chan, value);
|
|
}
|
|
}
|
|
|
|
${Ko()}
|
|
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);
|
|
}
|
|
`}},Ope=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=Xe(this.outputShape),this.dispatch=Oe(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`
|
|
${Qe()}
|
|
|
|
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 Mpe({x:e,filter:t,convInfo:n,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let l=e.shape,u=n.dataFormat==="channelsLast",c=!1,p=!1,d=n.filterHeight===n.inHeight&&n.filterWidth===n.inWidth&&n.padInfo.type==="VALID",h,f;if(d){let y=n.inHeight*n.inWidth*n.inChannels;h=qe({inputs:{x:e},backend:r,attrs:{shape:[1,n.batchSize,y]}}),f=qe({inputs:{x:t},backend:r,attrs:{shape:[1,y,n.outChannels]}})}else{let y=u?l[0]*l[1]*l[2]:l[0]*l[2]*l[3];h=qe({inputs:{x:e},backend:r,attrs:{shape:[1,y,n.inChannels]}}),f=qe({inputs:{x:t},backend:r,attrs:{shape:[1,n.inChannels,n.outChannels]}})}let m=C3({a:h,b:f,transposeA:c,transposeB:p,backend:r,bias:s,activation:i,preluActivationWeights:a,leakyreluAlpha:o}),g=qe({inputs:{x:m},backend:r,attrs:{shape:n.outShape}});return r.disposeData(h.dataId),r.disposeData(f.dataId),r.disposeData(m.dataId),g}function zpe({x:e,filter:t,convInfo:n,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let{filterWidth:l,filterHeight:u,inChannels:c,strideWidth:p,strideHeight:d,padInfo:h,outWidth:f,outHeight:m,dilationWidth:g,dilationHeight:y,dataFormat:x}=n,A=x==="channelsLast",b=l*u*c,v=m*f,S=[v,b],I=!1,E=!1,R=[],P=qe({inputs:{x:e},backend:r,attrs:{shape:e.shape.slice(1)}}),_=qe({inputs:{x:t},backend:r,attrs:{shape:[1,b,-1]}});R.push(P),R.push(_);let D=new Ope(S,A),T=[{type:"int32",data:[h.left,h.top]},{type:"int32",data:[p,d]},{type:"int32",data:[g,y]},{type:"int32",data:[f]},{type:"int32",data:[c*l]},{type:"int32",data:[c]}],F=r.runWebGPUProgram(D,[P],P.dtype,T),U=qe({inputs:{x:F},backend:r,attrs:{shape:[1,S[0],S[1]]}});R.push(F),R.push(U);let X=[1,S[0],S[1]],z=new O8(X,[1,v,n.outChannels],Y().get("WEBGPU_MATMUL_WORK_PER_THREAD"),I,E,s,i,a),Z=X[1],W=X[2],ee=n.outChannels,Q=[{type:"int32",data:[Z]},{type:"int32",data:[ee]},{type:"int32",data:[W]}],ae=[U,_];s&&ae.push(s),a&&ae.push(a),i==="leakyrelu"&&(T.push({type:"float32",data:[o]}),z.uniforms+=" alpha : f32,");let J=r.runWebGPUProgram(z,ae,U.dtype,Q),se=A?[1,m,f,n.outChannels]:[1,n.outChannels,m,f],ie=qe({inputs:{x:J},backend:r,attrs:{shape:se}});R.push(J);for(let me of R)r.disposeData(me.dataId);return ie}function U8({x:e,filter:t,convInfo:n,backend:r,bias:s=null,preluActivationWeights:a=null,leakyreluAlpha:o=0,activation:i=null}){let l=s!=null,u=a!=null,c;if(n.filterHeight===n.inHeight&&n.filterWidth===n.inWidth&&n.padInfo.type==="VALID"||n.filterHeight===1&&n.filterWidth===1&&n.dilationHeight===1&&n.dilationWidth===1&&n.strideHeight===1&&n.strideWidth===1&&(n.padInfo.type==="SAME"||n.padInfo.type==="VALID"))return Mpe({x:e,filter:t,convInfo:n,backend:r,bias:s,activation:i,preluActivationWeights:a,leakyreluAlpha:o});if(Y().getBool("WEBGPU_CONV_SEPARATE_IM2COL_SHADER")&&e.shape[0]===1)return zpe({x:e,filter:t,convInfo:n,backend:r,bias:s,preluActivationWeights:a,leakyreluAlpha:o,activation:i});let d=Y().getBool("WEBGPU_USE_NAIVE_CONV2D"),h=(n.inChannels%4===0||n.inChannels===3&&n.padInfo.type==="VALID")&&n.outChannels%4===0,f=[n.padInfo.top,n.padInfo.left],m=[{type:"int32",data:[n.filterHeight,n.filterWidth]},{type:"int32",data:[...f]},{type:"int32",data:[n.strideHeight,n.strideWidth]},{type:"int32",data:[n.dilationHeight,n.dilationWidth]}];if(d)c=new Fpe(n,l,i,u);else{h?c=new Dpe(n,l,i,u):c=new Ppe(n,l,i,u);let y=n.outShape[1]*n.outShape[2],x=n.outShape[3],A=n.filterHeight*n.filterWidth*n.inShape[3];m.push({type:"int32",data:[y]},{type:"int32",data:[x]},{type:"int32",data:[A]})}let g=[e,t];return l&&g.push(s),u&&g.push(a),i==="leakyrelu"&&(m.push({type:"float32",data:[o]}),c.uniforms+=" alpha : f32,"),r.runWebGPUProgram(c,g,e.dtype,m)}function Lpe(e){let{inputs:t,attrs:n,backend:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dataFormat:l,dilations:u,dimRoundingMode:c}=n,p=C.convertConv2DDataFormat(l),d=C.computeConv2DInfo(s.shape,a.shape,o,u,i,c,!1,p);return U8({x:s,filter:a,convInfo:d,backend:r})}var Bpe={kernelName:no,backendName:"webgpu",kernelFunc:Lpe},Wpe=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=w3(this.dispatchLayout,this.outputShape),this.elementsPerThread=k3(this.dispatchLayout,this.outputShape),this.dispatch=Oe(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;
|
|
}
|
|
|
|
${I3(this.elementsPerThread,this.workGroupSize)}
|
|
`}},Vpe=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=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.isChannelsLast=e.dataFormat==="channelsLast",this.shaderKey=`conv2DDerInput_${this.isChannelsLast}`}getUserCode(){let e=this.isChannelsLast?1:2,t=this.isChannelsLast?2:3,n=this.isChannelsLast?3:1;return`
|
|
${Qe()} {
|
|
if(index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let batch = coords[0];
|
|
let d1 = coords[${n}];
|
|
|
|
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 Upe(e){let{inputs:t,backend:n,attrs:r}=e,{dy:s,filter:a}=t,{inputShape:o,strides:i,pad:l,dataFormat:u,dimRoundingMode:c}=r,p=C.convertConv2DDataFormat(u),d=C.computeConv2DInfo(o,a.shape,i,1,l,c,!1,p),h=[{type:"int32",data:[d.filterHeight,d.filterWidth]},{type:"int32",data:[d.filterHeight-1-d.padInfo.top,d.filterWidth-1-d.padInfo.left]},{type:"int32",data:[d.strideHeight,d.strideWidth]},{type:"int32",data:[d.batchSize,d.outHeight,d.outWidth,d.outChannels]}],f;if(Y().getBool("WEBGPU_USE_NAIVE_CONV2D_TRANSPOSE"))f=new Vpe(d);else{f=new Wpe(d);let m=d.inShape[1]*d.inShape[2],g=d.inShape[3],y=d.filterHeight*d.filterWidth*d.outChannels;h.push({type:"uint32",data:[m]},{type:"uint32",data:[g]},{type:"uint32",data:[y]})}return n.runWebGPUProgram(f,[s,a],"float32",h)}var Gpe={kernelName:ro,backendName:"webgpu",kernelFunc:Upe},Hpe=wn({opType:2}),jpe={kernelName:so,backendName:"webgpu",kernelFunc:Hpe},qpe=wn({opType:3}),Xpe={kernelName:ao,backendName:"webgpu",kernelFunc:qpe},Kpe=class{constructor(e,t,n,r){this.variableNames=["Image","Boxes","BoxInd"],this.uniforms="extrapolationValue : f32,",this.workGroupSize=[64,1,1],this.size=!0;let[s]=t;this.outputShape=[s,n[0],n[1],e],this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.methodId=r==="bilinear"?1:0,this.cropHeightBiggerThan1=this.outputShape[1]>1,this.cropWidthBiggerThan1=this.outputShape[2]>1,this.shaderKey=`cropAndResize_${this.methodId}_${this.cropHeightBiggerThan1}_${this.cropWidthBiggerThan1}`}getUserCode(){let[e,t]=["f32(uniforms.imageShape[1] - 1)","f32(uniforms.imageShape[2] - 1)"],[n,r,s]=this.cropHeightBiggerThan1?[`(${e} / f32(uniforms.outShape[1] - 1))`,"(y2-y1) * height_ratio",`y1*${e} + f32(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${e}`],[a,o,i]=this.cropWidthBiggerThan1?[`(${t} / f32(uniforms.outShape[2] - 1))`,"(x2-x1) * width_ratio",`x1*${t} + f32(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${t}`];return`
|
|
${Qe()}
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let height_ratio = f32(${n});
|
|
let width_ratio = f32(${a});
|
|
let b = coords[0];
|
|
let y = coords[1];
|
|
let x = coords[2];
|
|
let d = coords[3];
|
|
// get box vals
|
|
let y1 = getBoxes(b, 0);
|
|
let x1 = getBoxes(b, 1);
|
|
let y2 = getBoxes(b, 2);
|
|
let x2 = getBoxes(b, 3);
|
|
// get image in batch index
|
|
let bInd = i32(round(getBoxInd(b)));
|
|
if(bInd < 0 || bInd >= uniforms.outShape[0]) {
|
|
return;
|
|
}
|
|
let height_scale = ${r};
|
|
let width_scale = ${o};
|
|
let in_y = ${s};
|
|
if( in_y < 0.0 || in_y > ${e} ) {
|
|
setOutputAtIndex(index, uniforms.extrapolationValue);
|
|
return;
|
|
}
|
|
let in_x = ${i};
|
|
if( in_x < 0.0 || in_x > ${t} ) {
|
|
setOutputAtIndex(index, uniforms.extrapolationValue);
|
|
return;
|
|
}
|
|
let sourceFracIndexCR = vec2<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);
|
|
}
|
|
}
|
|
}
|
|
`}},Zpe=e=>{let{inputs:t,backend:n,attrs:r}=e,{image:s,boxes:a,boxInd:o}=t,{cropSize:i,method:l,extrapolationValue:u}=r,c=new Kpe(s.shape[3],a.shape,i,l),p=[{type:"float32",data:[u]}];return n.runWebGPUProgram(c,[s,a,o],"float32",p)},Ype={kernelName:Xi,backendName:"webgpu",kernelFunc:Zpe},c4=class{constructor(e,t,n,r){this.variableNames=["x"],this.uniforms="index : f32,",this.size=!0;let s=128;this.workGroupSize=[s,1,1],this.outputShape=t,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.exclusive=n,this.reverse=r,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",n=this.exclusive?t:`getX(${d4(e,"coords",this.op)})`,r=this.outputShape[this.outputShape.length-1],s="",a="";return this.exclusive?(s=this.reverse?`end != ${r-1}`:"end != 0",a=this.reverse?"end + 1":"end - 1"):(s=this.reverse?`end + pow2 < ${r}`:"end >= pow2",a=this.reverse?"end + pow2":"end - pow2"),`
|
|
${Qe()}
|
|
if (index < uniforms.size) {
|
|
var coords = getCoordsFromIndex(index);
|
|
|
|
let end = ${p4(e,"coords",this.op)};
|
|
var val = ${n};
|
|
let pow2 = i32(pow(2.0, uniforms.index));
|
|
if (${s}) {
|
|
let idx = ${a};
|
|
${p4(e,"coords",this.op)} = idx;
|
|
val ${this.op}= getX(${d4(e,"coords",this.op)});
|
|
}
|
|
setOutputAtIndex(index, val);
|
|
}
|
|
}
|
|
`}};function d4(e,t,n){if(e===1)return`${t}`;if(e===2)return`${t}.x, ${t}.y`;if(e===3)return`${t}.x, ${t}.y, ${t}.z`;if(e===4)return`${t}.x, ${t}.y, ${t}.z, ${t}.w`;throw Error(`Cumulative ${n} for rank ${e} is not yet supported`)}function p4(e,t,n){if(e===1)return`${t}`;if(e===2)return`${t}.y`;if(e===3)return`${t}.z`;if(e===4)return`${t}.w`;throw Error(`Cumulative ${n} for rank ${e} is not yet supported`)}function G8(e,t,n,r,s,a){let o=t.shape.length,i=C.getAxesPermutation([r],o),l=t;i!=null&&(l=Qs({inputs:{x:t},backend:n,attrs:{perm:i}}));let u=C.getInnerMostAxes(1,o)[0];if(u!==o-1)throw new Error(`WebGPU cumprod shader expects an inner-most axis=${t.shape.length-1} but got axis=${r}`);let c=l.shape[u],p=Or({inputs:{x:l},backend:n});for(let d=0;d<=Math.ceil(Math.log2(c))-1;d++){let h=new c4(e,l.shape,!1,a),f=p,m=[{type:"float32",data:[d]}];p=n.runWebGPUProgram(h,[p],p.dtype,m),n.disposeData(f.dataId)}if(s){let d=new c4(e,l.shape,s,a),h=p,f=[{type:"float32",data:[0]}];p=n.runWebGPUProgram(d,[p],p.dtype,f),n.disposeData(h.dataId)}if(i!=null){let d=C.getUndoAxesPermutation(i),h=Qs({inputs:{x:p},backend:n,attrs:{perm:d}});return n.disposeData(p.dataId),n.disposeData(l.dataId),h}return p}function Jpe(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:o,reverse:i}=r;return G8("*",s,n,a,o,i)}var Qpe={kernelName:qi,backendName:"webgpu",kernelFunc:Jpe};function ehe(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:o,reverse:i}=r;return G8("+",s,n,a,o,i)}var the={kernelName:oo,backendName:"webgpu",kernelFunc:ehe},nhe=class{constructor(e,t){this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.uniforms="blockSize : i32,",this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`depthToSpace_${t}`,this.dataFormat=t}getUserCode(){return`
|
|
${Qe()}
|
|
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 rhe(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockSize:a,dataFormat:o}=r,i=s.shape[0],l=o==="NHWC"?s.shape[1]:s.shape[2],u=o==="NHWC"?s.shape[2]:s.shape[3],c=o==="NHWC"?s.shape[3]:s.shape[1],p=l*a,d=u*a,h=c/(a*a),f=o==="NHWC"?[i,p,d,h]:[i,h,p,d],m=[{type:"int32",data:[a]}],g=new nhe(f,o);return n.runWebGPUProgram(g,[s],s.dtype,m)}var she={kernelName:Ki,backendName:"webgpu",kernelFunc:rhe},H8=class{constructor(e,t=!1,n=null,r=!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=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize,[1,4,4]),w.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=n,this.hasPreluActivation=r,this.shaderKey=`depthwise3x3_${n}`}getUserCode(){let e="",t="";if(this.activation){let s=la(this.activation,this.isVec4);this.hasPreluActivation?e=`fn activation(a : vec4<f32>, outCoord : vec4<i32>) -> vec4<f32> {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${s}
|
|
}`:e=`
|
|
fn activation(a : vec4<f32>, outCoord : vec4<i32>) -> vec4<f32> {
|
|
${s}
|
|
}
|
|
`,t="dotProd[i] = activation(dotProd[i], coords);"}let n=this.addBias?"dotProd[i] = dotProd[i] + getBiasByOutputCoords(coords);":"";return`
|
|
${e}
|
|
|
|
${v3()}
|
|
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)) {
|
|
${n}
|
|
${t}
|
|
setOutputAtCoords(coords[0], coords[1], coords[2], coords[3], dotProd[i]);
|
|
}
|
|
}
|
|
}
|
|
`}},j8=class{constructor(e,t=!1,n=null,r=!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=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize),w.assert(e.dataFormat==="channelsLast",()=>"TODO: NCHW is unimplemented"),t&&this.variableNames.push("bias"),r&&this.variableNames.push("preluActivationWeights"),this.convInfo=e,this.addBias=t,this.activation=n,this.hasPreluActivation=r,this.shaderKey=`depthwise_${this.activation}`}getUserCode(){let e="",t="";if(this.activation){let s=la(this.activation,!1);this.hasPreluActivation?e=`fn activation(a : f32, outCoord : vec4<i32>) -> f32 {
|
|
let b = getPreluActivationWeightsByOutputCoords(outCoord);
|
|
${s}
|
|
}`:e=`
|
|
fn activation(a : f32, outCoord : vec4<i32>) -> f32 {
|
|
${s}
|
|
}
|
|
`,t="dotProd = activation(dotProd, coords);"}let n=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);
|
|
}
|
|
}
|
|
|
|
${Ko()}
|
|
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;
|
|
}
|
|
}
|
|
}
|
|
|
|
${n}
|
|
${t}
|
|
writeResult(batch, coords[1], coords[2], d2, dotProd);
|
|
}
|
|
`}};function ahe(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a}=t,{strides:o,pad:i,dilations:l,dimRoundingMode:u}=r,c=l;c==null&&(c=[1,1]);let p=C.computeConv2DInfo(s.shape,a.shape,o,c,i,u,!0),d=[{type:"int32",data:[p.padInfo.top,p.padInfo.left]},{type:"int32",data:[p.strideHeight,p.strideWidth]},{type:"int32",data:[p.dilationHeight,p.dilationWidth]},{type:"int32",data:[p.inHeight,p.inWidth]}],h;return p.batchSize===1&&p.inHeight===p.outHeight&&p.inWidth===p.outWidth&&p.strideHeight===1&&p.strideWidth===1&&p.filterHeight===p.filterWidth&&p.inChannels===p.outChannels&&p.dilationHeight===1&&p.dilationWidth===1&&p.filterHeight===3&&p.inChannels%4===0?h=new H8(p):(h=new j8(p),d.push({type:"int32",data:[p.filterHeight]},{type:"int32",data:[p.filterWidth]},{type:"int32",data:[p.outChannels/p.inChannels]})),n.runWebGPUProgram(h,[s,a],s.dtype,d)}var ohe={kernelName:io,backendName:"webgpu",kernelFunc:ahe},q8=Zn({opSnippet:0,cpuKernelImpl:Fde,supportsComplex:!0}),ihe={kernelName:Co,backendName:"webgpu",kernelFunc:q8},lhe=class{constructor(e,t){this.workGroupSize=[64,1,1],this.variableNames=["x"],this.uniforms="reduceSize : i32,",this.size=!0,this.inputShape=[e.batchSize,e.inSize];let[n]=C.computeOutAndReduceShapes(this.inputShape,[1]);this.outputShape=n.length===0?[1]:n,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,[1,1,1]),this.reduceType=t,this.shaderKey=`reduce_${t}`}getUserCode(){let e="",t="0.0";this.reduceType==="min"||this.reduceType==="max"?(e=`
|
|
if (isnan(candidate)) {
|
|
bestValue = uniforms.NAN;
|
|
} else if (!isnan(bestValue) && candidate ${this.reduceType==="min"?"<":">"} bestValue)
|
|
{ bestValue = candidate; }`,t="f32(x[offset])"):this.reduceType==="sum"||this.reduceType==="mean"?e=" bestValue = bestValue + candidate; ":this.reduceType==="prod"&&(e=" bestValue = bestValue * candidate; ",t="1.0");let n=this.reduceType==="mean"?"setOutputAtIndex(outputIndex, bestValue / f32(uniforms.reduceSize));":"setOutputAtIndex(outputIndex, bestValue);";return`
|
|
fn DIV_CEIL(a : u32, b : u32) -> u32 {
|
|
return ((a - 1u) / b + 1u);
|
|
}
|
|
|
|
${`
|
|
var<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;
|
|
}
|
|
${Qe()}
|
|
let outputIndex = index / i32(workGroupSizeX);
|
|
let offset = getOffset(outputIndex);
|
|
var bestValue = ${t};
|
|
let Length = uniforms.reduceSize;
|
|
let WorkPerThread = DIV_CEIL(u32(Length), workGroupSizeX);
|
|
for (var k = i32(localId.x); k < Length && outputIndex < uniforms.size;
|
|
k = k + i32(workGroupSizeX)) {
|
|
let candidate = f32(x[offset + k]);
|
|
${e}
|
|
}
|
|
xBestValues[localId.x] = bestValue;
|
|
workgroupBarrier();
|
|
|
|
var reduceSize = min(u32(Length), workGroupSizeX);
|
|
for (var currentSize = reduceSize / 2u; reduceSize > 1u;
|
|
currentSize = reduceSize / 2u) {
|
|
let interval = DIV_CEIL(reduceSize, 2u);
|
|
if (localId.x < currentSize) {
|
|
let candidate = xBestValues[localId.x + interval];
|
|
${e}
|
|
xBestValues[localId.x] = bestValue;
|
|
}
|
|
reduceSize = interval;
|
|
workgroupBarrier();
|
|
}
|
|
|
|
if (localId.x == 0u && outputIndex < uniforms.size) {
|
|
${n}
|
|
}
|
|
}
|
|
`}};function qp(e,t,n,r,s){let a=e.shape.length,o=[],i=w.parseAxisParam(t,e.shape),l=i,u=C.getAxesPermutation(l,a),c=e;u!=null&&(c=Qs({inputs:{x:e},attrs:{perm:u},backend:s}),l=C.getInnerMostAxes(l.length,a),o.push(c)),C.assertAxesAreInnerMostDims(r,l,a);let[p,d]=C.computeOutAndReduceShapes(c.shape,l),h=p;n&&(h=C.expandShapeToKeepDim(p,i));let f;if((r==="max"||r==="prod")&&s.shouldExecuteOnCPU([c])){let m=s.tensorMap.get(c.dataId).values;switch(r){case"max":let g=$de(m,w.sizeFromShape(d),h,e.dtype);f=s.makeTensorInfo(h,e.dtype,g);break;case"prod":let{outVals:y,outShape:x,outDtype:A}=zde(c.shape,c.dtype,m,l);f=s.makeTensorInfo(x,A,y);break;default:throw new Error(`${r} CPU implementation is not yet supported.`)}}else{let m=w.sizeFromShape(d),y=w.sizeFromShape(c.shape)/m,x={windowSize:m,inSize:m,batchSize:y,outSize:1},A=r==="mean"?"float32":gp(e.dtype),b=[{type:"int32",data:[m]}],v=new lhe(x,r),S=s.runWebGPUProgram(v,[c],A,b);o.push(S),f=qe({inputs:{x:S},attrs:{shape:h},backend:s})}return o.forEach(m=>s.disposeData(m.dataId)),f}function T3(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r;return qp(s,a,o,"sum",n)}var uhe={kernelName:zo,backendName:"webgpu",kernelFunc:T3};function che(e){let{inputs:t,backend:n,attrs:r}=e,{equation:s}=r,a=t,{allDims:o,summedDims:i,idDims:l}=C.decodeEinsumEquation(s,a.length);C.checkEinsumDimSizes(o.length,l,a);let{path:u,steps:c}=C.getEinsumComputePath(i,l),p=c.length,d=null,h=o.length,f=[];for(let m=0;m<p;++m){for(let g of c[m]){let{permutationIndices:y,expandDims:x}=C.getEinsumPermutation(h,l[g]),A;C.isIdentityPermutation(y)?A=a[g]:(A=Qs({inputs:{x:a[g]},backend:n,attrs:{perm:y}}),f.push(A));let b=A.shape.slice();for(let v=0;v<x.length;++v)b.splice(x[v],0,1);w.arraysEqual(A.shape,b)||(A=qe({inputs:{x:A},backend:n,attrs:{shape:b}}),f.push(A)),d===null?d=A:(d=q8({inputs:{a:A,b:d},backend:n}),f.push(d))}m<p-1&&(u[m]>=0&&(d=T3({inputs:{x:d},backend:n,attrs:{axis:u[m]-(o.length-h),keepDims:!1}}),f.push(d)),h--)}for(let m of f)m!==d&&n.disposeData(m.dataId);return d}var dhe={kernelName:np,backendName:"webgpu",kernelFunc:che},phe=wn({opType:4}),hhe={kernelName:uo,backendName:"webgpu",kernelFunc:phe},fhe=Zn({opSnippet:4,dtype:"bool",cpuKernelImpl:vde}),mhe={kernelName:Zi,backendName:"webgpu",kernelFunc:fhe},X8=wn({opType:5,cpuKernelImpl:wde,dtype:"float32"}),ghe={kernelName:co,backendName:"webgpu",kernelFunc:X8};function iy(e){let{inputs:t,attrs:n,backend:r}=e,{dim:s}=n,{input:a}=t,o=a.shape.length,i=a.shape.slice(),l=s;return s<0&&(w.assert(-(o+1)<=s,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),l=o+s+1),i.splice(l,0,1),qe({inputs:{x:a},backend:r,attrs:{shape:i}})}var yhe={kernelName:Yi,backendName:"webgpu",kernelFunc:iy},Ahe=wn({opType:6,cpuKernelImpl:kde}),xhe={kernelName:Ji,backendName:"webgpu",kernelFunc:Ahe},bhe=class{constructor(e){this.variableNames=[],this.outputShape=[],this.uniforms="value : f32,",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="fill"}getUserCode(){return`
|
|
${Qe()}
|
|
if (index < uniforms.size) {
|
|
setOutputAtIndex(index, uniforms.value);
|
|
}
|
|
}
|
|
`}};function Dc(e){let{backend:t,attrs:n}=e,{shape:r,value:s}=n,{dtype:a}=n;if(a=a||w.inferDtype(s),a==="string"){let o=w.getArrayFromDType(a,w.sizeFromShape(r));return o.fill(s),t.makeTensorInfo(r,a,o)}else{let o=new bhe(r),i=[{type:"float32",data:[s]}];return t.runWebGPUProgram(o,[],a,i)}}var vhe={kernelName:Ku,backendName:"webgpu",kernelFunc:Dc},whe=class{constructor(e){this.outputShape=[],this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="flipLeftRight"}getUserCode(){return`
|
|
${Qe()}
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
let coordX = uniforms.xShape[2] - coords[2] - 1;
|
|
let outputValue = getX(coords[0], coords[1], coordX, coords[3]);
|
|
setOutputAtIndex(index, outputValue);
|
|
}
|
|
}
|
|
`}},khe={kernelName:Qi,backendName:"webgpu",kernelFunc:({inputs:e,backend:t})=>{let{image:n}=e,r=t,s=new whe(n.shape);return r.runWebGPUProgram(s,[n],n.dtype)}},She=wn({opType:7,cpuKernelImpl:Sde}),Ihe={kernelName:po,backendName:"webgpu",kernelFunc:She},Che=Zn({opSnippet:12,dtype:"int32"}),The={kernelName:ho,backendName:"webgpu",kernelFunc:Che},Nhe=(e,t,n,r,s)=>{let a=[r,...n];return s&&a.push(s),e.createBindGroup({layout:t,entries:a.map((o,i)=>({binding:i,resource:o}))})},K8=(e,t,n,r,s,a=!1)=>{let o={dtype:s.dtype,shape:s.shape},i=Jce(r,o,t,a),l=e.createShaderModule({code:i,label:t.constructor.name});return e.createComputePipeline({layout:n,compute:{module:l,entryPoint:"main"},label:t.constructor.name})};function Z8(e,t,n,r="",s=""){return e.shaderKey+"_"+(e.workGroupSize?e.workGroupSize.join(","):"")+t.map(o=>o.length).join(",")+n.join(",")+e.variableNames.join(",")+r+s}function h4(e){let{externalImage:t,backend:n,attrs:r,outShape:s,useImport:a}=e,{numChannels:o}=r,i=w.sizeFromShape(s),l=w.computeStrides(s),u=n.makeTensorInfo(s,"int32"),c=n.getFromPixelsProgram(a?"import":"copyExternal");c.updateOutputShape(s);let p=[u.shape],d=[u.dtype,a?"import":"copyExternal"],h=Z8(c,p,d),f=c.getLayout(n.device),m=n.getAndSavePipeline(h,()=>K8(n.device,c,f.pipelineLayout,[],u,!0));c.setPipeline(m),a||n.queue.copyExternalImageToTexture({source:t,origin:{x:0,y:0}},{texture:c.makeInputTexture(n.device,s[1],s[0])},[s[1],s[0]]);let g=n.tensorMap.get(u.dataId);g.bufferInfo.buffer=n.acquireBuffer(g.bufferInfo.byteSize);let y=[i,o,...l,...c.dispatch];c.setUniform(n.device,y);let x;if(a){let A={source:t};x=n.device.importExternalTexture(A)}else x=c.inputTexture.createView();return n.runFromPixelsProgram(c,g.bufferInfo.buffer,f,x,u.dataId),u}var Ehe={kernelName:Md,backendName:"webgpu",kernelFunc:Rhe},pu;function Rhe(e){let{inputs:t,backend:n,attrs:r}=e,{pixels:s}=t,{numChannels:a}=r;if(s==null)throw new Error("pixels passed to tf.browser.fromPixels() can not be null");let o=typeof HTMLVideoElement!="undefined"&&s instanceof HTMLVideoElement,i=typeof HTMLImageElement!="undefined"&&s instanceof HTMLImageElement,l=typeof HTMLCanvasElement!="undefined"&&s instanceof HTMLCanvasElement||typeof OffscreenCanvas!="undefined"&&s instanceof OffscreenCanvas,u=typeof ImageBitmap!="undefined"&&s instanceof ImageBitmap,[c,p]=o?[s.videoWidth,s.videoHeight]:[s.width,s.height],d=[p,c,a];if(Y().getBool("WEBGPU_USE_IMPORT")&&o)return h4({externalImage:s,backend:n,attrs:r,outShape:d,useImport:!0});if((o||i)&&(pu==null&&(pu=document.createElement("canvas").getContext("2d")),pu.canvas.width=c,pu.canvas.height=p,pu.drawImage(s,0,0,c,p),s=pu.canvas),u||l||o||i)return h4({externalImage:s,backend:n,attrs:r,outShape:d,useImport:!1});let h=s.data,f=h;if(a!=null&&a!==4){f=new Uint8Array(s.width*s.height*a);let y=h.length,x=0;for(let A=0;A<y;A++)A%4<a&&(f[x++]=h[A])}let m=n.makeTensorInfo(d,"int32"),g=n.tensorMap.get(m.dataId);return g.values=new Int32Array(f),n.maybeReleaseBuffer(m.dataId),n.uploadToGPU(m.dataId),m}var _he=class{constructor(e,t,n,r,s){this.uniforms="varianceEpsilon : f32,",this.workGroupSize=[128,1,1],this.size=!0,this.variableNames=["x","mean","variance"],C.assertAndGetBroadcastShape(e,t),C.assertAndGetBroadcastShape(e,n),this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize),r!=null&&(C.assertAndGetBroadcastShape(e,r),this.variableNames.push("offset")),s!=null&&(C.assertAndGetBroadcastShape(e,s),this.variableNames.push("scale")),this.offsetShape=r,this.scaleShape=s,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)"),`
|
|
${Qe()}
|
|
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)));
|
|
}
|
|
}
|
|
`}},$he={kernelName:fo,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:r,scale:s,offset:a,mean:o,variance:i}=e,{varianceEpsilon:l}=t,u=n,c=[r,o,i],p=null;a!=null&&(p=a.shape,c.push(a));let d=null;s!=null&&(d=s.shape,c.push(s));let h=new _he(r.shape,o.shape,i.shape,p,d),f=[{type:"float32",data:[l]}];return u.runWebGPUProgram(h,c,r.dtype,f)}};function Dhe(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:u,dataFormat:c,dilations:p,dimRoundingMode:d,activation:h,leakyreluAlpha:f}=r,m=C.convertConv2DDataFormat(c),g=C.computeConv2DInfo(s.shape,a.shape,l,p,u,d,!1,m);return U8({x:s,filter:a,convInfo:g,backend:n,bias:o,preluActivationWeights:i,leakyreluAlpha:f,activation:h})}var Phe={kernelName:Fa,backendName:"webgpu",kernelFunc:Dhe};function Fhe(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:u,dilations:c,dimRoundingMode:p,activation:d,leakyreluAlpha:h}=r,f=c;f==null&&(f=[1,1]),w.assert(C.eitherStridesOrDilationsAreOne(l,f),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${f}'`);let m=C.computeConv2DInfo(s.shape,a.shape,l,f,u,p,!0),g=[s,a],y=o!=null,x=i!=null;y&&g.push(o),x&&g.push(i);let A=[{type:"int32",data:[m.padInfo.top,m.padInfo.left]},{type:"int32",data:[m.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 H8(m,y,d,x):(b=new j8(m,y,d,x),A.push({type:"int32",data:[m.filterHeight]},{type:"int32",data:[m.filterWidth]},{type:"int32",data:[m.outChannels/m.inChannels]})),d==="leakyrelu"&&(A.push({type:"float32",data:[h]}),b.uniforms+=" alpha : f32,"),n.runWebGPUProgram(b,g,"float32",A)}var Ohe={kernelName:Oa,backendName:"webgpu",kernelFunc:Fhe},Mhe=class{constructor(e,t){this.variableNames=["A","indices"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey=`gathernd_${e}`,this.sliceDim=e,this.uniforms=`sliceDim : i32, strides : ${yn(e)},`}getUserCode(){let e;return this.sliceDim>1?e="uniforms.strides[j]":e="uniforms.strides",`
|
|
${Qe()}
|
|
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 zhe(e){let{inputs:t,backend:n}=e,{params:r,indices:s}=t,a=s.shape,o=a[a.length-1],i=w.sizeFromShape(r.shape),[l,u,c,p]=C.prepareAndValidate(r,s),d=qe({inputs:{x:s},backend:n,attrs:{shape:[u,o]}}),h=qe({inputs:{x:r},backend:n,attrs:{shape:[w.sizeFromShape(r.shape)/c,c]}});if(n.shouldExecuteOnCPU([r,s])||r.dtype==="string"){let x=n.readSync(s.dataId),A=n.bufferSync(r),b=Ide(x,A,r.dtype,u,o,c,p,r.shape,i);return n.makeTensorInfo(l,r.dtype,b.values)}let f=new Mhe(o,[u,c]),m=[{type:"int32",data:[o]},{type:"int32",data:p}],g=n.runWebGPUProgram(f,[h,d],h.dtype,m),y=qe({inputs:{x:g},backend:n,attrs:{shape:l}});return n.disposeData(d.dataId),n.disposeData(h.dataId),n.disposeData(g.dataId),y}var Lhe={kernelName:tl,backendName:"webgpu",kernelFunc:zhe},Bhe=class{constructor(e,t){this.variableNames=["A","indices"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e.slice(),this.aShape=e,this.outputShape=t,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="gather"}getUserCode(){let e=Whe(this.aShape);return`
|
|
${Qe()}
|
|
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 Whe(e){let t=["resRC.x","resRC.y","resRC.z","resRC.w"],n=[];for(let r=0;r<e.length;r++)r===2?n.push("indexZ"):n.push(`${t[r]}`);return n.join()}function Y8(e){let{inputs:t,backend:n,attrs:r}=e,{x:s,indices:a}=t,{axis:o,batchDims:i}=r,l=w.parseAxisParam(o,s.shape)[0],u=C.segment_util.collectGatherOpShapeInfo(s,a,l,i),c=w.sizeFromShape(a.shape),p=[],d=qe({inputs:{x:s},backend:n,attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]}}),h=qe({inputs:{x:a},backend:n,attrs:{shape:[u.batchSize,c/u.batchSize]}});p.push(d),p.push(h);let f=[u.batchSize,u.outerSize,c/u.batchSize,u.sliceSize];if(n.shouldExecuteOnCPU([s,a])){let A=n.tensorMap.get(h.dataId).values,b=We(h.shape,h.dtype,A),S=n.tensorMap.get(d.dataId).values,I=We(d.shape,d.dtype,S),E=Cde(I,b,f);return p.forEach(R=>n.disposeData(R.dataId)),n.makeTensorInfo(u.outputShape,E.dtype,E.values)}let m=new Bhe(d.shape,f),g=n.runWebGPUProgram(m,[d,h],d.dtype);p.push(g);let y=qe({inputs:{x:g},backend:n,attrs:{shape:u.outputShape}});return p.forEach(x=>n.disposeData(x.dataId)),y}var Vhe={kernelName:el,backendName:"webgpu",kernelFunc:Y8},Uhe=Zn({opSnippet:5,cpuKernelImpl:Nde,dtype:"bool"}),Ghe={kernelName:nl,backendName:"webgpu",kernelFunc:Uhe},Hhe=Zn({opSnippet:6,dtype:"bool",cpuKernelImpl:Tde}),jhe={kernelName:mo,backendName:"webgpu",kernelFunc:Hhe};function qhe(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{alpha:a}=r,o=[{type:"float32",data:[a]}],i=new Hp(s.shape,14);return i.uniforms="alpha : f32,",n.runWebGPUProgram(i,[s],"float32",o)}var Xhe={kernelName:yo,backendName:"webgpu",kernelFunc:qhe},Khe=Zn({opSnippet:7,dtype:"bool",cpuKernelImpl:Rde}),Zhe={kernelName:rl,backendName:"webgpu",kernelFunc:Khe},Yhe=Zn({opSnippet:8,dtype:"bool",cpuKernelImpl:Ede}),Jhe={kernelName:sl,backendName:"webgpu",kernelFunc:Yhe},Qhe=wn({opType:9,cpuKernelImpl:_de}),efe={kernelName:Ao,backendName:"webgpu",kernelFunc:Qhe},tfe=Zn({opSnippet:9,dtype:"bool"}),nfe={kernelName:al,backendName:"webgpu",kernelFunc:tfe},rfe=wn({opType:10}),sfe={kernelName:ec,backendName:"webgpu",kernelFunc:rfe};function J8(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reductionIndices:a,keepDims:o}=r;return qp(s,a,o,"max",n)}var afe={kernelName:xo,backendName:"webgpu",kernelFunc:J8},ofe=Zn({opSnippet:15,cpuKernelImpl:Dde}),ife={kernelName:bo,backendName:"webgpu",kernelFunc:ofe};function lfe(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{filterSize:a,strides:o,pad:i,dimRoundingMode:l}=r,u=1,c=C.computePool2DInfo(s.shape,a,o,u,i,l),p,d=[];if(c.filterHeight===1&&c.filterWidth===1){if(w.arraysEqual(c.inShape,c.outShape))return Or({inputs:{x:s},backend:n});p=new B8(c),d.push({type:"int32",data:[c.strideHeight,c.strideWidth]})}else p=new L8(c,"max"),d.push({type:"int32",data:[c.strideHeight,c.strideWidth]},{type:"int32",data:[c.padInfo.top,c.padInfo.left]},{type:"int32",data:[c.dilationHeight,c.dilationWidth]},{type:"int32",data:[c.inHeight,c.inWidth]},{type:"int32",data:[c.effectiveFilterHeight,c.effectiveFilterWidth]});return n.runWebGPUProgram(p,[s],s.dtype,d)}var ufe={kernelName:vo,backendName:"webgpu",kernelFunc:lfe};function cfe(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{keepDims:a,axis:o}=r;return qp(s,o,a,"mean",n)}var dfe={kernelName:wo,backendName:"webgpu",kernelFunc:cfe};function pfe(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r;return qp(s,a,o,"min",n)}var hfe={kernelName:ko,backendName:"webgpu",kernelFunc:pfe},ffe=Zn({opSnippet:16,cpuKernelImpl:Pde}),mfe={kernelName:So,backendName:"webgpu",kernelFunc:ffe},gfe=class{constructor(e,t,n){this.uniforms="",this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t.map((r,s)=>r[0]+e[s]+r[1]),this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.xShape=e,t.map((r,s)=>{this.uniforms+=` pad${s} : vec2<i32>,`}),this.offset=n==="reflect"?0:1,this.shaderKey=`mirrorPad_${n}`}getUserCode(){let e=this.xShape.length,t=this.xShape.map((l,u)=>`uniforms.pad${u}[0]`).join(","),n=this.xShape.map((l,u)=>`uniforms.pad${u}[0] + uniforms.xShape${e>1?`[${u}]`:""}`).join(","),r=e===1?"start":"start[i]",s=e===1?"end":"end[i]",a=e===1?"outC":"outC[i]",o=yn(e),i=e>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,e):"coords";return`
|
|
${Qe()}
|
|
if (index < uniforms.size) {
|
|
let start = ${o}(${t});
|
|
let end = ${o}(${n});
|
|
var outC = getCoordsFromIndex(index);
|
|
for (var i = 0; i < ${e}; i = i + 1) {
|
|
if (${a} < ${r}) {
|
|
${a} = ${r} * 2 - ${a} - ${this.offset};
|
|
} else if(${a} >= ${s}) {
|
|
${a} = (${s} - 1) * 2 - ${a} + ${this.offset};
|
|
}
|
|
}
|
|
let coords = outC - start;
|
|
setOutputAtIndex(index, getX(${i}));
|
|
}
|
|
}
|
|
`}},yfe={kernelName:Io,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:r}=e,{paddings:s,mode:a}=t,o=n,i=s.map(c=>({type:"int32",data:[c[0],c[1]]})),l=new gfe(r.shape,s,a);return o.runWebGPUProgram(l,[r],r.dtype,i)}};function Afe(e){let{inputs:t,backend:n}=e,{x:r}=t;if(n.shouldExecuteOnCPU([r])){let a=n.tensorMap.get(r.dataId),[o,i]=Ode(a.values,r.shape,r.dtype);return n.makeTensorInfo(i,r.dtype,o)}let s=new Hp(r.shape,11);return n.runWebGPUProgram(s,[r],r.dtype)}var xfe={kernelName:ol,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:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:l}=r,u=n.readSync(s.dataId),c=n.readSync(a.dataId),{selectedIndices:p}=Kr.nonMaxSuppressionV3Impl(u,c,o,i,l);return n.makeTensorInfo([p.length],"int32",new Int32Array(p))}var vfe={kernelName:ll,backendName:"webgpu",kernelFunc:bfe};function wfe(e){console.warn("tf.nonMaxSuppression() in webgpu locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:r}=e,{boxes:s,scores:a}=t,{maxOutputSize:o,iouThreshold:i,scoreThreshold:l,softNmsSigma:u}=r,c=n.readSync(s.dataId),p=n.readSync(a.dataId),d=o,h=i,f=l,m=u,{selectedIndices:g,selectedScores:y}=Kr.nonMaxSuppressionV5Impl(c,p,d,h,f,m);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var kfe={kernelName:ul,backendName:"webgpu",kernelFunc:wfe};function Hf(e){let{inputs:t,backend:n}=e,{x:r}=t;if(r.dtype==="complex64"){let s=jp({inputs:{input:r},backend:n}),a=Hf({inputs:{x:s},backend:n}),o=N0({inputs:{input:r},backend:n}),i=Hf({inputs:{x:o},backend:n}),l=_c({inputs:{real:a,imag:i},backend:n});return n.disposeData(s.dataId),n.disposeData(a.dataId),n.disposeData(o.dataId),n.disposeData(i.dataId),l}else return Dc({attrs:{shape:r.shape,dtype:r.dtype,value:r.dtype==="string"?"":0},backend:n})}var Sfe={kernelName:Tl,backendName:"webgpu",kernelFunc:Hf};function Q8(e){let{inputs:t,backend:n}=e,{x:r}=t;if(r.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(r.dtype==="complex64"){let s=jp({inputs:{input:r},backend:n}),a=Q8({inputs:{x:s},backend:n}),o=N0({inputs:{input:r},backend:n}),i=Hf({inputs:{x:o},backend:n}),l=_c({inputs:{real:a,imag:i},backend:n});return n.disposeData(s.dataId),n.disposeData(a.dataId),n.disposeData(o.dataId),n.disposeData(i.dataId),l}else return Dc({attrs:{shape:r.shape,dtype:r.dtype,value:1},backend:n})}var Ife={kernelName:cl,backendName:"webgpu",kernelFunc:Q8};function Cfe(e){let{inputs:t,backend:n,attrs:r}=e,{axis:s}=r;if(t.length===1)return iy({inputs:{input:t[0]},backend:n,attrs:{dim:s}});let a=t[0].shape,o=t[0].dtype;t.forEach(c=>{w.assertShapesMatch(a,c.shape,"All tensors passed to stack must have matching shapes"),w.assert(o===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=t.map(c=>{let p=iy({inputs:{input:c},backend:n,attrs:{dim:s}});return i.push(p),p}),u=V8({inputs:l,backend:n,attrs:{axis:s}});return i.forEach(c=>n.disposeData(c.dataId)),u}var Tfe={kernelName:pl,backendName:"webgpu",kernelFunc:Cfe},Nfe=class{constructor(e,t){this.variableNames=["x"],this.uniforms="constantValue : f32,",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t.map((n,r)=>n[0]+e[r]+n[1]),this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize),t.map((n,r)=>{this.uniforms+=` pad${r} : vec2<i32>,`}),this.xShape=e,this.shaderKey="pad"}getUserCode(){let e=this.xShape.length,t=yn(e),n=this.xShape.map((c,p)=>`uniforms.pad${p}[0]`).join(","),r=this.xShape.map((c,p)=>`uniforms.pad${p}[0] + uniforms.xShape${e>1?`[${p}]`:""}`).join(","),s=e>1?`${t}(${n})`:`${n}`,a=e>1?`${t}(${r})`:`${r}`,o=e>1?"any(outC < start)":"outC < start",i=e>1?"any(outC >= end)":"outC >= end",l=e>1?["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,e):"coords";return`
|
|
${Qe()}
|
|
if (index < uniforms.size) {
|
|
let start = ${s};
|
|
let end = ${a};
|
|
let outC = getCoordsFromIndex(index);
|
|
|
|
if (${o} || ${i}) {
|
|
setOutputAtIndex(index, uniforms.constantValue);
|
|
} else {
|
|
let coords = outC - start;
|
|
setOutputAtIndex(index, getX(${l}));
|
|
}
|
|
}
|
|
}
|
|
`}},eC=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{paddings:a,constantValue:o}=r;if(a.every(u=>w.arraysEqual(u,[0,0])))return Or({inputs:{x:s},backend:n});if(w.sizeFromShape(s.shape)===0){let u=a.map((c,p)=>c[0]+s.shape[p]+c[1]);return Dc({backend:n,attrs:{shape:u,value:o,dtype:s.dtype}})}let i=[{type:"float32",data:[o]}];a.map(u=>i.push({type:"int32",data:[u[0],u[1]]}));let l=new Nfe(s.shape,a);return n.runWebGPUProgram(l,[s],s.dtype,i)},Efe={kernelName:To,backendName:"webgpu",kernelFunc:eC},Rfe=Zn({opSnippet:13}),_fe={kernelName:No,backendName:"webgpu",kernelFunc:Rfe};function $fe(e){let{inputs:t,backend:n}=e,{x:r,alpha:s}=t,a=new M8(14,r.shape,s.shape);return n.runWebGPUProgram(a,[r,s],"float32")}var Dfe={kernelName:Eo,backendName:"webgpu",kernelFunc:$fe};function Pfe(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,keepDims:o}=r;return qp(s,a,o,"prod",n)}var Ffe={kernelName:Ro,backendName:"webgpu",kernelFunc:Pfe},Ofe=e=>{let{backend:t,attrs:n}=e,{start:r,stop:s,step:a,dtype:o}=n,i=Lde(r,s,a,o);return t.makeTensorInfo([i.length],o,i)},Mfe={kernelName:rc,backendName:"webgpu",kernelFunc:Ofe},tC=Zn({opSnippet:3}),zfe={kernelName:lo,backendName:"webgpu",kernelFunc:tC},Lfe=wn({opType:12}),Bfe={kernelName:_o,backendName:"webgpu",kernelFunc:Lfe},Wfe=wn({opType:13}),Vfe={kernelName:Do,backendName:"webgpu",kernelFunc:Wfe},Ufe=class{constructor(e,t,n){this.variableNames=["x"],this.uniforms="adjustHeightWidth : vec2<f32>, halfPixelCenters : f32,",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=[e[0],t,n,e[3]],this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.shaderKey="resizeBilinear"}getUserCode(){return`
|
|
${Qe()}
|
|
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 Gfe(e){let{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,size:o,halfPixelCenters:i}=r,[l,u]=o,c=a&&l>1?1:0,p=a&&u>1?1:0,h=[{type:"float32",data:[c,p]},{type:"float32",data:[i?.5:0]}],f=new Ufe(s.shape,l,u);return n.runWebGPUProgram(f,[s],"float32",h)}var Hfe={kernelName:$o,backendName:"webgpu",kernelFunc:Gfe},jfe=class{constructor(e,t,n,r){this.variableNames=["x"],this.uniforms="adjustHeightWidth : vec2<f32>, roundBase : f32,",this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=[e[0],t,n,e[3]],this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.halfPixelCenters=r,this.shaderKey=`resizeNearest_${r}`}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",`
|
|
${Qe()}
|
|
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 qfe(e){let{inputs:t,backend:n,attrs:r}=e,{images:s}=t,{alignCorners:a,halfPixelCenters:o,size:i}=r,[l,u]=i,c=a&&l>1?1:0,p=a&&u>1?1:0,h=[{type:"float32",data:[c,p]},{type:"float32",data:[a?.5:0]}],f=new jfe(s.shape,l,u,o);return n.runWebGPUProgram(f,[s],s.dtype,h)}var Xfe={kernelName:ac,backendName:"webgpu",kernelFunc:qfe},Kfe=class{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(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`
|
|
${Qe()}
|
|
|
|
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);
|
|
}
|
|
}
|
|
`}},Zfe={kernelName:Nl,backendName:"webgpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:r}=e,{radians:s,fillValue:a,center:o}=t,i=n,l=new Kfe(r.shape,a),[u,c]=C.getImageCenter(o,r.shape[1],r.shape[2]),p=[{type:"float32",data:[u]},{type:"float32",data:[c]},{type:"float32",data:[Math.sin(s)]},{type:"float32",data:[Math.cos(s)]}];return typeof a=="number"?p.push({type:"float32",data:[Number.parseFloat(a.toFixed(2))]}):p.push({type:"float32",data:a}),i.runWebGPUProgram(l,[r],r.dtype,p)}},Yfe=wn({opType:15,cpuKernelImpl:Bde}),Jfe={kernelName:Po,backendName:"webgpu",kernelFunc:Yfe},Qfe=class{constructor(e,t,n,r,s,a,o){this.variableNames=["updates","indices"],this.workGroupSize=[64,1,1],this.atomic=!0,this.outputShape=a,this.type=o,this.dispatchLayout=Xe(e),this.dispatch=Oe(this.dispatchLayout,e,this.workGroupSize),this.sliceDimGreaterThanOne=t>1,this.shaderKey=`scatter_${n}_${r}_${this.sliceDimGreaterThanOne}_${o}`;let i=yn(s.length);this.uniforms=`sliceDim : i32, strides: ${i}, size: i32,`,this.updatesRank=r,this.indicesRank=n}getUserCode(){let e="";this.indicesRank===1?e="coords[0]":this.indicesRank===2&&(e="coords[0], j");let t=`getIndices(${e})`,n=this.sliceDimGreaterThanOne?"uniforms.strides[j]":"uniforms.strides",r="",s="",a="";this.updatesRank===1?(r="coords[0]",s="flattenedIndex",a=`
|
|
fn getUpdatesCoordsFromFlatIndex(index : i32) -> i32 {
|
|
return index;
|
|
}
|
|
`):this.updatesRank===2&&(r="coords[0], coords[1]",s="vec2<i32>(flattenedIndex, coords[1])",a=`
|
|
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 o=`getUpdates(${r})`,i=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`
|
|
${a}
|
|
|
|
${Qe()}
|
|
|
|
if (index < uniforms.size) {
|
|
let coords = getUpdatesCoordsFromFlatIndex(index);
|
|
var flattenedIndex = 0;
|
|
for (var j = 0; j < uniforms.sliceDim; j = j + 1) {
|
|
let indexInside = i32(round(${t}));
|
|
flattenedIndex = flattenedIndex + indexInside * ${n};
|
|
}
|
|
let updateValue = ${o};
|
|
let flatIndex = getOutputIndexFromCoords(${s});
|
|
|
|
${i}
|
|
}
|
|
}`}};function eme(e){let{inputs:t,backend:n,attrs:r}=e,{indices:s,updates:a}=t,{shape:o}=r,{sliceRank:i,numUpdates:l,sliceSize:u,strides:c,outputSize:p}=C.calculateShapes(a,s,o),d=[p/u,u];if(p===0)return n.makeTensorInfo(o,s.dtype);let h=qe({inputs:{x:s},backend:n,attrs:{shape:[l,i]}}),f=qe({inputs:{x:a},backend:n,attrs:{shape:[l,u]}}),m=f.dtype,g=Dc({backend:n,attrs:{shape:d,value:0,dtype:m}}),y=w.sizeFromShape(f.shape),x=[{type:"int32",data:[i]},{type:"int32",data:c},{type:"int32",data:[y]}],A=new Qfe(f.shape,i,h.shape.length,f.shape.length,c,d,m),b=n.runWebGPUProgram(A,[f,h],m,x,g),v=qe({inputs:{x:b},backend:n,attrs:{shape:o}});return n.disposeData(h.dataId),n.disposeData(f.dataId),n.disposeData(b.dataId),v}var tme={kernelName:gl,backendName:"webgpu",kernelFunc:eme},nme=class{constructor(e,t,n){this.variableNames=["c","a","b"],this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=t,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.cRank=e,this.rank=n,this.shaderKey="select"}getUserCode(){let e,t;if(this.rank>4)throw Error(`Where for rank ${this.rank} is not yet supported`);if(this.rank===1)t="resRC",e="resRC";else{let r=["resRC.x","resRC.y","resRC.z","resRC.w"],s=[],a=[];for(let o=0;o<this.outputShape.length;o++)a.push(`${r[o]}`),o<this.cRank&&s.push(`${r[o]}`);e=s.join(),t=a.join()}return`
|
|
${Qe()}
|
|
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 rme(e){let{inputs:t,backend:n}=e,{condition:r,t:s,e:a}=t,o=new nme(r.shape.length,s.shape,s.shape.length);return n.runWebGPUProgram(o,[r,s,a],Nn(s.dtype,a.dtype))}var sme={kernelName:yl,backendName:"webgpu",kernelFunc:rme},ame=wn({opType:18}),ome={kernelName:Oo,backendName:"webgpu",kernelFunc:ame},ime=wn({opType:16}),lme={kernelName:Fo,backendName:"webgpu",kernelFunc:ime},ume=wn({opType:17}),cme={kernelName:xl,backendName:"webgpu",kernelFunc:ume},nC=Zn({opSnippet:2,cpuKernelImpl:Hde,supportsComplex:!0}),dme={kernelName:Wo,backendName:"webgpu",kernelFunc:nC};function pme(e){let{inputs:t,backend:n,attrs:r}=e,{logits:s}=t,{dim:a}=r,o=w.parseAxisParam([a],s.shape),i=J8({inputs:{x:s},backend:n,attrs:{reductionIndices:o,keepDims:!1}}),l=C.expandShapeToKeepDim(i.shape,o),u=qe({inputs:{x:i},backend:n,attrs:{shape:l}}),c=nC({inputs:{a:s,b:u},backend:n}),p=X8({inputs:{x:c},backend:n}),d=T3({inputs:{x:p},backend:n,attrs:{axis:o,keepDims:!1}}),h=qe({inputs:{x:d},backend:n,attrs:{shape:l}}),f=tC({inputs:{a:p,b:h},backend:n});return n.disposeData(i.dataId),n.disposeData(u.dataId),n.disposeData(c.dataId),n.disposeData(p.dataId),n.disposeData(d.dataId),n.disposeData(h.dataId),f}var hme={kernelName:Lo,backendName:"webgpu",kernelFunc:pme},fme=e=>{let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,paddings:o}=r;w.assert(s.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGPU backend not implemented yet");let i=a.reduce((y,x)=>y*x),l=[[0,0]];l.push(...o);for(let y=1+a.length;y<s.shape.length;++y)l.push([0,0]);let u=[],c=eC({inputs:{x:s},backend:n,attrs:{paddings:l,constantValue:0}}),p=C.getReshaped(c.shape,a,i,!1),d=C.getPermuted(p.length,a.length,!1),h=C.getReshapedPermuted(c.shape,a,i,!1),f=qe({inputs:{x:c},backend:n,attrs:{shape:p}}),m=Qs({inputs:{x:f},backend:n,attrs:{perm:d}}),g=qe({inputs:{x:m},backend:n,attrs:{shape:h}});return u.push(c),u.push(f),u.push(m),u.forEach(y=>n.disposeData(y.dataId)),g},mme={kernelName:bl,backendName:"webgpu",kernelFunc:fme},gme=class{constructor(e,t,n,r,s,a,o=!0){this.variableNames=["updates","indices","defaultValue"],this.workGroupSize=[64,1,1],this.workPerThread=4,this.size=!0,this.outputShape=a,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]);let i=t>1;this.shaderKey=`scatter_${n}_${r}_${i}`;let l=yn(s.length);this.uniforms=`updateSize : i32, sliceDim : i32, strides: ${l},`;let u="";n===1?u="i":n===2&&(u="i, j"),this.indicesSnippet=`getIndices(${u})`;let c="";r===1?c="i":r===2&&(c="i, coords[1]"),this.updatesSnippet=`getUpdates(${c})`,this.strideString=i?"uniforms.strides[j]":"uniforms.strides"}getUserCode(){return`
|
|
${Qe()}
|
|
|
|
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 yme(e){let{inputs:t,backend:n,attrs:r}=e,{sparseIndices:s,sparseValues:a,defaultValue:o}=t,{outputShape:i}=r,{sliceRank:l,numUpdates:u,strides:c,outputSize:p}=C.calculateShapes(a,s,i),d=!1,h=[{type:"int32",data:[u]},{type:"int32",data:[l]},{type:"int32",data:c}],f=new gme(u,l,s.shape.length,a.shape.length,c,[p,1],d),m=n.runWebGPUProgram(f,[a,s,o],a.dtype,h),g=qe({inputs:{x:m},backend:n,attrs:{shape:i}});return n.disposeData(m.dataId),g}var Ame={kernelName:dp,backendName:"webgpu",kernelFunc:yme};function xme(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{numOrSizeSplits:a,axis:o}=r,i=w.parseAxisParam(o,s.shape)[0],l=C.prepareSplitSize(s,a,i),u=s.shape.length,c=new Array(u).fill(0),p=s.shape.slice();return l.map(d=>{let h=[...p];h[i]=d;let f=$c({inputs:{x:s},backend:n,attrs:{begin:c,size:h}});return c[i]+=d,f})}var bme={kernelName:vl,backendName:"webgpu",kernelFunc:xme},vme=wn({opType:19}),wme={kernelName:Mo,backendName:"webgpu",kernelFunc:vme},kme={kernelName:cc,backendName:"webgpu",kernelFunc:({inputs:e,backend:t})=>{let{x:n}=e,r=t,s=new Hp(n.shape,20);return r.runWebGPUProgram(s,[n],n.dtype)}},Sme=Zn({opSnippet:11}),Ime={kernelName:Bo,backendName:"webgpu",kernelFunc:Sme},Cme=class{constructor(e){this.variableNames=["x"],this.workPerThread=1,this.workGroupSize=[64,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize,[this.workPerThread,1,1]);let t=yn(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((s,a)=>(r++,this.outputShape.length===1?`coords * uniforms.strides[${a}] + uniforms.begin[${a}]`:`coords[${r-1}] * uniforms.strides[${a}] + uniforms.begin[${a}]`)).join(",")}return`
|
|
${Qe()}
|
|
if (index < uniforms.size) {
|
|
let coords = getCoordsFromIndex(index);
|
|
setOutputAtIndex(index, getX(${t}));
|
|
}
|
|
}
|
|
`}};function Tme(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{begin:a,end:o,strides:i,beginMask:l,endMask:u,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:d}=r,{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:x,end:A,strides:b}=Mt.sliceInfo(s.shape,a,o,i,l,u,c,p,d),v;if(m)v=qe({inputs:{x:s},backend:n,attrs:{shape:f}});else if(g||y){w.assert(s.shape.length>=1,()=>`Input must have rank at least 1, got: ${s.shape.length}`);let S=Mt.computeOutShape(x,A,b),I=$c({inputs:{x:s},backend:n,attrs:{begin:x,size:S}});v=qe({inputs:{x:I},backend:n,attrs:{shape:f}}),n.disposeData(I.dataId)}else if(n.shouldExecuteOnCPU([s])){let I=n.readSync(s.dataId),E=We(s.shape,s.dtype,I),R=Ude(h,E,b,x);v=n.makeTensorInfo(f,s.dtype,R.values)}else{let I=new Cme(h),E=[{type:"int32",data:x},{type:"int32",data:b}],R=n.runWebGPUProgram(I,[s],s.dtype,E);v=qe({inputs:{x:R},backend:n,attrs:{shape:f}}),n.disposeData(R.dataId)}return v}var Nme={kernelName:wl,backendName:"webgpu",kernelFunc:Tme};function Eme(e){let{inputs:t,backend:n,attrs:r}=e,{separator:s,nGramWidths:a,leftPad:o,rightPad:i,padWidth:l,preserveShortSequences:u}=r,{data:c,dataSplits:p}=t,d=n.readSync(c.dataId),h=n.readSync(p.dataId),[f,m]=Gde(d,h,s,a,o,i,l,u);return[n.makeTensorInfo([f.length],"string",f),n.makeTensorInfo(p.shape,"int32",m)]}var Rme={kernelName:pp,backendName:"webgpu",kernelFunc:Eme},_me=wn({opType:21}),$me={kernelName:Vo,backendName:"webgpu",kernelFunc:_me},Dme=class{constructor(e,t){this.variableNames=["A"],this.workGroupSize=[64,1,1],this.size=!0;let n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=e[r]*t[r];this.outputShape=n,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.rank=this.outputShape.length,this.shaderKey="tile"}getUserCode(){let e=Pme(this.rank,"uniforms.");return`
|
|
${Qe()}
|
|
if (index < uniforms.size) {
|
|
let resRC = getCoordsFromIndex(index);
|
|
setOutputAtIndex(index, getA(${e}));
|
|
}
|
|
}
|
|
`}};function Pme(e,t=""){if(e>=5)throw Error(`Tile for rank ${e} is not yet supported`);if(e===1)return`(resRC % ${t}aShape)`;let n=["resRC.x","resRC.y","resRC.z","resRC.w"],r=[];for(let s=0;s<e;s++)r.push(`(${n[s]} % ${t}aShape[${s}])`);return r.join()}function Fme(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{reps:a}=r;if(n.shouldExecuteOnCPU([s])||s.dtype==="string"||s.shape.length>=5){let l=n.readSync(s.dataId),u=s.dtype==="string"?l.map(d=>w.decodeString(d)):l,c=We(s.shape,s.dtype,u),p=jde(c,a);return n.makeTensorInfo(p.shape,p.dtype,p.values)}let o=new Dme(s.shape,a);return n.runWebGPUProgram(o,[s],s.dtype)}var Ome={kernelName:na,backendName:"webgpu",kernelFunc:Fme},Mme=class{constructor(e){this.variableNames=["x","indices"],this.workGroupSize=[256,1,1],this.size=!0,this.outputShape=e,this.dispatchLayout=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.uniforms=`inputSize : i32, firstPass : i32, negativeInf : f32,
|
|
dir : i32, inc : i32,`,this.shaderKey="swap"}getUserCode(){return`
|
|
${Qe()}
|
|
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=Xe(this.outputShape),this.dispatch=Oe(this.dispatchLayout,this.outputShape,this.workGroupSize),this.uniforms="inputSize : i32, firstPass : i32, k : i32,",this.shaderKey="merge"}getUserCode(){return`
|
|
${Qe()}
|
|
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 hu(e,t){t!==null&&e.disposeData(t.dataId)}function f4(e){let t=1;for(;t<e;)t*=2;return t}function Lme(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{k:a,sorted:o}=r,i=s.shape,l=i[i.length-1];if(n.shouldExecuteOnCPU([s])){let v=n.readSync(s.dataId),[S,I]=qde(v,i,s.dtype,a,o);return[n.makeTensorInfo(S.shape,S.dtype,S.values),n.makeTensorInfo(I.shape,I.dtype,I.values)]}if(a===0)return i[i.length-1]=0,[n.makeTensorInfo(i,s.dtype,[]),n.makeTensorInfo(i,"int32",[])];if(l===1)return[s,Dc({attrs:{shape:i,dtype:"int32",value:0},backend:n})];let c=w.sizeFromShape(i)/l,p=qe({inputs:{x:s},attrs:{shape:[c,l]},backend:n}),d=f4(a),h=f4(l),f=null,m=()=>f===null?[p,p]:[p,f],g=(v,S,I)=>{let E=m(),R=new Mme(I),_=[{type:"int32",data:[l]},{type:"int32",data:[f===null?1:0]},{type:"float32",data:[Number.NEGATIVE_INFINITY]},{type:"int32",data:[v]},{type:"int32",data:[S]}],D=f;f=n.runWebGPUProgram(R,E,"int32",_),hu(n,D)};for(let v=1;v<d;v*=2){let S=v*2;for(let I=v;I>=1;I/=2)g(S,I,[c,h])}for(let v=h;v>d;v/=2){let S=m(),I=new zme([c,v/2]),R=[{type:"int32",data:[l]},{type:"int32",data:[f===null?1:0]},{type:"int32",data:[d]}],P=f;f=n.runWebGPUProgram(I,S,"int32",R),hu(n,P);let _=d/2,D=_*2;for(let T=_;T>=1;T/=2)g(D,T,f.shape)}let y=f;f=$c({inputs:{x:f},backend:n,attrs:{begin:0,size:[c,a]}}),hu(n,y);let x=Y8({inputs:{x:p,indices:f},backend:n,attrs:{axis:1,batchDims:1}});hu(n,p);let A=i.slice(0,-1);A.push(a),y=f,f=qe({inputs:{x:f},attrs:{shape:A},backend:n}),hu(n,y);let b=x;return x=qe({inputs:{x},attrs:{shape:A},backend:n}),hu(n,b),[x,f]}var Bme={kernelName:Sl,backendName:"webgpu",kernelFunc:Lme},Wme=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=Xe(this.outputShape),this.dispatch=Oe(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;
|
|
}
|
|
|
|
${Qe()}
|
|
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 Vme(e){let{inputs:t,backend:n,attrs:r}=e,{image:s,transforms:a}=t,{interpolation:o,fillMode:i,fillValue:l,outputShape:u}=r,[c,p,d,h]=s.shape,[f,m]=u!=null?u:[p,d],g=[c,f,m,h],y=new Wme(g),x=o==="nearest"?1:2,A;switch(i){case"constant":A=1;break;case"reflect":A=2;break;case"wrap":A=3;break;case"nearest":A=4;break;default:A=1;break}let b=[{type:"int32",data:[x]},{type:"int32",data:[A]},{type:"float32",data:[l]}];return n.runWebGPUProgram(y,[s,a],"float32",b)}var Ume={kernelName:Il,backendName:"webgpu",kernelFunc:Vme};function Gme(e){let{inputs:t,backend:n,attrs:r}=e,{value:s}=t,{axis:a}=r;a<0&&(a+=s.shape.length);let o=s,i=o.shape.length,l=s.shape[a],u=new Array(i-1),c=0;for(let m=0;m<i;m++)m!==a&&(u[c++]=o.shape[m]);let p=[],d=new Array(i).fill(0),h=o.shape.slice();h[a]=1;let f=new Array(l);for(let m=0;m<f.length;m++){d[a]=m;let g=$c({inputs:{x:o},backend:n,attrs:{begin:d,size:h}}),y=qe({inputs:{x:g},backend:n,attrs:{shape:u}});f[m]=y,p.push(g)}return p.forEach(m=>n.disposeData(m.dataId)),f}var Hme={kernelName:Cl,backendName:"webgpu",kernelFunc:Gme},jme=[hde,Zde,Jde,tpe,ipe,upe,dpe,hpe,Ape,wpe,Spe,Npe,yde,$pe,Bpe,Gpe,jpe,Xpe,Ype,Qpe,the,she,ohe,dhe,hhe,mhe,ghe,yhe,xhe,vhe,khe,Ehe,Ihe,The,$he,Phe,Ohe,Lhe,Vhe,Ghe,jhe,gde,Rpe,Xhe,Zhe,Jhe,efe,nfe,sfe,afe,ife,ufe,dfe,hfe,mfe,yfe,ihe,xfe,vfe,kfe,xpe,Ife,Tfe,Efe,_fe,Dfe,Ffe,Mfe,bpe,zfe,Bfe,Vfe,dde,Hfe,Xfe,Zfe,Jfe,tme,sme,ome,lme,cme,gpe,Nme,Rme,hme,mme,Ame,bme,wme,kme,Ime,dme,uhe,$me,Ome,Bme,Ume,ape,Hme,Sfe];for(let e of jme)qr(e);var qme=class{constructor(e){this.device=e,this.numUsedBuffers=0,this.numFreeBuffers=0,this.freeBuffers=new Map,this.usedBuffers=new Map,this.numBytesUsed=0,this.numBytesAllocated=0}acquireUploadBuffer(e,t){return this.acquireBuffer(e,t,!0)}acquireBuffer(e,t,n=!1){let r=m4(e,t);if(this.freeBuffers.has(r)||this.freeBuffers.set(r,[]),this.usedBuffers.has(r)||this.usedBuffers.set(r,[]),this.numBytesUsed+=e,this.numUsedBuffers++,this.freeBuffers.get(r).length>0){this.numFreeBuffers--;let a=this.freeBuffers.get(r).shift();return this.usedBuffers.get(r).push(a),a}this.numBytesAllocated+=e;let s=this.device.createBuffer({mappedAtCreation:n,size:e,usage:t});return this.usedBuffers.get(r).push(s),s}releaseBuffer(e,t,n){if(this.freeBuffers.size===0)return;let r=m4(t,n);this.freeBuffers.has(r)||this.freeBuffers.set(r,[]),this.freeBuffers.get(r).push(e),this.numFreeBuffers++,this.numUsedBuffers--;let s=this.usedBuffers.get(r),a=s.indexOf(e);if(a<0)throw new Error("Cannot release a buffer that was never provided by this buffer manager");s.splice(a,1),this.numBytesUsed-=t}releaseUploadBuffer(e,t,n){e.mapAsync(GPUMapMode.WRITE).then(()=>{this.releaseBuffer(e,t,n)},r=>{})}getNumUsedBuffers(){return this.numUsedBuffers}getNumFreeBuffers(){return this.numFreeBuffers}dispose(){this.freeBuffers.forEach((e,t)=>{e.forEach(n=>{n.destroy()})}),this.usedBuffers.forEach((e,t)=>{e.forEach(n=>{n.destroy()})}),this.freeBuffers=new Map,this.usedBuffers=new Map,this.numUsedBuffers=0,this.numFreeBuffers=0,this.numBytesUsed=0,this.numBytesAllocated=0}};function m4(e,t){return`${e}_${t}`}var rC=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=Xe(this.outputShape),this.dispatch=Oe(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>"};
|
|
|
|
${Qe()}
|
|
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 n=e.createBuffer({size:t.length*4,usage:GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST});this.uniform=n}!t||t.length===this.lastUniformData.length&&t.every((n,r)=>n===this.lastUniformData[r])||(e.queue.writeBuffer(this.uniform,0,new Uint32Array(t)),this.lastUniformData=t)}makeInputTexture(e,t,n){return(!this.inputTexture||this.lastPixelSize.width!==t||this.lastPixelSize.height!==n)&&(this.inputTexture&&this.inputTexture.destroy(),this.inputTexture=e.createTexture({size:[t,n],format:"rgba8unorm",usage:GPUTextureUsage.COPY_DST|GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),this.lastPixelSize.width=t,this.lastPixelSize.height=n),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 n=e.createBindGroupLayout({entries:t}),r=e.createPipelineLayout({bindGroupLayouts:[n]});return{bindGroupLayout:n,pipelineLayout:r}}},Xme=class extends rC{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 n=e.createBindGroupLayout({entries:t}),r=e.createPipelineLayout({bindGroupLayouts:[n]});return{bindGroupLayout:n,pipelineLayout:r}}},Kme=Y().getNumber("WEBGPU_CPU_HANDOFF_SIZE_THRESHOLD"),g4=(e,t)=>{let n=e.limits.maxComputeWorkgroupsPerDimension,r=t.dispatchLayout,s=t.dispatch;if(s.every(o=>o<=n))return s;w.assert(s[0]>n&&r.y===void 0&&r.z===void 0,()=>"Dispatch size exceeds WebGPU limits in Y or Z dimension.");let a=Math.ceil(Math.sqrt(s[0]));return a>n?(a=Math.ceil(Math.cbrt(s[0])),w.assert(a<=n,()=>"Total dispatch size exceeds WebGPU maximum."),[a,a,a]):[a,a,1]},sC=class extends Ou{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,!S3())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 qme(this.device),this.tensorMap=new Zd(this,sn()),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 sC.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 n=this.tensorMap.get(e);if(n.refCount--,!t&&n.refCount>0)return!1;if(this.commandQueueOwnedIds.has(e))return this.tensorDisposalQueue.push(e),!1;this.maybeReleaseBuffer(e);let{complexTensorInfos:r}=this.tensorMap.get(e);r!=null&&(this.disposeData(r.real.dataId,!0),this.disposeData(r.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,n){if(n==="complex64"&&e!=null)throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let r={id:this.nextDataId()},s=w.sizeFromShape(t)*ry(n);return this.tensorMap.set(r,{dtype:n,values:e,bufferInfo:{byteSize:s,usage:this.defaultGpuBufferUsage()},refCount:1}),r}move(e,t,n,r,s){if(r==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");let a=w.sizeFromShape(n)*ry(r);this.tensorMap.set(e,{dtype:r,values:t,bufferInfo:{byteSize:a,usage:this.defaultGpuBufferUsage()},refCount:s})}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 rC),this.fromPixelProgram;case"import":return this.fromPixelImportProgram||(this.fromPixelImportProgram=new Xme),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 n=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()),n}convertAndCacheOnCPU(e,t){let n=this.tensorMap.get(e);return this.maybeReleaseBuffer(e),n.values=t,n.values}readSync(e){let t=this.tensorMap.get(e),{values:n}=t;if(n==null)throw new Error("WebGPU readSync is only available for CPU-resident tensors.");return n}async read(e){if(!this.tensorMap.has(e))throw new Error(`Tensor ${e} was not registered!`);let t=this.tensorMap.get(e),{values:n}=t;if(n!=null)return this.convertAndCacheOnCPU(e,n);let r;if(t.dtype==="complex64"){let s=await Promise.all([this.read(t.complexTensorInfos.real.dataId),this.read(t.complexTensorInfos.imag.dataId)]),a=s[0],o=s[1];r=C.mergeRealAndImagArrays(a,o)}else{let s=await this.getBufferData(t);r=P8(s,t.dtype)}return this.convertAndCacheOnCPU(e,r),r}bufferSync(e){let t=this.readSync(e.dataId),n=t;if(e.dtype==="string")try{n=t.map(r=>w.decodeString(r))}catch(r){throw new Error("Failed to decode encoded string bytes into utf-8")}return We(e.shape,e.dtype,n)}async time(e){let t=this.activeTimers,n=[],r=!1;this.programTimersStack==null?(this.programTimersStack=n,r=!0):this.activeTimers.push(n),this.activeTimers=n,e();let s=w.flatten(this.activeTimers.map(l=>l.query)).filter(l=>l!=null),a=w.flatten(this.activeTimers.map(l=>l.name)).filter(l=>l!=null);this.activeTimers=t,r&&(this.programTimersStack=null);let o={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null},i=await Promise.all(s);return o.kernelMs=w.sum(i),o.getExtraProfileInfo=()=>i.map((l,u)=>({name:a[u],ms:l})).map(l=>`${l.name}: ${l.ms}`).join(", "),this.uploadWaitMs=0,this.downloadWaitMs=0,o}getAndSavePipeline(e,t){return e in this.pipelineCache||(this.pipelineCache[e]=t()),this.pipelineCache[e]}makeTensorInfo(e,t,n){let r;if(t==="string"&&n!=null&&n.length>0&&w.isString(n[0])){let s=n.map(a=>w.encodeString(a));r=this.write(s,e,t)}else r=this.write(n,e,t);return{dataId:r,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 n=this.bufferManager.acquireUploadBuffer(t.bufferInfo.byteSize,GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC),r=n.getMappedRange();t.dtype==="int32"||t.dtype==="bool"?new Int32Array(r).set(t.values):new Float32Array(r).set(t.values),n.unmap(),this.ensureCommandEncoderReady(),this.ensureComputePassEnded(),this.currentCommandEncoder.copyBufferToBuffer(n,0,t.bufferInfo.buffer,0,t.bufferInfo.byteSize);let s={byteSize:t.bufferInfo.byteSize,usage:GPUBufferUsage.MAP_WRITE|GPUBufferUsage.COPY_SRC,buffer:n};this.stagingDisposalQueue.push(s)}}makeUniforms(e){let t=0,n=[];e.forEach(a=>{a.data.length===0&&(a.data=[1]);let o;switch(a.data.length){case 1:o=4;break;case 2:o=8;break;case 3:o=16;break;case 4:o=16;break;default:w.assert(!1,()=>`Unsupported ${a.data.length}D shape`)}t=Math.ceil(t/o)*o,n.push(t),t+=a.data.length*4});let r=new ArrayBuffer(t);e.forEach((a,o)=>{let i=n[o];a.type==="int32"?new Int32Array(r,i,a.data.length).set(a.data):a.type==="uint32"?new Uint32Array(r,i,a.data.length).set(a.data):new Float32Array(r,i,a.data.length).set(a.data)});let s=this.acquireBuffer(t,GPUBufferUsage.COPY_DST|GPUBufferUsage.UNIFORM);return this.queue.writeBuffer(s,0,r,0,t),{offset:0,size:t,buffer:s}}createLayout(e){let t=[];t.push({binding:0,visibility:GPUShaderStage.COMPUTE,buffer:{type:"storage"}});for(let s=0;s<e;s++)t.push({binding:s+1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"read-only-storage"}});t.push({binding:e+1,visibility:GPUShaderStage.COMPUTE,buffer:{type:"uniform"}});let n=this.device.createBindGroupLayout({entries:t}),r=this.device.createPipelineLayout({bindGroupLayouts:[n]});return{bindGroupLayout:n,pipelineLayout:r}}getCachedOrCreateLayout(e){return e in this.layoutCache||(this.layoutCache[e]=this.createLayout(e)),this.layoutCache[e]}runWebGPUProgram(e,t,n,r,s){if(!s){if(s=this.makeTensorInfo(e.outputShape,n),w.sizeFromShape(s.shape)===0){let I=this.tensorMap.get(s.dataId);return I.values=w.getTypedArrayFromDType(s.dtype,0),s}this.uploadToGPU(s.dataId)}e.dispatch=g4(this.device,e);let a=[{type:"float32",data:[NaN]}],o=t.concat(s).map(I=>I.shape),i="int32";o.map(I=>{a.push({type:i,data:I})});let l=w.computeStrides(s.shape);if(a.push({type:i,data:l}),e.size){let I=w.sizeFromShape(e.outputShape);a.push({type:i,data:[e.isVec4?I/4:I]})}r&&(a=[...a,...r]);let u=this.makeUniforms(a),c=t.map((I,E)=>{if(I.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(I.dataId),{dtype:this.tensorMap.get(I.dataId).dtype,shape:I.shape,name:e.variableNames[E]}}),p=c.map(I=>I.dtype).concat(s.dtype),d=c.map(I=>C.getBroadcastDims(I.shape,s.shape)),h=c.map(I=>w.arraysEqual(I.shape,s.shape)).join("_"),f=d.map(I=>I.join("_")).join(";"),m=Z8(e,o,p,f,h),{bindGroupLayout:g,pipelineLayout:y}=this.getCachedOrCreateLayout(e.variableNames.length),x=this.getAndSavePipeline(m,()=>K8(this.device,e,y,c,s)),A=this.activeTimers!=null,b=Nhe(this.device,g,t.map(I=>this.tensorToBinding(I)),this.tensorToBinding(s),u);this.ensureCommandEncoderReady();let v=this.getComputePass();A&&this.supportTimeQuery&&v.writeTimestamp(this.querySet,0),v.setPipeline(x),v.setBindGroup(0,b),v.dispatch(e.dispatch[0],e.dispatch[1],e.dispatch[2]),A&&this.supportTimeQuery&&v.writeTimestamp(this.querySet,1),this.dispatchNumberInEncoder++,t.forEach(I=>{this.commandQueueOwnedIds.add(I.dataId)}),this.commandQueueOwnedIds.add(s.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(),A&&this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(this.querySet)}),s}runFromPixelsProgram(e,t,n,r,s){e.dispatch=g4(this.device,e);let a=this.device.createBindGroup({layout:n.bindGroupLayout,entries:[{binding:0,resource:{buffer:t}},{binding:1,resource:r},{binding:2,resource:{buffer:e.uniform}}]});this.ensureCommandEncoderReady();let o=this.getComputePass(),i=this.activeTimers!=null;i&&this.supportTimeQuery&&o.writeTimestamp(this.querySet,0),o.setPipeline(e.pipeline),o.setBindGroup(0,a),o.dispatch(e.dispatch[0],e.dispatch[1],e.dispatch[2]),i&&this.supportTimeQuery&&o.writeTimestamp(this.querySet,1),this.commandQueueOwnedIds.add(s),this.submitQueue(),i&&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),n=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,n,0,16),this.submitQueue(),await n.mapAsync(GPUMapMode.READ);let r=new BigUint64Array(n.getMappedRange()),s=Number(r[1]-r[0]);return n.unmap(),this.bufferManager.releaseBuffer(n,16,GPUBufferUsage.MAP_READ|GPUBufferUsage.COPY_DST),this.bufferManager.releaseBuffer(t,16,GPUBufferUsage.COPY_SRC|GPUBufferUsage.QUERY_RESOLVE),s/1e6}shouldExecuteOnCPU(e,t=Kme){return Y().getBool("WEBGPU_CPU_FORWARD")&&e.every(n=>this.tensorMap.get(n.dataId).bufferInfo.buffer==null&&w.sizeFromShape(n.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)}},N3=sC;N3.nextDataId=0;var aC={};Le(aC,{WebGPUBackend:()=>N3,webgpu_util:()=>$8});S3()&&Rl("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),n=t.limits,r={},s=t.features.has("timestamp-query");r.requiredLimits={maxComputeWorkgroupStorageSize:n.maxComputeWorkgroupStorageSize,maxComputeWorkgroupsPerDimension:n.maxComputeWorkgroupsPerDimension},s?r.requiredFeatures=["timestamp-query"]:console.warn("This device doesn't support timestamp-query extension. Start Chrome browser with flag --disable-dawn-features=disallow_unsafe_apis then try again. Or zero will shown for the kernel time when profiling mode isenabled. Using performance.now is not workable for webgpu sinceit doesn't support synchronously to read data from GPU.");let a=await t.requestDevice(r);return new N3(a,s)},3);var Ut=(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))(Ut||{}),E0=(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))(E0||{}),oC;function Zme(e){oC=e.wasm.cwrap(Pa,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function Yme(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a,bias:o,preluActivationWeights:i}=t;if(s.dtype!=="float32"||a.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:l,transposeB:u,activation:c,leakyreluAlpha:p}=r,d=n.dataIdMap.get(s.dataId).id,h=n.dataIdMap.get(a.dataId).id,f=0;if(o!=null){let E=n.dataIdMap.get(o.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=i==null?0:n.dataIdMap.get(i.dataId).id,g=E0[c];if(g==null)throw new Error(`${c} activation not yet supported for FusedConv2D in the wasm backend.`);let y=l?s.shape[2]:s.shape[1],x=u?a.shape[1]:a.shape[2],A=El.assertAndGetBroadcastShape(s.shape.slice(0,-2),a.shape.slice(0,-2)),b=n.makeOutput([...A,y,x],s.dtype),v=n.dataIdMap.get(b.dataId).id,S=new Uint8Array(new Int32Array(s.shape).buffer),I=new Uint8Array(new Int32Array(a.shape).buffer);return oC(d,S,s.shape.length,h,I,a.shape.length,l,u,g,f,m,p||0,v),b}var Jme={kernelName:Pa,backendName:"wasm",setupFunc:Zme,kernelFunc:Yme};function kn(e,t){let n;function r(a){n=a.wasm.cwrap(e,null,["number","number","number"])}function s(a){let{backend:o,inputs:{x:i}}=a,l=o.dataIdMap.get(i.dataId).id,u=o.makeOutput(i.shape,t||i.dtype),c=o.dataIdMap.get(u.dataId).id;return w.sizeFromShape(u.shape)===0||n(l,Ut[i.dtype],c),u}return{kernelName:e,backendName:"wasm",setupFunc:r,kernelFunc:s}}var Qme=kn(Gi);function Yn(e,t,n){let r;function s(o){r=o.wasm.cwrap(e,null,["number","array","number","number","array","number","number","number"])}function a(o){let{backend:i,inputs:l}=o,{a:u,b:c}=l,p=i.dataIdMap.get(u.dataId).id,d=i.dataIdMap.get(c.dataId).id,h=n!=null?n:u.dtype,f=C.assertAndGetBroadcastShape(u.shape,c.shape),m=i.makeOutput(f,h);if(w.sizeFromShape(f)===0)return m;let g=new Uint8Array(new Int32Array(u.shape).buffer),y=new Uint8Array(new Int32Array(c.shape).buffer),x=i.dataIdMap.get(m.dataId).id;return(()=>r(p,g,u.shape.length,d,y,c.shape.length,Ut[u.dtype],x))(),m}return{kernelName:e,backendName:"wasm",setupFunc:s,kernelFunc:a}}var e0e=!0,t0e=Yn(ea,e0e),iC;function n0e(e){iC=e.wasm.cwrap(Za,null,["array","number","number","number"])}function r0e(e){let{inputs:t,backend:n}=e,r=n.makeOutput(t[0].shape,t[0].dtype);if(w.sizeFromShape(r.shape)===0)return r;let s=t.map(i=>n.dataIdMap.get(i.dataId).id),a=new Uint8Array(new Int32Array(s).buffer),o=n.dataIdMap.get(r.dataId).id;return iC(a,s.length,Ut[r.dtype],o),r}var s0e={kernelName:Za,backendName:"wasm",setupFunc:n0e,kernelFunc:r0e};function R0(e){let{inputs:{x:t},backend:n}=e,r=n.makeOutput(t.shape,t.dtype),s=n.typedArrayFromHeap(t);return n.typedArrayFromHeap(r).set(s),r}var a0e={kernelName:go,backendName:"wasm",kernelFunc:R0},lC;function o0e(e){lC=e.wasm.cwrap(Uo,null,["number","array","number","number","number","array","number"])}function Xa(e){let{inputs:t,backend:n,attrs:r}=e,[s,a]=l0e(t.x.shape,r.perm),o=!0;for(let f=0;f<a.length;f++)a[f]!==f&&(o=!1);let i=i0e(t.x.shape,r.perm),l={dataId:t.x.dataId,shape:s,dtype:t.x.dtype};if(o){let f=R0({inputs:t,backend:n});return f.shape=i,f}let u=n.makeOutput(i,l.dtype),c=n.dataIdMap.get(l.dataId).id,p=n.dataIdMap.get(u.dataId).id,d=new Uint8Array(new Int32Array(a).buffer),h=new Uint8Array(new Int32Array(l.shape).buffer);return lC(c,h,l.shape.length,Ut[l.dtype],p,d,a.length),u}function i0e(e,t){let n=new Array(e.length);for(let r=0;r<n.length;r++)n[r]=e[t[r]];return n}function l0e(e,t){let n=[],r=[];for(let s=0;s<e.length;++s)e[s]!==1&&n.push(e[s]),e[t[s]]!==1&&r.push(t[s]);for(let s=0;s<r.length;++s){let a=-1;for(let o=0;o<r.length;++o)r[o]>=s&&(a===-1||r[a]>r[o])&&(a=o);r[a]=s}return[n,r]}var u0e={kernelName:Uo,backendName:"wasm",kernelFunc:Xa,setupFunc:o0e};function Zo(e,t,n){let r=e.shape,s=e.shape.length,a=w.parseAxisParam(t,r),o=a,i=C.getAxesPermutation(o,s),l=null,u=!1;if(i!=null){let c=new Array(s);for(let h=0;h<c.length;h++)c[h]=r[i[h]];o=C.getInnerMostAxes(o.length,s),l=Xa({inputs:{x:e},attrs:{perm:i},backend:n});let p=n.dataIdMap.get(e.dataId).id;n.dataIdMap.get(l.dataId).id!==p&&(u=!0)}return{transposed:l,originalAxes:a,axes:o,inputWasTransposed:u}}var uC;function c0e(e){uC=e.wasm.cwrap(Bu,null,["number, number, number"])}function d0e(e){let{backend:t,inputs:n,attrs:r}=e,{axis:s,keepDims:a}=r,{x:o}=n,l=t.dataIdMap.get(o.dataId).id,u=o,{transposed:c,axes:p,originalAxes:d,inputWasTransposed:h}=Zo(o,s,t);if(h){let A=t.dataIdMap.get(c.dataId).id;u=c,l=A}let f=u.shape.length;C.assertAxesAreInnerMostDims("all",p,f);let[m,g]=C.computeOutAndReduceShapes(u.shape,p),y=w.sizeFromShape(g),x=t.makeOutput(m,o.dtype);if(w.sizeFromShape(u.shape)!==0){let A=t.dataIdMap.get(x.dataId).id;uC(l,y,A)}if(h&&t.disposeData(c.dataId),a){let A=C.expandShapeToKeepDim(x.shape,d);x.shape=A}return x}var p0e={kernelName:Bu,backendName:"wasm",setupFunc:c0e,kernelFunc:d0e},cC;function h0e(e){cC=e.wasm.cwrap(Wu,null,["number, number, number"])}function f0e(e){let{backend:t,inputs:n,attrs:r}=e,{axis:s,keepDims:a}=r,{x:o}=n,l=t.dataIdMap.get(o.dataId).id,u=o,{transposed:c,axes:p,originalAxes:d,inputWasTransposed:h}=Zo(o,s,t);if(h){let A=t.dataIdMap.get(c.dataId).id;u=c,l=A}let f=u.shape.length;C.assertAxesAreInnerMostDims("any",p,f);let[m,g]=C.computeOutAndReduceShapes(u.shape,p),y=w.sizeFromShape(g),x=t.makeOutput(m,o.dtype);if(w.sizeFromShape(u.shape)!==0){let A=t.dataIdMap.get(x.dataId).id;cC(l,y,A)}if(h&&t.disposeData(c.dataId),a){let A=C.expandShapeToKeepDim(x.shape,d);x.shape=A}return x}var m0e={kernelName:Wu,backendName:"wasm",setupFunc:h0e,kernelFunc:f0e},dC;function g0e(e){dC=e.wasm.cwrap(Ya,null,["number","number","number","number","number"])}function y0e(e){let{backend:t,inputs:n,attrs:r}=e,{axis:s}=r,{x:a}=n,o=t.dataIdMap.get(a.dataId).id,i=o,l=a,{transposed:u,axes:c,inputWasTransposed:p}=Zo(a,s,t);if(p){let y=t.dataIdMap.get(u.dataId).id;y!==o&&(l=u,i=y)}let d=l.shape.slice(0,-1),h=t.makeOutput(d,"int32"),f=t.dataIdMap.get(h.dataId).id,m=w.sizeFromShape(h.shape),g=l.shape[c[0]];return dC(i,Ut[l.dtype],m,g,f),p&&t.disposeData(u.dataId),h}var A0e={kernelName:Ya,backendName:"wasm",kernelFunc:y0e,setupFunc:g0e},pC;function x0e(e){pC=e.wasm.cwrap(Ja,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function b0e(e){let{inputs:t,attrs:n,backend:r}=e,s=t.x,a=r.dataIdMap.get(s.dataId).id,{filterSize:o,strides:i,pad:l,dimRoundingMode:u}=n,c=C.computePool2DInfo(s.shape,o,i,1,l,u),p=c.filterHeight,d=c.filterWidth,h=c.padInfo.top,f=c.padInfo.right,m=c.padInfo.bottom,g=c.padInfo.left,y=c.strideHeight,x=c.strideWidth,A=c.inChannels;if(c.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${c.dataFormat}'. Please use 'channelsLast'.`);if(c.dilationWidth!==1||c.dilationHeight!==1)throw new Error(`was backend only supports average pooling with dilation = [1, 1], got [${c.dilationHeight}, ${c.dilationWidth}].`);let b=r.makeOutput(c.outShape,"float32"),v=r.dataIdMap.get(b.dataId).id;return pC(a,s.shape[0],s.shape[1],s.shape[2],p,d,h,f,m,g,y,x,A,v),b}var v0e={kernelName:Ja,backendName:"wasm",setupFunc:x0e,kernelFunc:b0e};function nr(e){let{inputs:t,attrs:n}=e,{x:r}=t,{shape:s}=n,a=w.sizeFromShape(r.shape),o=w.inferFromImplicitShape(s,a);return w.assert(a===w.sizeFromShape(o),()=>`new shape: ${o}, old shape: ${r.shape}. New shape and old shape must have the same number of elements.`),e.backend.incRef(r.dataId),{dataId:r.dataId,shape:o,dtype:r.dtype}}var w0e={kernelName:hl,backendName:"wasm",kernelFunc:nr},hC;function k0e(e){hC=e.wasm.cwrap(Qa,null,["number","array","number","number","array","number","number","number","number"])}function S0e(e){let{inputs:t,backend:n,attrs:r}=e,{a:s,b:a}=t,{transposeA:o,transposeB:i}=r;if(s.dtype!=="float32"||a.dtype!=="float32")throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");let l=s.shape.length,u=a.shape.length,c=o?s.shape[l-2]:s.shape[l-1],p=i?a.shape[u-1]:a.shape[u-2],d=o?s.shape[l-1]:s.shape[l-2],h=i?a.shape[u-2]:a.shape[u-1],f=s.shape.slice(0,-2),m=a.shape.slice(0,-2),g=w.sizeFromShape(f),y=w.sizeFromShape(m),A=El.assertAndGetBroadcastShape(s.shape.slice(0,-2),a.shape.slice(0,-2)).concat([d,h]);w.assert(c===p,()=>`Error in matMul: inner shapes (${c}) and (${p}) of Tensors with shapes ${s.shape} and ${a.shape} and transposeA=${o} and transposeB=${i} must match.`);let b=o?[g,c,d]:[g,d,c],v=i?[y,h,p]:[y,p,h],S=nr({inputs:{x:s},backend:n,attrs:{shape:b}}),I=nr({inputs:{x:a},backend:n,attrs:{shape:v}}),E=n.dataIdMap.get(S.dataId).id,R=n.dataIdMap.get(I.dataId).id,P=o?S.shape[2]:S.shape[1],_=i?I.shape[1]:I.shape[2],D=Math.max(g,y),T=n.makeOutput([D,P,_],S.dtype),F=n.dataIdMap.get(T.dataId).id,U=new Uint8Array(new Int32Array(S.shape).buffer),X=new Uint8Array(new Int32Array(I.shape).buffer);return hC(E,U,S.shape.length,R,X,I.shape.length,o,i,F),n.disposeData(S.dataId),n.disposeData(I.dataId),T.shape=A,T}var I0e={kernelName:Qa,backendName:"wasm",setupFunc:k0e,kernelFunc:S0e};function Wi(e){let{inputs:{x:t},attrs:{begin:n,size:r},backend:s}=e,[a,o]=Mt.parseSliceParams(t,n,r),i=Mt.isSliceContinous(t.shape,a,o),l=s.readSync(t.dataId),u=s.makeOutput(o,t.dtype),c=w.computeStrides(t.shape),p=s.dataIdMap.get(u.dataId);if(i){let f=Mt.computeFlatOffset(a,c);return t.dtype==="string"?p.stringBytes=l.slice(f,f+w.sizeFromShape(o)):s.typedArrayFromHeap(u).set(l.subarray(f,f+w.sizeFromShape(o))),u}if(t.dtype==="string"){let f=Bf(l,a,o,t.shape,t.dtype);return p.stringBytes=f,u}let d=s.typedArrayFromHeap(u),h=t.shape.length;if(h===2)C0e(l,c[0],d,a,o);else if(h===3)T0e(l,c[0],c[1],d,a,o);else if(h===4)N0e(l,c[0],c[1],c[2],d,a,o);else{let f=Bf(l,a,o,t.shape,t.dtype);d.set(f)}return u}function C0e(e,t,n,r,s){let a=0,o=r[0],i=r[1],l=o+s[0];for(let u=o;u<l;u++){let c=u*t+i;n.set(e.subarray(c,c+s[1]),a),a+=s[1]}}function T0e(e,t,n,r,s,a){let o=0,i=s[0],l=s[1],u=s[2],c=i+a[0],p=l+a[1];for(let d=i;d<c;d++)for(let h=l;h<p;h++){let f=d*t+h*n+u;r.set(e.subarray(f,f+a[2]),o),o+=a[2]}}function N0e(e,t,n,r,s,a,o){let i=0,l=a[0],u=a[1],c=a[2],p=l+o[0],d=u+o[1],h=c+o[2],f=a[3];for(let m=l;m<p;m++)for(let g=u;g<d;g++)for(let y=c;y<h;y++){let x=m*t+g*n+y*r+f;s.set(e.subarray(x,x+o[3]),i),i+=o[3]}}var E0e={kernelName:Al,backendName:"wasm",kernelFunc:Wi};function R0e(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,crops:o}=r,i=a.reduce((y,x)=>y*x),l=C.getReshaped(s.shape,a,i),u=C.getPermuted(l.length,a.length),c=C.getReshapedPermuted(s.shape,a,i),p=C.getSliceBeginCoords(o,a.length),d=C.getSliceSize(c,o,a.length),h=nr({inputs:{x:s},backend:n,attrs:{shape:l}}),f=Xa({inputs:{x:h},backend:n,attrs:{perm:u}}),m=nr({inputs:{x:f},backend:n,attrs:{shape:c}}),g=Wi({inputs:{x:m},backend:n,attrs:{begin:p,size:d}});return n.disposeData(h.dataId),n.disposeData(f.dataId),n.disposeData(h.dataId),g}var _0e={kernelName:Hi,backendName:"wasm",kernelFunc:R0e};function Xp(e){let{inputs:{x:t},attrs:{dtype:n},backend:r}=e,s=r.makeOutput(t.shape,n),a=r.typedArrayFromHeap(t);return r.typedArrayFromHeap(s).set(a),s}var $0e={kernelName:eo,backendName:"wasm",kernelFunc:Xp},D0e=kn(to),fC;function P0e(e){fC=e.wasm.cwrap(ta,null,["number","number","number","number"])}function F0e(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{clipValueMin:a,clipValueMax:o}=r,i=n.dataIdMap.get(s.dataId).id,l=n.makeOutput(s.shape,s.dtype),u=n.dataIdMap.get(l.dataId).id;return fC(i,a,o,u),l}var O0e={kernelName:ta,backendName:"wasm",setupFunc:P0e,kernelFunc:F0e};function mC(e){let{inputs:t,backend:n}=e,r=w.parseAxisParam(e.attrs.axis,t[0].shape)[0],s=C.computeOutShape(t.map(h=>h.shape),r),a=t.filter(h=>w.sizeFromShape(h.shape)>0);if(a.length===1)return R0({inputs:{x:a[0]},backend:n});let o=n.makeOutput(s,t[0].dtype);if(w.sizeFromShape(s)===0)return o;let i=a.map(h=>h.shape);if(C.assertParamsConsistent(i,r),a[0].dtype==="string"){let h=a.map(A=>{let b=w.sizeFromShape(A.shape.slice(r));return nr({inputs:{x:A},backend:n,attrs:{shape:[-1,b]}})}),f=h.map(A=>({vals:n.readSync(A.dataId),shape:A.shape}));s=C.computeOutShape(h.map(A=>A.shape),1);let m=h[0].shape[0]===1,g=Jx(f,s,t[0].dtype,m),y=C.computeOutShape(a.map(A=>A.shape),r);o.shape=y;let x=n.dataIdMap.get(o.dataId);return x.stringBytes=C.fromStringArrayToUint8(g),h.forEach(A=>n.disposeData(A.dataId)),o}let l=w.sizeFromShape(a[0].shape.slice(0,r)),u=0,c=a.map(h=>{let f=w.sizeFromShape(h.shape.slice(r));return u+=f,f}),p=a.map(h=>n.typedArrayFromHeap(h)),d=n.typedArrayFromHeap(o);for(let h=0;h<l;h++){let f=h*u;for(let m=0;m<p.length;m++){let g=c[m],y=h*g,x=p[m].subarray(y,y+g);d.set(x,f),f+=g}}return o}var M0e={kernelName:ji,backendName:"wasm",kernelFunc:mC},gC;function z0e(e){gC=e.wasm.cwrap(no,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function L0e(e){let{inputs:t,attrs:n,backend:r}=e,{x:s,filter:a}=t,o=r.dataIdMap.get(s.dataId).id,i=r.dataIdMap.get(a.dataId).id,{strides:l,dilations:u,pad:c,dimRoundingMode:p,dataFormat:d}=n,h=C.convertConv2DDataFormat(d),f=C.computeConv2DInfo(s.shape,a.shape,l,u,c,p,!1,h),m=f.filterHeight,g=f.filterWidth,y=f.padInfo.top,x=f.padInfo.right,A=f.padInfo.bottom,b=f.padInfo.left,v=f.dilationHeight,S=f.dilationWidth,I=f.strideHeight,E=f.strideWidth,R=f.inChannels,P=f.outChannels,_=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 D=r.makeOutput(f.outShape,"float32"),T=r.dataIdMap.get(D.dataId).id;return gC(o,s.shape[0],s.shape[1],s.shape[2],i,m,g,y,x,A,b,_,v,S,I,E,R,P,T),D}var B0e={kernelName:no,backendName:"wasm",setupFunc:z0e,kernelFunc:L0e},yC;function W0e(e){yC=e.wasm.cwrap(ro,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function V0e(e){let{backend:t,inputs:n,attrs:r}=e,{dy:s,filter:a}=n,{strides:o,pad:i,dataFormat:l,dimRoundingMode:u,inputShape:c}=r,p=1,d=C.convertConv2DDataFormat(l),h=C.computeConv2DInfo(c,a.shape,o,p,i,u,!1,d),{batchSize:f,filterHeight:m,filterWidth:g,inChannels:y,inHeight:x,inWidth:A,outChannels:b,outHeight:v,outWidth:S,strideHeight:I,strideWidth:E}=h,R=m-1-h.padInfo.top,P=g-1-h.padInfo.left,_=h.dataFormat==="channelsLast",D=w.computeStrides(h.inShape),T=w.computeStrides(s.shape),[F,U,X]=w.computeStrides(a.shape),z=D[0],Z=_?D[1]:D[2],W=_?D[2]:1,ee=_?1:D[1],Q=T[0],ae=_?T[1]:T[2],J=_?T[2]:1,se=_?1:T[1],ie=t.makeOutput(h.inShape,"float32"),me=t.dataIdMap.get(ie.dataId).id,be=t.dataIdMap.get(s.dataId).id,Ee=t.dataIdMap.get(a.dataId).id;return yC(be,Ee,f,m,g,x,A,y,v,S,b,I,E,R,P,F,U,X,z,Z,W,ee,Q,ae,J,se,me),ie}var U0e={kernelName:ro,backendName:"wasm",setupFunc:W0e,kernelFunc:V0e},G0e=kn(so),H0e=kn(ao),AC=(e=>(e[e.bilinear=0]="bilinear",e[e.nearest=1]="nearest",e))(AC||{}),xC;function j0e(e){xC=e.wasm.cwrap(Xi,null,["number","number","number","number","array","number","number","number","number","number"])}function q0e(e){let{backend:t,inputs:n,attrs:r}=e,{method:s,extrapolationValue:a,cropSize:o}=r,{image:i,boxes:l,boxInd:u}=n,c=l.shape[0],[p,d]=o,h=[c,p,d,i.shape[3]],f=t.dataIdMap.get(i.dataId),m;i.dtype!=="float32"&&(m=Xp({backend:t,inputs:{x:i},attrs:{dtype:"float32"}}),f=t.dataIdMap.get(m.dataId));let g=f.id,y=t.dataIdMap.get(l.dataId).id,x=t.dataIdMap.get(u.dataId).id,A=t.makeOutput(h,"float32"),b=t.dataIdMap.get(A.dataId).id,v=new Uint8Array(new Int32Array(i.shape).buffer);return xC(g,y,x,c,v,p,d,AC[s],a,b),m!=null&&t.disposeData(m.dataId),A}var X0e={kernelName:Xi,backendName:"wasm",setupFunc:j0e,kernelFunc:q0e},bC;function K0e(e){bC=e.wasm.cwrap(qi,null,["number","number","number","number","number","number"])}function Z0e(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:o,reverse:i}=r,l=s.shape.length;w.assert(s.dtype==="float32"||s.dtype==="int32",()=>`cumprod does not support ${s.dtype} tensors in the WASM backend`);let u=C.getAxesPermutation([a],l),c=s;u!==null&&(c=Xa({inputs:{x:s},attrs:{perm:u},backend:n}));let p=C.getInnerMostAxes(1,l)[0];C.assertAxesAreInnerMostDims("cumprod",[p],l);let d=n.makeOutput(c.shape,c.dtype),h=c.shape[p],f=n.dataIdMap.get(c.dataId).id,m=n.dataIdMap.get(d.dataId).id;bC(f,o?1:0,i?1:0,h,m,Ut[s.dtype]);let g=d;if(u!==null){let y=C.getUndoAxesPermutation(u);g=Xa({inputs:{x:d},attrs:{perm:y},backend:n}),n.disposeData(c.dataId),n.disposeData(d.dataId)}return g}var Y0e={kernelName:qi,backendName:"wasm",setupFunc:K0e,kernelFunc:Z0e},vC;function J0e(e){vC=e.wasm.cwrap(oo,null,["number","number","number","number","number","number"])}function Q0e(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{axis:a,exclusive:o,reverse:i}=r,l=s.shape.length;w.assert(s.dtype==="float32"||s.dtype==="int32",()=>`cumsum does not support ${s.dtype} tensors in the WASM backend`);let u=C.getAxesPermutation([a],l),c=s;u!==null&&(c=Xa({inputs:{x:s},attrs:{perm:u},backend:n}));let p=C.getInnerMostAxes(1,l)[0];C.assertAxesAreInnerMostDims("cumsum",[p],l);let d=n.makeOutput(c.shape,c.dtype),h=c.shape[p],f=n.dataIdMap.get(c.dataId).id,m=n.dataIdMap.get(d.dataId).id;vC(f,o?1:0,i?1:0,h,m,Ut[s.dtype]);let g=d;if(u!==null){let y=C.getUndoAxesPermutation(u);g=Xa({inputs:{x:d},attrs:{perm:y},backend:n}),n.disposeData(c.dataId),n.disposeData(d.dataId)}return g}var e2e={kernelName:oo,backendName:"wasm",setupFunc:J0e,kernelFunc:Q0e},wC;function t2e(e){wC=e.wasm.cwrap(Ki,null,["number","number","number","array","number","array","array","number","number"])}function n2e(e){let{backend:t,inputs:n,attrs:r}=e,{x:s}=n,{blockSize:a,dataFormat:o}=r,i=s.shape[0],l=o==="NHWC"?s.shape[1]:s.shape[2],u=o==="NHWC"?s.shape[2]:s.shape[3],c=o==="NHWC"?s.shape[3]:s.shape[1],p=l*a,d=u*a,h=c/(a*a),f=o==="NHWC"?[i,p,d,h]:[i,h,p,d],m=t.makeOutput(f,"float32"),y=t.dataIdMap.get(s.dataId).id,x=new Uint8Array(new Int32Array(w.computeStrides(s.shape)).buffer),A=new Uint8Array(new Int32Array(f).buffer),b=new Uint8Array(new Int32Array(w.computeStrides(f)).buffer),v=t.dataIdMap.get(m.dataId).id;return wC(y,a,o==="NHWC"?1:0,x,s.shape.length-1,A,b,f.length,v),m}var r2e={kernelName:Ki,backendName:"wasm",setupFunc:t2e,kernelFunc:n2e},kC;function s2e(e){kC=e.wasm.cwrap(io,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function a2e(e){let{inputs:t,attrs:n,backend:r}=e,{x:s,filter:a}=t,o=r.dataIdMap.get(s.dataId).id,i=r.dataIdMap.get(a.dataId).id,{strides:l,dilations:u,pad:c,dimRoundingMode:p}=n,d=u==null?[1,1]:u,h=C.computeConv2DInfo(s.shape,a.shape,l,d,c,p,!0),f=h.filterHeight,m=h.filterWidth,g=h.padInfo.top,y=h.padInfo.right,x=h.padInfo.bottom,A=h.padInfo.left,b=h.dilationHeight,v=h.dilationWidth,S=h.strideHeight,I=h.strideWidth,E=h.inChannels,R=h.outChannels,P=h.padInfo.type==="SAME"?1:0;if(h.dataFormat!=="channelsLast")throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${h.dataFormat}'. Please use 'channelsLast'.`);let _=r.makeOutput(h.outShape,"float32"),D=r.dataIdMap.get(_.dataId).id;return kC(o,s.shape[0],s.shape[1],s.shape[2],i,f,m,g,y,x,A,P,b,v,S,I,E,R,D),_}var o2e={kernelName:io,backendName:"wasm",setupFunc:s2e,kernelFunc:a2e},i2e=kn(uo),l2e=!1,u2e=Yn(Zi,l2e,"bool"),c2e=kn(co,"float32");function ly(e){let{inputs:t,attrs:n,backend:r}=e,{input:s}=t,{dim:a}=n,o=s.shape.length,i=s.shape.slice(),l=a;return a<0&&(w.assert(-(o+1)<=a,()=>`Axis must be in the interval [${-(o+1)}, ${o}]`),l=o+a+1),i.splice(l,0,1),nr({inputs:{x:s},backend:r,attrs:{shape:i}})}var d2e={kernelName:Yi,backendName:"wasm",kernelFunc:ly};function SC(e){let{attrs:{shape:t,value:n,dtype:r},backend:s}=e,a=s.makeOutput(t,r);return s.typedArrayFromHeap(a).fill(n),a}var p2e={kernelName:Ku,backendName:"wasm",kernelFunc:SC},IC;function h2e(e){IC=e.wasm.cwrap(Qi,null,["number","number","number","number","number","number"])}function f2e(e){let{inputs:t,backend:n}=e,{image:r}=t,s=n.makeOutput(r.shape,r.dtype),a=n.dataIdMap.get(r.dataId).id,o=n.dataIdMap.get(s.dataId).id,[i,l,u,c]=r.shape;return IC(a,i,l,u,c,o),s}var m2e={kernelName:Qi,backendName:"wasm",kernelFunc:f2e,setupFunc:h2e},g2e=kn(po),y2e=!1,A2e=Yn(ho,y2e),CC;function x2e(e){CC=e.wasm.cwrap(fo,null,["number","number","number","number","number","number","number"])}function b2e(e){let{backend:t,inputs:n,attrs:r}=e,{varianceEpsilon:s}=r,{x:a,mean:o,variance:i,offset:l,scale:u}=n,c=t.dataIdMap.get(a.dataId).id,p=t.dataIdMap.get(o.dataId).id,d=t.dataIdMap.get(i.dataId).id,h=l!=null?t.dataIdMap.get(l.dataId).id:0,f=u!=null?t.dataIdMap.get(u.dataId).id:0,m=t.makeOutput(a.shape,a.dtype);if(w.sizeFromShape(a.shape)===0)return m;let g=t.dataIdMap.get(m.dataId).id;return CC(c,p,d,h,f,s,g),m}var v2e={kernelName:fo,backendName:"wasm",setupFunc:x2e,kernelFunc:b2e},TC;function w2e(e){TC=e.wasm.cwrap(Fa,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 k2e(e){let{inputs:t,attrs:n,backend:r}=e,{x:s,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:u,dilations:c,dataFormat:p,dimRoundingMode:d,activation:h,leakyreluAlpha:f}=n,m=C.computeConv2DInfo(s.shape,a.shape,l,c,u,d),g=E0[h];if(g==null)throw new Error(`${h} activation not yet supported for FusedConv2D in the wasm backend.`);let y=r.dataIdMap.get(s.dataId).id,x=r.dataIdMap.get(a.dataId).id,A=m.outChannels,b=0;if(o!=null){let J=r.dataIdMap.get(o.dataId);if(J.shape.length!==1)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${J.shape.length}.`);if(J.shape[0]!==A)throw new Error(`FusedConv2D bias shape (${J.shape}) does not match the number of output channels (${A})`);b=J.id}let v=m.filterHeight,S=m.filterWidth,I=m.padInfo.top,E=m.padInfo.right,R=m.padInfo.bottom,P=m.padInfo.left,_=m.dilationHeight,D=m.dilationWidth,T=m.strideHeight,F=m.strideWidth,U=m.inChannels,X=m.padInfo.type==="SAME"?1:0,z=m.batchSize,Z=m.inHeight,W=m.inWidth;if(p!=="NHWC")throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);let ee=r.makeOutput(m.outShape,"float32"),Q=r.dataIdMap.get(ee.dataId).id,ae=i==null?0:r.dataIdMap.get(i.dataId).id;return TC(y,z,Z,W,x,v,S,b,I,E,R,P,X,_,D,T,F,U,A,g,ae,f||0,Q),ee}var S2e={kernelName:Fa,backendName:"wasm",setupFunc:w2e,kernelFunc:k2e},NC;function I2e(e){NC=e.wasm.cwrap(Oa,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 C2e(e){let{inputs:t,attrs:n,backend:r}=e,{x:s,filter:a,bias:o,preluActivationWeights:i}=t,{strides:l,pad:u,dilations:c,dataFormat:p,dimRoundingMode:d,activation:h,leakyreluAlpha:f}=n,m=C.computeConv2DInfo(s.shape,a.shape,l,c,u,d,!0),g=E0[h];if(g==null)throw new Error(`${h} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);let y=r.dataIdMap.get(s.dataId).id,x=r.dataIdMap.get(a.dataId).id,A=m.outChannels,b=0;if(o!=null){let J=r.dataIdMap.get(o.dataId);if(J.shape.length!==1)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${J.shape.length}.`);if(J.shape[0]!==A)throw new Error(`FusedDepthwiseConv2D bias shape (${J.shape}) does not match the number of output channels (${A})`);b=J.id}let v=m.filterHeight,S=m.filterWidth,I=m.padInfo.top,E=m.padInfo.right,R=m.padInfo.bottom,P=m.padInfo.left,_=m.dilationHeight,D=m.dilationWidth,T=m.strideHeight,F=m.strideWidth,U=m.inChannels,X=m.padInfo.type==="SAME"?1:0,z=m.batchSize,Z=m.inHeight,W=m.inWidth;if(p!=="NHWC")throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${p}'. Please use 'NHWC'.`);let ee=r.makeOutput(m.outShape,"float32"),Q=r.dataIdMap.get(ee.dataId).id,ae=i==null?0:r.dataIdMap.get(i.dataId).id;return NC(y,z,Z,W,x,v,S,b,I,E,R,P,X,_,D,T,F,U,A,g,ae,f||0,Q),ee}var T2e={kernelName:Oa,backendName:"wasm",setupFunc:I2e,kernelFunc:C2e},EC;function N2e(e){EC=e.wasm.cwrap(tl,null,["number","number","number","number","number","number","array","number"])}function E2e(e){let{backend:t,inputs:n}=e,{params:r,indices:s}=n,[a,o,i,l]=Sy.prepareAndValidate(r,s),u=t.makeOutput(a,r.dtype);if(o===0)return u;let c=s.shape,p=c[c.length-1],h=t.dataIdMap.get(r.dataId).id,m=t.dataIdMap.get(s.dataId).id,g=new Uint8Array(new Int32Array(l).buffer),y=t.dataIdMap.get(u.dataId).id;return EC(h,Ut[r.dtype],m,o,p,i,g,y),u}var R2e={kernelName:tl,backendName:"wasm",setupFunc:N2e,kernelFunc:E2e},RC;function _2e(e){RC=e.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function $2e(e){let{backend:t,inputs:n,attrs:r}=e,{x:s,indices:a}=n,{axis:o,batchDims:i}=r,l=w.parseAxisParam(o,s.shape)[0],u=t.readSync(a.dataId),c=s.shape[l];for(let R=0;R<u.length;++R){let P=u[R];w.assert(P<=c-1&&P>=0,()=>`GatherV2: the index value ${P} is not in [0, ${c-1}]`)}let p=C.segment_util.collectGatherOpShapeInfo(s,a,l,i),d=nr({inputs:{x:s},attrs:{shape:[p.batchSize,p.outerSize,p.dimSize,p.sliceSize]},backend:t}),h=w.sizeFromShape(a.shape),f=nr({inputs:{x:a},attrs:{shape:[p.batchSize,h/p.batchSize]},backend:t}),m=[p.batchSize,p.outerSize,h/p.batchSize,p.sliceSize],g=t.makeOutput(m,s.dtype);if(w.sizeFromShape(s.shape)===0)return g;let y=d.shape.length-1,A=t.dataIdMap.get(d.dataId).id,v=t.dataIdMap.get(f.dataId).id,S=t.dataIdMap.get(g.dataId).id,I=new Uint8Array(new Int32Array(w.computeStrides(d.shape)).buffer),E=new Uint8Array(new Int32Array(w.computeStrides(m)).buffer);return RC(A,Ut[s.dtype],I,y,v,p.batchSize,E,S),t.disposeData(d.dataId),t.disposeData(f.dataId),g.shape=p.outputShape,g}var D2e={kernelName:el,backendName:"wasm",setupFunc:_2e,kernelFunc:$2e},P2e=!1,F2e=Yn(nl,P2e,"bool"),O2e=!1,M2e=Yn(mo,O2e,"bool"),_C;function z2e(e){_C=e.wasm.cwrap(yo,null,["number","number","number","number"])}function L2e(e){let{inputs:{x:t},attrs:{alpha:n},backend:r}=e,s=r.dataIdMap.get(t.dataId).id,a=r.makeOutput(t.shape,"float32");if(w.sizeFromShape(t.shape)!==0){let o=r.dataIdMap.get(a.dataId).id;_C(s,Ut[t.dtype],n,o)}return a}var B2e={kernelName:yo,backendName:"wasm",setupFunc:z2e,kernelFunc:L2e},W2e=!1,V2e=Yn(rl,W2e,"bool"),U2e=!1,G2e=Yn(sl,U2e,"bool"),H2e=kn(Ao),j2e=!1,q2e=Yn(al,j2e,"bool"),$C;function X2e(e){$C=e.wasm.cwrap(xo,null,["number","number","number","number"])}function K2e(e){let{backend:t,inputs:n,attrs:r}=e,{reductionIndices:s,keepDims:a}=r,{x:o}=n,l=t.dataIdMap.get(o.dataId).id,u=o,{transposed:c,axes:p,originalAxes:d,inputWasTransposed:h}=Zo(o,s,t);if(h){let A=t.dataIdMap.get(c.dataId).id;u=c,l=A}let f=u.shape.length;C.assertAxesAreInnerMostDims("max",p,f);let[m,g]=C.computeOutAndReduceShapes(u.shape,p),y=w.sizeFromShape(g),x=t.makeOutput(m,o.dtype);if(w.sizeFromShape(u.shape)!==0){let A=t.dataIdMap.get(x.dataId).id;$C(l,Ut[o.dtype],y,A)}if(h&&t.disposeData(c.dataId),a){let A=C.expandShapeToKeepDim(x.shape,d);x.shape=A}return x}var Z2e={kernelName:xo,backendName:"wasm",setupFunc:X2e,kernelFunc:K2e},Y2e=!1,J2e=Yn(bo,Y2e),DC;function Q2e(e){DC=e.wasm.cwrap(vo,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function e1e(e){let{inputs:t,attrs:n,backend:r}=e,s=t.x,a=r.dataIdMap.get(s.dataId).id;w.assert(s.dtype==="float32",()=>`Error in MaxPool: only float32 input is supported. Got ${s.dtype}.`);let{filterSize:o,strides:i,pad:l,dimRoundingMode:u}=n,c=C.computePool2DInfo(s.shape,o,i,1,l,u),p=c.filterHeight,d=c.filterWidth,h=c.padInfo.top,f=c.padInfo.right,m=c.padInfo.bottom,g=c.padInfo.left,y=c.dilationHeight,x=c.dilationWidth,A=c.strideHeight,b=c.strideWidth,v=c.inChannels,S=c.outChannels;if(c.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${c.dataFormat}'. Please use 'channelsLast'.`);let I=r.makeOutput(c.outShape,"float32"),E=r.dataIdMap.get(I.dataId).id;return DC(a,s.shape[0],s.shape[1],s.shape[2],p,d,h,f,m,g,y,x,A,b,v,S,E),I}var t1e={kernelName:vo,backendName:"wasm",setupFunc:Q2e,kernelFunc:e1e},PC;function n1e(e){PC=e.wasm.cwrap(wo,null,["number, number, number"])}function r1e(e){let{backend:t,inputs:n,attrs:r}=e,{axis:s,keepDims:a}=r,{x:o}=n,i=t.dataIdMap.get(o.dataId).id,l=i,u=o,{transposed:c,axes:p,originalAxes:d,inputWasTransposed:h}=Zo(o,s,t),f=p;if(h){let b=t.dataIdMap.get(c.dataId).id;b!==i&&(u=c,l=b,f=C.getInnerMostAxes(f.length,u.shape.length))}C.assertAxesAreInnerMostDims("mean",f,u.shape.length);let[m,g]=C.computeOutAndReduceShapes(u.shape,f),y=w.sizeFromShape(g),x=u;u.dtype!=="float32"&&(x=Xp({backend:t,inputs:{x:u},attrs:{dtype:"float32"}}),l=t.dataIdMap.get(x.dataId).id);let A=t.makeOutput(m,"float32");if(w.sizeFromShape(u.shape)!==0){let b=t.dataIdMap.get(A.dataId).id;PC(l,y,b)}if(h&&t.disposeData(c.dataId),a){let b=C.expandShapeToKeepDim(A.shape,d);A.shape=b}return u.dtype!=="float32"&&t.disposeData(x.dataId),A}var s1e={kernelName:wo,backendName:"wasm",setupFunc:n1e,kernelFunc:r1e},FC;function a1e(e){FC=e.wasm.cwrap(ko,null,["number","number","number","number"])}function o1e(e){let{backend:t,inputs:n,attrs:r}=e,{axis:s,keepDims:a}=r,{x:o}=n,i=t.dataIdMap.get(o.dataId).id,l=i,u=o,{transposed:c,axes:p,originalAxes:d,inputWasTransposed:h}=Zo(o,s,t);if(h){let A=t.dataIdMap.get(c.dataId).id;A!==i&&(u=c,l=A)}let f=u.shape.length;C.assertAxesAreInnerMostDims("min",p,f);let[m,g]=C.computeOutAndReduceShapes(u.shape,p),y=w.sizeFromShape(g),x=t.makeOutput(m,u.dtype);if(w.sizeFromShape(u.shape)!==0){let A=t.dataIdMap.get(x.dataId).id;FC(l,Ut[o.dtype],y,A)}if(h&&t.disposeData(c.dataId),a){let A=C.expandShapeToKeepDim(x.shape,d);x.shape=A}return x}var i1e={kernelName:ko,backendName:"wasm",setupFunc:a1e,kernelFunc:o1e},l1e=!1,u1e=Yn(So,l1e),OC=(e=>(e[e.reflect=0]="reflect",e[e.symmetric=1]="symmetric",e))(OC||{}),MC;function c1e(e){MC=e.wasm.cwrap(Io,null,["number","array","number","number","array","array","number","number"])}function d1e(e){let{inputs:{x:t},backend:n,attrs:{paddings:r,mode:s}}=e,a=r.map((f,m)=>f[0]+t.shape[m]+f[1]),o=n.dataIdMap.get(t.dataId).id,i=n.makeOutput(a,t.dtype),l=n.dataIdMap.get(i.dataId).id,u=new Uint8Array(new Int32Array(t.shape).buffer),c=r.map(f=>f[0]),p=r.map(f=>f[1]),d=new Uint8Array(new Int32Array(c).buffer),h=new Uint8Array(new Int32Array(p).buffer);return MC(o,u,t.shape.length,Ut[t.dtype],d,h,OC[s],l),i}var p1e={kernelName:Io,backendName:"wasm",kernelFunc:d1e,setupFunc:c1e},h1e=!0,f1e=Yn(Co,h1e),m1e=kn(ol);function E3(e,t){let n=new Int32Array(e.wasm.HEAPU8.buffer,t,4),r=n[0],s=n[1],a=n[2],o=n[3];return e.wasm._free(t),{pSelectedIndices:r,selectedSize:s,pSelectedScores:a,pValidOutputs:o}}var zC;function g1e(e){zC=e.wasm.cwrap(ll,"number",["number","number","number","number","number"])}function y1e(e){let{backend:t,inputs:n,attrs:r}=e,{iouThreshold:s,maxOutputSize:a,scoreThreshold:o}=r,{boxes:i,scores:l}=n,u=t.dataIdMap.get(i.dataId).id,c=t.dataIdMap.get(l.dataId).id,p=zC(u,c,a,s,o),{pSelectedIndices:d,selectedSize:h,pSelectedScores:f,pValidOutputs:m}=E3(t,p);return t.wasm._free(f),t.wasm._free(m),t.makeOutput([h],"int32",d)}var A1e={kernelName:ll,backendName:"wasm",setupFunc:g1e,kernelFunc:y1e},LC;function x1e(e){LC=e.wasm.cwrap(nc,"number",["number","number","number","number","number","bool"])}function b1e(e){let{backend:t,inputs:n,attrs:r}=e,{iouThreshold:s,maxOutputSize:a,scoreThreshold:o,padToMaxOutputSize:i}=r,{boxes:l,scores:u}=n,c=t.dataIdMap.get(l.dataId).id,p=t.dataIdMap.get(u.dataId).id,d=LC(c,p,a,s,o,i),{pSelectedIndices:h,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=E3(t,d);t.wasm._free(m);let y=t.makeOutput([f],"int32",h),x=t.makeOutput([],"int32",g);return[y,x]}var v1e={kernelName:nc,backendName:"wasm",setupFunc:x1e,kernelFunc:b1e},BC;function w1e(e){BC=e.wasm.cwrap(ul,"number",["number","number","number","number","number","number"])}function k1e(e){let{backend:t,inputs:n,attrs:r}=e,{iouThreshold:s,maxOutputSize:a,scoreThreshold:o,softNmsSigma:i}=r,{boxes:l,scores:u}=n,c=t.dataIdMap.get(l.dataId).id,p=t.dataIdMap.get(u.dataId).id,d=BC(c,p,a,s,o,i),{pSelectedIndices:h,selectedSize:f,pSelectedScores:m,pValidOutputs:g}=E3(t,d);t.wasm._free(g);let y=t.makeOutput([f],"int32",h),x=t.makeOutput([f],"float32",m);return[y,x]}var S1e={kernelName:ul,backendName:"wasm",setupFunc:w1e,kernelFunc:k1e},I1e=!1,C1e=Yn(il,I1e,"bool"),WC;function T1e(e){WC=e.wasm.cwrap(dl,null,["number","number","number","number","number"])}function N1e(e){let{inputs:t,backend:n,attrs:r}=e,{indices:s}=t,{depth:a,onValue:o,offValue:i}=r,l=n.makeOutput([...s.shape,a],"int32"),u=n.dataIdMap.get(l.dataId).id,p=n.dataIdMap.get(s.dataId).id;return WC(p,a,o,i,u),l}var E1e={kernelName:dl,backendName:"wasm",setupFunc:T1e,kernelFunc:N1e};function R1e(e){let{inputs:{x:t},backend:n}=e,r=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(r).fill(1),r}var _1e={kernelName:cl,backendName:"wasm",kernelFunc:R1e};function $1e(e){let{inputs:t,backend:n,attrs:r}=e,{axis:s}=r;if(t.length===1)return ly({inputs:{input:t[0]},backend:n,attrs:{dim:s}});let a=t[0].shape,o=t[0].dtype;t.forEach(c=>{w.assertShapesMatch(a,c.shape,"All tensors passed to stack must have matching shapes"),w.assert(o===c.dtype,()=>"All tensors passed to stack must have matching dtypes")});let i=[],l=t.map(c=>{let p=ly({inputs:{input:c},backend:n,attrs:{dim:s}});return i.push(p),p}),u=mC({inputs:l,backend:n,attrs:{axis:s}});return i.forEach(c=>n.disposeData(c.dataId)),u}var D1e={kernelName:pl,backendName:"wasm",kernelFunc:$1e},VC;function P1e(e){VC=e.wasm.cwrap(To,null,["number","array","number","number","array","array","number","number"])}function F1e(e){let{inputs:{x:t},backend:n,attrs:{paddings:r,constantValue:s}}=e,a=r.map((m,g)=>m[0]+t.shape[g]+m[1]);if(w.sizeFromShape(t.shape)===0)return SC({backend:n,attrs:{shape:a,value:s,dtype:t.dtype}});let o=n.dataIdMap.get(t.dataId).id,i=n.makeOutput(a,t.dtype),u=n.dataIdMap.get(i.dataId).id,c=new Uint8Array(new Int32Array(t.shape).buffer),p=r.map(m=>m[0]),d=r.map(m=>m[1]),h=new Uint8Array(new Int32Array(p).buffer),f=new Uint8Array(new Int32Array(d).buffer);return VC(o,c,t.shape.length,Ut[t.dtype],h,f,s,u),i}var UC={kernelName:To,backendName:"wasm",kernelFunc:F1e,setupFunc:P1e},O1e=!1,M1e=Yn(No,O1e),GC;function z1e(e){GC=e.wasm.cwrap(Eo,null,["number","number","number"])}function L1e(e){let{inputs:t,backend:n}=e,{x:r,alpha:s}=t,a=n.dataIdMap.get(r.dataId).id,o=n.dataIdMap.get(s.dataId).id,i=a,l=r,u=l;l.dtype!=="float32"&&(u=Xp({backend:n,inputs:{x:r},attrs:{dtype:"float32"}}),i=n.dataIdMap.get(u.dataId).id);let c=n.makeOutput(r.shape,"float32"),p=n.dataIdMap.get(c.dataId).id;return GC(i,o,p),l.dtype!=="float32"&&n.disposeData(u.dataId),c}var B1e={kernelName:Eo,backendName:"wasm",setupFunc:z1e,kernelFunc:L1e},HC;function W1e(e){HC=e.wasm.cwrap(Ro,null,["number","number","number","number"])}function V1e(e){let{backend:t,inputs:n,attrs:r}=e,{axis:s,keepDims:a}=r,{x:o}=n,i=t.dataIdMap.get(o.dataId).id,l=i,u=o,{transposed:c,axes:p,originalAxes:d,inputWasTransposed:h}=Zo(o,s,t),f=p;if(h){let A=t.dataIdMap.get(c.dataId).id;A!==i&&(u=c,l=A,f=C.getInnerMostAxes(f.length,u.shape.length))}C.assertAxesAreInnerMostDims("prod",f,u.shape.length);let[m,g]=C.computeOutAndReduceShapes(u.shape,f),y=w.sizeFromShape(g),x=t.makeOutput(m,u.dtype);if(w.sizeFromShape(u.shape)!==0){let A=t.dataIdMap.get(x.dataId).id;HC(l,y,Ut[x.dtype],A)}if(h&&t.disposeData(c.dataId),a){let A=C.expandShapeToKeepDim(x.shape,d);x.shape=A}return x}var U1e={kernelName:Ro,backendName:"wasm",setupFunc:W1e,kernelFunc:V1e},G1e=e=>{let{backend:t,attrs:n}=e,{start:r,stop:s,step:a,dtype:o}=n,i=t3(r,s,a,o),l=t.makeOutput([i.length],o);return t.typedArrayFromHeap(l).set(i),l},H1e={kernelName:rc,backendName:"wasm",kernelFunc:G1e},j1e=!0,q1e=Yn(lo,j1e),X1e=kn(_o),K1e=kn(Do),jC;function Z1e(e){jC=e.wasm.cwrap($o,null,["number","number","number","number","number","number","number","number","number","number"])}function Y1e(e){let{backend:t,inputs:n,attrs:r}=e,{images:s}=n,{alignCorners:a,halfPixelCenters:o,size:i}=r,[l,u]=i,[c,p,d,h]=s.shape,f=[c,l,u,h],m=t.dataIdMap.get(s.dataId),g;m.dtype!=="float32"&&(g=Xp({backend:t,inputs:{x:s},attrs:{dtype:"float32"}}),m=t.dataIdMap.get(g.dataId));let y=m.id,x=t.makeOutput(f,"float32");if(w.sizeFromShape(s.shape)===0)return x;let A=t.dataIdMap.get(x.dataId).id;return jC(y,c,p,d,h,l,u,a?1:0,o?1:0,A),g!=null&&t.disposeData(g.dataId),x}var J1e={kernelName:$o,backendName:"wasm",setupFunc:Z1e,kernelFunc:Y1e},qC;function Q1e(e){qC=e.wasm.cwrap(fl,null,["number","array","number","array","number","number"])}function ege(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{dims:a}=r,o=w.parseAxisParam(a,s.shape);if(s.shape.length===0)return R0({inputs:{x:s},backend:n});let i=n.makeOutput(s.shape,s.dtype),l=n.dataIdMap.get(s.dataId).id,u=n.dataIdMap.get(i.dataId).id,c=new Uint8Array(new Int32Array(o).buffer),p=new Uint8Array(new Int32Array(s.shape).buffer);qC(l,c,o.length,p,s.shape.length,u);let d=nr({inputs:{x:i},attrs:{shape:s.shape},backend:n});return n.disposeData(i.dataId),d}var tge={kernelName:fl,backendName:"wasm",kernelFunc:ege,setupFunc:Q1e},XC;function nge(e){XC=e.wasm.cwrap(Nl,null,["number","number","number","number","number","number","number","number","array","number","number"])}function rge(e){let{inputs:t,backend:n,attrs:r}=e,{image:s}=t,{radians:a,fillValue:o,center:i}=r,l=n.makeOutput(s.shape,s.dtype),u=n.dataIdMap.get(s.dataId).id,c=n.dataIdMap.get(l.dataId).id,[p,d,h,f]=s.shape,[m,g]=C.getImageCenter(i,d,h),y=o===0,x=255,A=typeof o=="number"?[o,o,o,y?0:x]:[...o,x],b=new Uint8Array(new Int32Array(A).buffer);return XC(u,p,d,h,f,a,m,g,b,A.length,c),l}var sge={kernelName:Nl,backendName:"wasm",kernelFunc:rge,setupFunc:nge},age=kn(ml),oge=kn(Po),KC;function ige(e){KC=e.wasm.cwrap(gl,null,["number","number","number","number","number","number","array","number","number"])}function lge(e){let{backend:t,inputs:n,attrs:r}=e,{indices:s,updates:a}=n,{shape:o}=r,i=t.makeOutput(o,a.dtype);if(w.sizeFromShape(o)===0)return i;let{sliceRank:l,numUpdates:u,sliceSize:c,strides:p,outputSize:d}=Iy.calculateShapes(a,s,o),f=t.dataIdMap.get(s.dataId).id,g=t.dataIdMap.get(a.dataId).id,y=new Uint8Array(new Int32Array(p).buffer),x=t.dataIdMap.get(i.dataId).id;return KC(f,g,Ut[a.dtype],l,u,c,y,d,x),i}var uge={kernelName:gl,backendName:"wasm",setupFunc:ige,kernelFunc:lge},ZC;function cge(e){ZC=e.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function dge(e){let{inputs:t,backend:n}=e,{condition:r,t:s,e:a}=t,o=n.dataIdMap.get(r.dataId).id,i=n.dataIdMap.get(s.dataId).id,l=n.dataIdMap.get(a.dataId).id,u=n.makeOutput(s.shape,s.dtype),c=n.dataIdMap.get(u.dataId).id,p=r.shape.length,d=s.shape.length,h=p===0||p>1||d===1?1:w.sizeFromShape(s.shape.slice(1));return ZC(o,i,l,h,c),u}var pge={kernelName:yl,backendName:"wasm",kernelFunc:dge,setupFunc:cge},YC;function hge(e){YC=e.wasm.cwrap(Oo,null,["number","number"])}function fge(e){let{backend:t,inputs:{x:n}}=e,r=t.dataIdMap.get(n.dataId).id,s=t.makeOutput(n.shape,n.dtype),a=t.dataIdMap.get(s.dataId).id;return w.sizeFromShape(s.shape)===0||YC(r,a),s}var mge={kernelName:"Sigmoid",backendName:"wasm",setupFunc:hge,kernelFunc:fge},gge=kn(Fo),JC;function yge(e){JC=e.wasm.cwrap(Lo,null,["number","number","number","number"])}function Age(e){let{backend:t,inputs:{logits:n},attrs:{dim:r}}=e,s=t.dataIdMap.get(n.dataId).id,a=t.makeOutput(n.shape,n.dtype),o=t.dataIdMap.get(a.dataId).id,i=n.shape[r],l=w.sizeFromShape(n.shape)/i;return w.sizeFromShape(a.shape)===0||JC(s,o,i,l),a}var xge={kernelName:Lo,backendName:"wasm",setupFunc:yge,kernelFunc:Age};function bge(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,{blockShape:a,paddings:o}=r,i=w.sizeFromShape(a),l=[[0,0]];l.push(...o);for(let S=1+a.length;S<s.shape.length;++S)l.push([0,0]);let u=UC.kernelFunc({inputs:{x:s},backend:n,attrs:{paddings:l,constantValue:0}}),c=C.getReshaped(u.shape,a,i,!1),p=C.getPermuted(c.length,a.length,!1),d=C.getReshapedPermuted(u.shape,a,i,!1),m=nr({inputs:{x:u},backend:n,attrs:{shape:c}}),x=Xa({inputs:{x:m},backend:n,attrs:{perm:p}}),v=nr({inputs:{x},backend:n,attrs:{shape:d}});return n.disposeData(u.dataId),n.disposeData(m.dataId),n.disposeData(x.dataId),v}var vge={kernelName:bl,backendName:"wasm",kernelFunc:bge},QC;function wge(e){QC=e.wasm.cwrap("SparseFillEmptyRows","number",["number","number","number","number","number","number","number","number","number","number","number","number"])}function kge(e){let{backend:t,inputs:n}=e,{indices:r,values:s,denseShape:a,defaultValue:o}=n,i=r.shape[0],l=r.shape[1],u=t.readSync(a.dataId)[0],c=[i+u,l],p=t.dataIdMap.get(r.dataId).id,d=t.dataIdMap.get(s.dataId).id,h=t.dataIdMap.get(o.dataId).id,f=t.makeOutput(c,r.dtype),m=t.dataIdMap.get(f.dataId).id,g=t.makeOutput(c.slice(0,1),s.dtype),y=t.dataIdMap.get(g.dataId).id,x=t.makeOutput([u],"bool"),A=t.dataIdMap.get(x.dataId).id,b=t.makeOutput([i],r.dtype),v=t.dataIdMap.get(b.dataId).id,S=t.makeOutput([4],"int32"),I=t.dataIdMap.get(S.dataId).id,E=QC(p,d,Ut[s.dtype],i,u,l,h,m,y,A,v,I),R=t.readSync(S.dataId),P;switch(R[0]){case 1:{P=C.getSparseFillEmptyRowsIndicesDenseShapeMismatch(R[1]);break}case 2:{P=C.getSparseFillEmptyRowsNegativeIndexErrorMessage(R[1],R[2]);break}case 3:P=C.getSparseFillEmptyRowsOutOfRangeIndexErrorMessage(R[1],R[2],R[3]);break;default:P=""}if(t.disposeData(S.dataId),P)throw t.disposeData(f.dataId),t.disposeData(g.dataId),t.disposeData(x.dataId),t.disposeData(b.dataId),new Error(P);let _=f,D=g;return E!==c[0]&&(_=Wi({inputs:{x:f},attrs:{begin:0,size:[E,l]},backend:t}),D=Wi({inputs:{x:g},attrs:{begin:0,size:E},backend:t}),t.disposeData(f.dataId),t.disposeData(g.dataId)),[_,D,x,b]}var Sge={kernelName:lp,backendName:"wasm",setupFunc:wge,kernelFunc:kge},e9;function Ige(e){e9=e.wasm.cwrap(uc,null,["number","number","number","number","number","number","number"])}function Cge(e){let{backend:t,inputs:n}=e,{inputIndices:r,inputShape:s,newShape:a}=n;if(r.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape
|
|
${r.shape}`);if(s.shape.length!==1)throw new Error(`Input shape should be a vector but received shape
|
|
${s.shape}`);if(a.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${a.shape}`);let o=t.dataIdMap.get(r.dataId).id,i=t.dataIdMap.get(s.dataId).id,l=t.dataIdMap.get(a.dataId).id,u=r.shape[0],c=w.sizeFromShape(a.shape),p=t.makeOutput([u,c],r.dtype),d=t.dataIdMap.get(p.dataId).id,h=t.makeOutput([c],a.dtype),f=t.dataIdMap.get(h.dataId).id,m=t.makeOutput([3],"int32"),g=t.dataIdMap.get(m.dataId).id;e9(o,i,l,u,d,f,g);let y=t.readSync(m.dataId),x;switch(y[0]){case 0:{x=C.getSparseReshapeMultipleNegativeOneOutputDimErrorMessage(y[1],y[2]);break}case 1:{x=C.getSparseReshapeNegativeOutputDimErrorMessage(y[1],y[2]);break}case 2:x=C.getSparseReshapeEmptyTensorZeroOutputDimErrorMessage();break;case 3:{let A=Array.from(t.readSync(s.dataId)),b=Array.from(t.readSync(h.dataId));x=C.getSparseReshapeInputOutputMultipleErrorMessage(A,b);break}case 4:{let A=Array.from(t.readSync(s.dataId)),b=Array.from(t.readSync(h.dataId));x=C.getSparseReshapeInputOutputMismatchErrorMessage(A,b);break}default:x=""}if(t.disposeData(m.dataId),x)throw t.disposeData(p.dataId),t.disposeData(h.dataId),new Error(x);return[p,h]}var Tge={kernelName:uc,backendName:"wasm",setupFunc:Ige,kernelFunc:Cge},t9;function n9(e){t9=e.wasm.cwrap("SparseSegmentReduction",null,["number","number","number","number","number","number","number","number","number"])}function r9(e,t){let{backend:n,inputs:r}=e,{data:s,indices:a,segmentIds:o}=r,i=a.shape[0],l=n.readSync(o.dataId,i-1,i)[0],c=i>0?l+1:0;if(c<0)throw new Error(C.getSparseSegmentReductionNegativeSegmentIdsErrorMessage());let p=s.shape.slice();p[0]=c;let d=n.dataIdMap.get(s.dataId).id,h=n.dataIdMap.get(a.dataId).id,f=n.dataIdMap.get(o.dataId).id,m=n.makeOutput(p,s.dtype),g=n.dataIdMap.get(m.dataId).id,y=n.makeOutput([4],"int32"),x=n.dataIdMap.get(y.dataId).id;t9(d,Ut[s.dtype],s.shape[0],h,f,g,x,t,0);let A=n.readSync(y.dataId),b;switch(A[0]){case 0:{b=C.getSparseSegmentReductionNegativeSegmentIdsErrorMessage();break}case 1:{b=C.getSparseSegmentReductionNonIncreasingSegmentIdsErrorMessage();break}case 2:b=C.getSparseSegmentReductionSegmentIdOutOfRangeErrorMessage(A[1],A[2]);break;case 3:b=C.getSparseSegmentReductionIndicesOutOfRangeErrorMessage(A[1],A[2],A[3]);break;default:b=""}if(n.disposeData(y.dataId),b)throw n.disposeData(m.dataId),new Error(b);return m}function Nge(e){return r9(e,!0)}var Ege={kernelName:up,backendName:"wasm",setupFunc:n9,kernelFunc:Nge};function Rge(e){return r9(e,!1)}var _ge={kernelName:cp,backendName:"wasm",setupFunc:n9,kernelFunc:Rge};function $ge(e){let{inputs:t,attrs:n,backend:r}=e,{x:s}=t,{numOrSizeSplits:a,axis:o}=n,i=w.parseAxisParam(o,s.shape)[0],l=C.prepareSplitSize(s,a,i),u=new Array(s.shape.length).fill(0),c=s.shape.slice();return l.map(p=>{let d=[...c];d[i]=p;let h=Wi({inputs:{x:s},attrs:{begin:u,size:d},backend:r});return u[i]+=p,h})}var Dge={kernelName:vl,backendName:"wasm",kernelFunc:$ge},Pge=kn(Mo),Fge=kn(cc),Oge=!0,Mge=Yn(Bo,Oge),s9;function zge(e){s9=e.wasm.cwrap(Go,null,["number","number","number","number"])}function Lge(e){let{backend:t,inputs:n,attrs:r}=e,{alpha:s}=r,{x:a}=n,o=t.dataIdMap.get(a.dataId).id,i=t.makeOutput(a.shape,a.dtype),l=t.dataIdMap.get(i.dataId).id;return s9(o,s,Ut[a.dtype],l),i}var Bge={kernelName:Go,backendName:"wasm",setupFunc:zge,kernelFunc:Lge},a9;function Wge(e){a9=e.wasm.cwrap(wl,null,["number","array","number","array","array","array","array","array","number","number"])}function Vge(e){let{backend:t,inputs:n,attrs:r}=e,{x:s}=n,{begin:a,end:o,strides:i,beginMask:l,endMask:u,ellipsisMask:c,newAxisMask:p,shrinkAxisMask:d}=r,{finalShapeSparse:h,finalShape:f,isIdentity:m,sliceDim0:g,isSimpleSlice:y,begin:x,end:A,strides:b}=Mt.sliceInfo(s.shape,a,o,i,l,u,c,p,d),v;if(m)v=nr({inputs:{x:s},backend:t,attrs:{shape:f}});else if(g||y){w.assert(s.shape.length>=1,()=>`Input must have rank at least 1, got: ${s.shape.length}`);let S=Mt.computeOutShape(x,A,b),I=Wi({inputs:{x:s},backend:t,attrs:{begin:x,size:S}});v=nr({inputs:{x:I},backend:t,attrs:{shape:f}}),t.disposeData(I.dataId)}else{let S=t.makeOutput(h,"float32"),I=t.dataIdMap.get(s.dataId).id,E=new Uint8Array(new Int32Array(w.computeStrides(s.shape)).buffer),R=new Uint8Array(new Int32Array(x).buffer),P=new Uint8Array(new Int32Array(A).buffer),_=new Uint8Array(new Int32Array(b).buffer),D=new Uint8Array(new Int32Array(h).buffer),T=new Uint8Array(new Int32Array(w.computeStrides(h)).buffer),F=t.dataIdMap.get(S.dataId).id;a9(I,E,s.shape.length,R,P,_,D,T,h.length,F),v=nr({inputs:{x:S},backend:t,attrs:{shape:f}}),t.disposeData(S.dataId)}return v}var Uge={kernelName:wl,backendName:"wasm",setupFunc:Wge,kernelFunc:Vge},Gge=!0,Hge=Yn(Wo,Gge),o9;function jge(e){o9=e.wasm.cwrap(zo,null,["number","number","number","number"])}function qge(e){let{backend:t,inputs:n,attrs:r}=e,{axis:s,keepDims:a}=r,{x:o}=n,i=t.dataIdMap.get(o.dataId).id,l=i,u=o,{transposed:c,axes:p,originalAxes:d,inputWasTransposed:h}=Zo(o,s,t),f=p;if(h){let A=t.dataIdMap.get(c.dataId).id;A!==i&&(u=c,l=A,f=C.getInnerMostAxes(f.length,u.shape.length))}C.assertAxesAreInnerMostDims("sum",f,u.shape.length);let[m,g]=C.computeOutAndReduceShapes(u.shape,f),y=w.sizeFromShape(g),x=t.makeOutput(m,u.dtype);if(w.sizeFromShape(u.shape)!==0){let A=t.dataIdMap.get(x.dataId).id;o9(l,y,Ut[x.dtype],A)}if(h&&t.disposeData(c.dataId),a){let A=C.expandShapeToKeepDim(x.shape,d);x.shape=A}return x}var Xge={kernelName:zo,backendName:"wasm",setupFunc:jge,kernelFunc:qge},Kge=kn(kl),Zge=kn(Vo),i9;function Yge(e){i9=e.wasm.cwrap(na,null,["number","array","number","array","number","number"])}function Jge(e){let{inputs:t,backend:n,attrs:r}=e,{x:s}=t,a=n.dataIdMap.get(s.dataId).id,{reps:o}=r,i=new Array(s.shape.length);for(let d=0;d<i.length;d++)i[d]=s.shape[d]*o[d];let l=new Uint8Array(new Int32Array(s.shape).buffer),u=new Uint8Array(new Int32Array(i).buffer),c=n.makeOutput(i,s.dtype),p=n.dataIdMap.get(c.dataId).id;return i9(a,l,s.shape.length,u,i.length,Ut[c.dtype],p),c}var Qge={kernelName:na,backendName:"wasm",setupFunc:Yge,kernelFunc:Jge},l9;function eye(e){l9=e.wasm.cwrap(Sl,null,["number","array","number","number","number","bool","number","number"])}var tye=({inputs:e,backend:t,attrs:n})=>{let{x:r}=e,{k:s,sorted:a}=n,o=t.dataIdMap.get(r.dataId).id,i=new Uint8Array(new Int32Array(r.shape).buffer),l=r.shape.slice();l[l.length-1]=s;let u=t.makeOutput(l,r.dtype),c=t.dataIdMap.get(u.dataId).id,p=t.makeOutput(l,"int32"),d=t.dataIdMap.get(p.dataId).id;return l9(o,i,r.shape.length,Ut[r.dtype],s,a,c,d),[u,p]},nye={kernelName:Sl,backendName:"wasm",setupFunc:eye,kernelFunc:tye},u9;function rye(e){u9=e.wasm.cwrap(Il,null,["number","number","bool","number","number","number","number","number","number","array","number","number","number","number","number"])}function sye(e){let{backend:t,inputs:n,attrs:r}=e,{image:s,transforms:a}=n,{interpolation:o,fillMode:i,fillValue:l,outputShape:u}=r,[c,p,d,h]=s.shape,[f,m]=u!=null?u:[p,d],g=[c,f,m,h],y=new Uint8Array(new Int32Array(w.computeStrides(s.shape)).buffer),x=t.makeOutput(g,s.dtype),A=t.dataIdMap.get(x.dataId).id,v=t.dataIdMap.get(s.dataId).id,I=t.dataIdMap.get(a.dataId).id,E=o==="nearest"?1:2,R;switch(i){case"constant":R=1;break;case"reflect":R=2;break;case"wrap":R=3;break;case"nearest":R=4;break;default:R=1;break}return u9(v,I,a.shape[0]>1,c,f,m,h,d,p,y,s.shape.length-1,E,R,l,A),x}var aye={kernelName:Il,backendName:"wasm",setupFunc:rye,kernelFunc:sye};function oye(e){let{inputs:t,backend:n,attrs:r}=e,{value:s}=t,{axis:a}=r;a<0&&(a+=s.shape.length);let o=s.shape[a],i=s.shape.length,l=new Array(i-1),u=0;for(let h=0;h<i;h++)h!==a&&(l[u++]=s.shape[h]);let c=new Array(o),p=new Array(i).fill(0),d=s.shape.slice();d[a]=1;for(let h=0;h<c.length;h++)p[a]=h,c[h]=Wi({inputs:{x:s},attrs:{begin:p,size:d},backend:n});return c.map(({dataId:h,dtype:f})=>({dataId:h,dtype:f,shape:l}))}var iye={kernelName:Cl,backendName:"wasm",kernelFunc:oye};function lye(e){let{inputs:{x:t},backend:n}=e,r=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(r).fill(0),r}var uye={kernelName:Tl,backendName:"wasm",kernelFunc:lye},cye=[Jme,Qme,t0e,s0e,p0e,m0e,A0e,v0e,I0e,_0e,$0e,D0e,O0e,M0e,B0e,U0e,G0e,H0e,X0e,Y0e,e2e,r2e,o2e,i2e,u2e,c2e,d2e,p2e,m2e,g2e,A2e,v2e,S2e,T2e,R2e,D2e,F2e,M2e,a0e,B2e,V2e,G2e,H2e,q2e,Z2e,J2e,t1e,s1e,i1e,u1e,p1e,f1e,m1e,A1e,v1e,S1e,C1e,E1e,_1e,D1e,UC,M1e,B1e,U1e,H1e,q1e,X1e,K1e,w0e,J1e,tge,sge,age,oge,uge,pge,mge,gge,E0e,xge,vge,Sge,Tge,Ege,_ge,Dge,Pge,Fge,Mge,Bge,Uge,Hge,Xge,Kge,Zge,Qge,nye,aye,u0e,iye,uye];for(let e of cye)qr(e);var uy=Y();uy.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])));uy.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(uy.get("IS_NODE"))return!1;try{return new MessageChannel().port1.postMessage(new SharedArrayBuffer(1)),WebAssembly.validate(new Uint8Array([0,97,115,109,1,0,0,0,1,4,1,96,0,0,3,2,1,0,5,4,1,3,1,1,10,11,1,9,0,65,0,254,16,2,0,26,11]))}catch(e){return!1}});var y4=Vi(pR()),dye=`"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}});`,pye=Vi(hR()),c9=class extends Ou{constructor(e){super(),this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.initWithThreadsCount(d9),cy=this.wasm.tfjs.getThreadsCount(),this.dataIdMap=new Zd(this,sn())}write(e,t,n){let r={id:this.dataIdNextNumber++};return this.move(r,e,t,n,1),r}numDataIds(){return this.dataIdMap.numDataIds()}async time(e){let t=w.now();return e(),{kernelMs:w.now()-t}}move(e,t,n,r,s){let a=this.dataIdNextNumber++;if(r==="string"){let u=t;this.dataIdMap.set(e,{id:a,stringBytes:u,shape:n,dtype:r,memoryOffset:null,refCount:s});return}let o=w.sizeFromShape(n),i=o*w.bytesPerElement(r),l=this.wasm._malloc(i);this.dataIdMap.set(e,{id:a,memoryOffset:l,shape:n,dtype:r,refCount:s}),this.wasm.tfjs.registerTensor(a,o,l),t!=null&&this.wasm.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,i),l)}async read(e){return this.readSync(e)}readSync(e,t,n){let{memoryOffset:r,dtype:s,shape:a,stringBytes:o}=this.dataIdMap.get(e);if(s==="string")return(t==null||t===0)&&(n==null||n>=o.length)?o:o.slice(t,n);t=t||0,n=n||w.sizeFromShape(a);let i=w.bytesPerElement(s),l=this.wasm.HEAPU8.slice(r+t*i,r+n*i);return mye(l.buffer,s)}disposeData(e,t=!1){if(this.dataIdMap.has(e)){let n=this.dataIdMap.get(e);if(n.refCount--,!t&&n.refCount>0)return!1;this.wasm._free(n.memoryOffset),this.wasm.tfjs.disposeData(n.id),this.dataIdMap.delete(e)}return!0}refCount(e){return this.dataIdMap.has(e)?this.dataIdMap.get(e).refCount:0}incRef(e){let t=this.dataIdMap.get(e);t!=null&&t.refCount++}floatPrecision(){return 32}getMemoryOffset(e){return this.dataIdMap.get(e).memoryOffset}dispose(){this.wasm.tfjs.dispose(),"PThread"in this.wasm&&this.wasm.PThread.terminateAllThreads(),this.wasm=null}memory(){return{unreliable:!1}}makeOutput(e,t,n){let r;if(n==null)r=this.write(null,e,t);else{let s=this.dataIdNextNumber++;r={id:s},this.dataIdMap.set(r,{id:s,memoryOffset:n,shape:e,dtype:t,refCount:1});let a=w.sizeFromShape(e);this.wasm.tfjs.registerTensor(s,a,n)}return{dataId:r,shape:e,dtype:t}}typedArrayFromHeap({shape:e,dtype:t,dataId:n}){let r=this.wasm.HEAPU8.buffer,{memoryOffset:s}=this.dataIdMap.get(n),a=w.sizeFromShape(e);switch(t){case"float32":return new Float32Array(r,s,a);case"int32":return new Int32Array(r,s,a);case"bool":return new Uint8Array(r,s,a);default:throw new Error(`Unknown dtype ${t}`)}}};function hye(e){return(t,n)=>(w.fetch(e,{credentials:"same-origin"}).then(r=>{r.ok||t.env.a(`failed to load wasm binary file at '${e}'`),r.arrayBuffer().then(s=>{WebAssembly.instantiate(s,t).then(a=>{n(a.instance,a.module)})})}),{})}function A4(e,t,n){if(jf!=null)return jf;let r="tfjs-backend-wasm.wasm";return e&&t?r="tfjs-backend-wasm-threaded-simd.wasm":e&&(r="tfjs-backend-wasm-simd.wasm"),Pd!=null&&Pd[r]!=null?Pd[r]:n+r}async function fye(){let[e,t]=await Promise.all([Y().getAsync("WASM_HAS_SIMD_SUPPORT"),Y().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise((n,r)=>{let s={};s.locateFile=(i,l)=>{if(i.endsWith(".worker.js")){let u=dye.replace(/\n/g,"\\n"),c=new Blob([u],{type:"application/javascript"});return URL.createObjectURL(c)}return i.endsWith(".wasm")?A4(e,t,Rd!=null?Rd:l):l+i},R3&&(s.instantiateWasm=hye(A4(e,t,Rd!=null?Rd:"")));let a=!1;s.onAbort=()=>{if(a||Fd)return;Fd=!0,r({message:"Make sure the server can serve the `.wasm` file relative to the bundled js file. For more details see https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/README.md#using-bundlers"})};let o;t&&e&&jf==null?(s.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+y4.default.toString()],{type:"text/javascript"}),o=(0,y4.default)(s)):o=(0,pye.default)(s),o.then(i=>{a=!0,Fd=!1;let l=null;i.tfjs={init:i.cwrap("init",null,[]),initWithThreadsCount:i.cwrap("init_with_threads_count",null,["number"]),getThreadsCount:i.cwrap("get_threads_count","number",[]),registerTensor:i.cwrap("register_tensor",null,["number","number","number"]),disposeData:i.cwrap("dispose_data",l,["number"]),dispose:i.cwrap("dispose",l,[])},n({wasm:i})})})}function mye(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 gye=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"],jf=null,Rd=null,Pd={},Fd=!1,R3=!1;function yye(e,t=!1){if($y("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."),Fd)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");jf=e,R3=t}function _3(e,t=!1){if(Fd)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")Rd=e;else{Pd=e;let n=gye.filter(r=>Pd[r]==null);if(n.length>0)throw new Error(`There were no entries found for the following binaries: ${n.join(",")}. Please either call setWasmPaths with a map providing a path for each binary, or with a string indicating the directory where all the binaries can be found.`)}R3=t}var d9=-1,cy=-1;function Aye(e){d9=e}function xye(){if(cy===-1)throw new Error("WASM backend not initialized.");return cy}var bye="0.0.0",vye=2;Rl("wasm",async()=>{let{wasm:e}=await fye();return new c9(e)},vye);var Sa="3.15.0-20220414",Kp={tfjs:Sa,"tfjs-core":Sa,"tfjs-data":Sa,"tfjs-layers":Sa,"tfjs-converter":Sa,"tfjs-backend-cpu":Sa,"tfjs-backend-webgl":Sa,"tfjs-backend-wasm":Sa};var p9=`
|
|
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 h9=`
|
|
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];
|
|
}
|
|
`,f9=`
|
|
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;
|
|
}
|
|
`,m9=`
|
|
precision highp float;
|
|
varying vec2 vUv;
|
|
uniform vec2 size;
|
|
uniform sampler2D texture;
|
|
vec2 pixelate(vec2 coord, vec2 size) {
|
|
return floor( coord / size ) * size;
|
|
}
|
|
void main(void) {
|
|
gl_FragColor = vec4(0.0);
|
|
vec2 coord = pixelate(vUv, size);
|
|
gl_FragColor += texture2D(texture, coord);
|
|
}
|
|
`,g9=`
|
|
precision highp float;
|
|
varying vec2 vUv;
|
|
uniform sampler2D texture;
|
|
uniform vec2 px;
|
|
void main(void) {
|
|
gl_FragColor = vec4(0.0);
|
|
gl_FragColor += texture2D(texture, vUv + vec2(-7.0*px.x, -7.0*px.y))*0.0044299121055113265;
|
|
gl_FragColor += texture2D(texture, vUv + vec2(-6.0*px.x, -6.0*px.y))*0.00895781211794;
|
|
gl_FragColor += texture2D(texture, vUv + vec2(-5.0*px.x, -5.0*px.y))*0.0215963866053;
|
|
gl_FragColor += texture2D(texture, vUv + vec2(-4.0*px.x, -4.0*px.y))*0.0443683338718;
|
|
gl_FragColor += texture2D(texture, vUv + vec2(-3.0*px.x, -3.0*px.y))*0.0776744219933;
|
|
gl_FragColor += texture2D(texture, vUv + vec2(-2.0*px.x, -2.0*px.y))*0.115876621105;
|
|
gl_FragColor += texture2D(texture, vUv + vec2(-1.0*px.x, -1.0*px.y))*0.147308056121;
|
|
gl_FragColor += texture2D(texture, vUv )*0.159576912161;
|
|
gl_FragColor += texture2D(texture, vUv + vec2( 1.0*px.x, 1.0*px.y))*0.147308056121;
|
|
gl_FragColor += texture2D(texture, vUv + vec2( 2.0*px.x, 2.0*px.y))*0.115876621105;
|
|
gl_FragColor += texture2D(texture, vUv + vec2( 3.0*px.x, 3.0*px.y))*0.0776744219933;
|
|
gl_FragColor += texture2D(texture, vUv + vec2( 4.0*px.x, 4.0*px.y))*0.0443683338718;
|
|
gl_FragColor += texture2D(texture, vUv + vec2( 5.0*px.x, 5.0*px.y))*0.0215963866053;
|
|
gl_FragColor += texture2D(texture, vUv + vec2( 6.0*px.x, 6.0*px.y))*0.00895781211794;
|
|
gl_FragColor += texture2D(texture, vUv + vec2( 7.0*px.x, 7.0*px.y))*0.0044299121055113265;
|
|
}
|
|
`,y9=`
|
|
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 $3=(e,t,n)=>{let r=new RegExp("\\b"+t+" \\w+ (\\w+)","ig");e.replace(r,(s,a)=>(n[a]=0,s))},D3=class{constructor(t,n,r){fe(this,"uniform",{});fe(this,"attribute",{});fe(this,"gl");fe(this,"id");fe(this,"compile",(t,n)=>{let r=this.gl.createShader(n);return r?(this.gl.shaderSource(r,t),this.gl.compileShader(r),this.gl.getShaderParameter(r,this.gl.COMPILE_STATUS)?r:(oe(`filter: gl compile failed: ${this.gl.getShaderInfoLog(r)}`),null)):(oe("filter: could not create shader"),null)});this.gl=t;let s=this.compile(n,this.gl.VERTEX_SHADER),a=this.compile(r,this.gl.FRAGMENT_SHADER);if(this.id=this.gl.createProgram(),!(!s||!a)){if(!this.id){oe("filter: could not create webgl program");return}if(this.gl.attachShader(this.id,s),this.gl.attachShader(this.id,a),this.gl.linkProgram(this.id),!this.gl.getProgramParameter(this.id,this.gl.LINK_STATUS)){oe(`filter: gl link failed: ${this.gl.getProgramInfoLog(this.id)}`);return}this.gl.useProgram(this.id),$3(n,"attribute",this.attribute);for(let o in this.attribute)this.attribute[o]=this.gl.getAttribLocation(this.id,o);$3(n,"uniform",this.uniform),$3(r,"uniform",this.uniform);for(let o in this.uniform)this.uniform[o]=this.gl.getUniformLocation(this.id,o)}}};function A9(){let e=0,t=null,n=!1,r=-1,s=[null,null],a=[],o=null,i=null,l=Jn(100,100),u={},c={INTERMEDIATE:1},p=l.getContext("webgl");if(!p){oe("filter: cannot get webgl context");return}this.gl=p;function d(x,A){if(!(x===l.width&&A===l.height)){if(l.width=x,l.height=A,!o){let b=new Float32Array([-1,-1,0,1,1,-1,1,1,-1,1,0,0,-1,1,0,0,1,-1,1,1,1,1,1,0]);o=p.createBuffer(),p.bindBuffer(p.ARRAY_BUFFER,o),p.bufferData(p.ARRAY_BUFFER,b,p.STATIC_DRAW),p.pixelStorei(p.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0)}p.viewport(0,0,l.width,l.height),s=[null,null]}}function h(x,A){let b=p.createFramebuffer();p.bindFramebuffer(p.FRAMEBUFFER,b);let v=p.createRenderbuffer();p.bindRenderbuffer(p.RENDERBUFFER,v);let S=p.createTexture();return p.bindTexture(p.TEXTURE_2D,S),p.texImage2D(p.TEXTURE_2D,0,p.RGBA,x,A,0,p.RGBA,p.UNSIGNED_BYTE,null),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MAG_FILTER,p.LINEAR),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MIN_FILTER,p.LINEAR),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_S,p.CLAMP_TO_EDGE),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_T,p.CLAMP_TO_EDGE),p.framebufferTexture2D(p.FRAMEBUFFER,p.COLOR_ATTACHMENT0,p.TEXTURE_2D,S,0),p.bindTexture(p.TEXTURE_2D,null),p.bindFramebuffer(p.FRAMEBUFFER,null),{fbo:b,texture:S}}function f(x){return s[x]=s[x]||h(l.width,l.height),s[x]}function m(x=0){if(!i)return;let A=null,b=null,v=!1;e===0?A=t:A=f(r).texture||null,e++,n&&!(x&c.INTERMEDIATE)?(b=null,v=e%2===0):(r=(r+1)%2,b=f(r).fbo||null),p.bindTexture(p.TEXTURE_2D,A),p.bindFramebuffer(p.FRAMEBUFFER,b),p.uniform1f(i.uniform.flipY,v?-1:1),p.drawArrays(p.TRIANGLES,0,6)}function g(x){if(u[x])return i=u[x],p.useProgram((i?i.id:null)||null),i;if(i=new D3(p,p9,x),!i)return oe("filter: could not get webgl program"),null;let A=Float32Array.BYTES_PER_ELEMENT,b=4*A;return p.enableVertexAttribArray(i.attribute.pos),p.vertexAttribPointer(i.attribute.pos,2,p.FLOAT,!1,b,0*A),p.enableVertexAttribArray(i.attribute.uv),p.vertexAttribPointer(i.attribute.uv,2,p.FLOAT,!1,b,2*A),u[x]=i,i}let y={colorMatrix:x=>{let A=new Float32Array(x);A[4]/=255,A[9]/=255,A[14]/=255,A[19]/=255;let b=A[18]===1&&A[3]===0&&A[8]===0&&A[13]===0&&A[15]===0&&A[16]===0&&A[17]===0&&A[19]===0?f9:h9,v=g(b);!v||(p.uniform1fv(v.uniform.m,A),m())},brightness:x=>{let A=(x||0)+1;y.colorMatrix([A,0,0,0,0,0,A,0,0,0,0,0,A,0,0,0,0,0,1,0])},saturation:x=>{let A=(x||0)*2/3+1,b=(A-1)*-.5;y.colorMatrix([A,b,b,0,0,b,A,b,0,0,b,b,A,0,0,0,0,0,1,0])},desaturate:()=>{y.saturation(-1)},contrast:x=>{let A=(x||0)+1,b=-128*(A-1);y.colorMatrix([A,0,0,0,b,0,A,0,0,b,0,0,A,0,b,0,0,0,1,0])},negative:()=>{y.contrast(-2)},hue:x=>{x=(x||0)/180*Math.PI;let A=Math.cos(x),b=Math.sin(x),v=.213,S=.715,I=.072;y.colorMatrix([v+A*(1-v)+b*-v,S+A*-S+b*-S,I+A*-I+b*(1-I),0,0,v+A*-v+b*.143,S+A*(1-S)+b*.14,I+A*-I+b*-.283,0,0,v+A*-v+b*-(1-v),S+A*-S+b*S,I+A*(1-I)+b*I,0,0,0,0,0,1,0])},desaturateLuminance:()=>{y.colorMatrix([.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,.2764723,.929708,.0938197,0,-37.1,0,0,0,1,0])},sepia:()=>{y.colorMatrix([.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0])},brownie:()=>{y.colorMatrix([.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0])},vintagePinhole:()=>{y.colorMatrix([.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0])},kodachrome:()=>{y.colorMatrix([1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0])},technicolor:()=>{y.colorMatrix([1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0])},polaroid:()=>{y.colorMatrix([1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0])},shiftToBGR:()=>{y.colorMatrix([0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0])},convolution:x=>{let A=new Float32Array(x),b=1/l.width,v=1/l.height,S=g(y9);!S||(p.uniform1fv(S.uniform.m,A),p.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:x=>{let A=x||1;y.convolution.call(this,[0,-1*A,0,-1*A,1+4*A,-1*A,0,-1*A,0])},emboss:x=>{let A=x||1;y.convolution.call(this,[-2*A,-1*A,0,-1*A,1,1*A,0,1*A,2*A])},blur:x=>{let A=x/7/l.width,b=x/7/l.height,v=g(g9);!v||(p.uniform2f(v.uniform.px,0,b),m(c.INTERMEDIATE),p.uniform2f(v.uniform.px,A,0),m())},pixelate:x=>{let A=x/l.width,b=x/l.height,v=g(m9);!v||(p.uniform2f(v.uniform.size,A,b),m())}};this.add=function(x){let A=Array.prototype.slice.call(arguments,1),b=y[x];a.push({func:b,args:A})},this.reset=function(){a=[]},this.get=function(){return a},this.apply=function(x){d(x.width,x.height),e=0,t||(t=p.createTexture()),p.bindTexture(p.TEXTURE_2D,t),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_S,p.CLAMP_TO_EDGE),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_WRAP_T,p.CLAMP_TO_EDGE),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MIN_FILTER,p.NEAREST),p.texParameteri(p.TEXTURE_2D,p.TEXTURE_MAG_FILTER,p.NEAREST),p.texImage2D(p.TEXTURE_2D,0,p.RGBA,p.RGBA,p.UNSIGNED_BYTE,x);for(let A=0;A<a.length;A++){n=A===a.length-1;let b=a[A];b.func.apply(this,b.args||[])}return l},this.draw=function(x){return this.add("brightness",0),this.apply(x)}}async function _0(e){let t=e.shape.length===4?tt(e):e,n=Yt(t,3,2),r=[Ba(n[0]),Ba(n[1]),Ba(n[2])],s=[gn(n[0]),gn(n[1]),gn(n[2])],a=await Promise.all(s.map(h=>h.data())),o=.99*Math.max(a[0][0],a[1][0],a[2][0]),i=[he(n[0],r[0]),he(n[1],r[1]),he(n[2],r[2])],l=[he(s[0],r[0]),he(s[1],r[1]),he(s[2],r[2])],u=[de(o,l[0]),de(o,l[1]),de(o,l[2])],c=[L(i[0],u[0]),L(i[1],u[1]),L(i[2],u[2])],p=cn([c[0],c[1],c[2]],2),d=H(p,[1,t.shape[0],t.shape[1],3]);return ne([...n,...r,...s,...i,...l,...u,...c,p,t]),d}var $0=2048,ct=null,en=null,Pc=null,Nt,ua={inputSum:0,cacheDiff:1,sumMethod:0,inputTensor:void 0};function Jn(e,t){let n;if(pe.browser)if(pe.worker){if(typeof OffscreenCanvas=="undefined")throw new Error("canvas error: attempted to run in web worker but OffscreenCanvas is not supported");n=new OffscreenCanvas(e,t)}else{if(typeof document=="undefined")throw new Error("canvas error: attempted to run in browser but DOM is not defined");n=document.createElement("canvas"),n.width=e,n.height=t}else typeof pe.Canvas!="undefined"?n=new pe.Canvas(e,t):typeof globalThis.Canvas!="undefined"&&(n=new globalThis.Canvas(e,t));return n}function D0(e,t){let n=t||Jn(e.width,e.height);return n.getContext("2d").drawImage(e,0,0),n}async function Fc(e,t,n=!0){if(!e)return t.debug&&oe("input error: input is missing"),{tensor:null,canvas:null};if(!(e instanceof rt)&&!(typeof Image!="undefined"&&e instanceof Image)&&!(typeof pe.Canvas!="undefined"&&e instanceof pe.Canvas)&&!(typeof globalThis.Canvas!="undefined"&&e instanceof globalThis.Canvas)&&!(typeof ImageData!="undefined"&&e instanceof ImageData)&&!(typeof ImageBitmap!="undefined"&&e instanceof ImageBitmap)&&!(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement)&&!(typeof HTMLMediaElement!="undefined"&&e instanceof HTMLMediaElement)&&!(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)&&!(typeof HTMLCanvasElement!="undefined"&&e instanceof HTMLCanvasElement)&&!(typeof OffscreenCanvas!="undefined"&&e instanceof OffscreenCanvas))throw new Error("input error: type is not recognized");if(e instanceof rt){let r=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)r=Kt(e,0);else if(e.shape[2]===4){let s=Dl(e,[0,0,0],[-1,-1,3]);r=Kt(s,0),ne(s)}}else e.shape.length===4&&(e.shape[3]===3?r=Gn(e):e.shape[3]===4&&(r=Fi(e,[0,0,0,0],[-1,-1,-1,3])));if(r==null||r.shape.length!==4||r.shape[0]!==1||r.shape[3]!==3)throw new Error(`input error: attempted to use tensor with unrecognized shape: ${e.shape}`);if(r.dtype==="int32"){let s=ge(r,"float32");ne(r),r=s}return{tensor:r,canvas:t.filter.return?en:null}}else{if(typeof e.readyState!="undefined"&&e.readyState<=2)return t.debug&&oe("input stream is not ready"),{tensor:null,canvas:ct};let r=e.naturalWidth||e.videoWidth||e.width||e.shape&&e.shape[1]>0,s=e.naturalHeight||e.videoHeight||e.height||e.shape&&e.shape[2]>0;if(!r||!s)return t.debug&&oe("cannot determine input dimensions"),{tensor:null,canvas:ct};let a=r,o=s;if(a>$0&&(a=$0,o=Math.trunc(a*s/r)),o>$0&&(o=$0,a=Math.trunc(o*r/s)),(t.filter.width||0)>0?a=t.filter.width:(t.filter.height||0)>0&&(a=r*((t.filter.height||0)/s)),(t.filter.height||0)>0?o=t.filter.height:(t.filter.width||0)>0&&(o=s*((t.filter.width||0)/r)),!a||!o)throw new Error("input error: cannot determine dimension");(!ct||(ct==null?void 0:ct.width)!==a||(ct==null?void 0:ct.height)!==o)&&(ct=Jn(a,o));let i=ct.getContext("2d");if(typeof ImageData!="undefined"&&e instanceof ImageData?i.putImageData(e,0,0):t.filter.flip&&typeof i.translate!="undefined"?(i.translate(r,0),i.scale(-1,1),i.drawImage(e,0,0,r,s,0,0,ct==null?void 0:ct.width,ct==null?void 0:ct.height),i.setTransform(1,0,0,1,0,0)):i.drawImage(e,0,0,r,s,0,0,ct==null?void 0:ct.width,ct==null?void 0:ct.height),(!en||ct.width!==en.width||(ct==null?void 0:ct.height)!==(en==null?void 0:en.height))&&(en=Jn(ct.width,ct.height)),t.filter.enabled&&pe.webgl.supported?(Nt||(Nt=pe.browser?new A9:null),pe.filter=!!Nt,!Nt||!Nt.add?(t.debug&&oe("input process error: cannot initialize filters"),pe.webgl.supported=!1,t.filter.enabled=!1,D0(ct,en)):(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?en=Nt.apply(ct):en=Nt.draw(ct))):(D0(ct,en),Nt&&(Nt=null),pe.filter=!!Nt),!n)return{tensor:null,canvas:en};if(!en)throw new Error("canvas error: cannot create output");let l,u=3;if(typeof ImageData!="undefined"&&e instanceof ImageData||e.data&&e.width&&e.height)if(pe.browser&&Mr)l=Mr?Mr.fromPixels(e):null;else{u=e.data.length/e.height/e.width;let d=new Uint8Array(e.data.buffer);l=pt(d,[e.height,e.width,u],"int32")}else if((!Pc||en.width!==Pc.width||en.height!==Pc.height)&&(Pc=Jn(en.width,en.height)),Mr&&pe.browser)t.backend==="webgl"||t.backend==="humangl"||t.backend==="webgpu"?l=Mr.fromPixels(en):(Pc=D0(en),l=Mr.fromPixels(Pc));else{let f=D0(en).getContext("2d").getImageData(0,0,a,o);u=f.data.length/a/o;let m=new Uint8Array(f.data.buffer);l=pt(m,[a,o,u])}if(u===4){let d=Dl(l,[0,0,0],[-1,-1,3]);ne(l),l=d}if(!l)throw new Error("input error: cannot create tensor");let c=ge(l,"float32"),p=t.filter.equalization?await _0(c):Kt(c,0);return ne([l,c]),{tensor:p,canvas:t.filter.return?en:null}}}async function x9(e,t){let n=!1;if(e.cacheSensitivity===0||!t.shape||t.shape.length!==4||t.shape[1]>2048||t.shape[2]>2048)return n;if(!ua.inputTensor)ua.inputTensor=Gn(t);else if(ua.inputTensor.shape[1]!==t.shape[1]||ua.inputTensor.shape[2]!==t.shape[2])ne(ua.inputTensor),ua.inputTensor=Gn(t);else{let r={};r.diff=he(t,ua.inputTensor),r.squared=L(r.diff,r.diff),r.sum=ke(r.squared);let a=(await r.sum.data())[0]/(t.shape[1]||1)/(t.shape[2]||1)/255/3;ne([ua.inputTensor,r.diff,r.squared,r.sum]),ua.inputTensor=Gn(t),n=a<=(e.cacheSensitivity||0)}return n}async function b9(e,t,n){let r={};if(!t||!n||t.shape.length!==4||t.shape.length!==n.shape.length)return e.debug||oe("invalid input tensor or tensor shapes do not match:",t.shape,n.shape),0;if(t.shape[0]!==1||n.shape[0]!==1||t.shape[3]!==3||n.shape[3]!==3)return e.debug||oe("input tensors must be of shape [1, height, width, 3]:",t.shape,n.shape),0;r.input1=Gn(t),r.input2=t.shape[1]!==n.shape[1]||t.shape[2]!==n.shape[2]?Se.resizeBilinear(n,[t.shape[1],t.shape[2]]):Gn(n),r.diff=he(r.input1,r.input2),r.squared=L(r.diff,r.diff),r.sum=ke(r.squared);let a=(await r.sum.data())[0]/(t.shape[1]||1)/(t.shape[2]||1)/255/3;return ne([r.input1,r.input2,r.diff,r.squared,r.sum]),a}var P3=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:Kp["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 n=t[0].match(/\(([^()]+)\)/g);this.platform=n&&n[0]?n[0].replace(/\(|\)/g,""):"",this.agent=navigator.userAgent.replace(t[0],""),this.platform[1]&&(this.agent=this.agent.replace(t[1],"")),this.agent=this.agent.replace(/ /g," ")}}else typeof process!="undefined"&&(this.platform=`${process.platform} ${process.arch}`,this.agent=`NodeJS ${process.version}`)}async updateBackend(){this.backends=Object.keys(sn().registryFactory),this.wasm.supported=typeof WebAssembly!="undefined",this.wasm.backend=this.backends.includes("wasm"),this.wasm.supported&&this.wasm.backend&&qn()==="wasm"&&(this.wasm.simd=await Y().getAsync("WASM_HAS_SIMD_SUPPORT"),this.wasm.multithread=await Y().getAsync("WASM_HAS_MULTITHREAD_SUPPORT"));let t=Jn(100,100),n=t?t.getContext("webgl2"):void 0;if(this.webgl.supported=typeof n!="undefined",this.webgl.backend=this.backends.includes("webgl"),this.webgl.supported&&this.webgl.backend&&(qn()==="webgl"||qn()==="humangl")){let r=zr().gpgpu!=="undefined"?await zr().getGPGPUContext().gl:null;r&&(this.webgl.version=r.getParameter(r.VERSION),this.webgl.renderer=r.getParameter(r.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(r){this.webgpu.supported=!1}try{this.kernels=_s(qn()).map(r=>r.kernelName.toLowerCase())}catch(r){}}async updateCPU(){let t={model:"",flags:[]};this.node&&this.platform.startsWith("linux"),this.cpu?this.cpu=t:Object.defineProperty(this,"cpu",{value:t})}},pe=new P3;var ca={cacheModels:!1,verbose:!0,debug:!1,modelBasePath:""};async function Iye(e,t){return ca.debug&&oe("load model fetch:",e,t),fetch(e,t)}function v9(e){ca.cacheModels=e.cacheModels,ca.verbose=e.debug,ca.modelBasePath=e.modelBasePath}async function Ge(e){let t=$b(ca.modelBasePath,e||""),n=t.split("/"),r="indexeddb://"+n[n.length-1].replace(".json",""),s=await Cn.listModels(),a=ca.cacheModels&&Object.keys(s).includes(r),o=typeof fetch=="undefined"?{}:{fetchFunc:(u,c)=>Iye(u,c)},i=new A0(a?r:t,o),l=!1;try{i.findIOHandler(),ca.debug&&oe("model load handler:",i.handler);let u=await i.handler.load();i.loadSync(u),ca.verbose&&oe("load model:",i.modelUrl),l=!0}catch(u){oe("error loading model:",t,u)}if(l&&ca.cacheModels&&!a)try{let u=await i.save(r);oe("model saved:",r,u)}catch(u){oe("error saving model:",t,u)}return i}var F3="2.7.0";var f2={};wa(f2,{Models:()=>ah,load:()=>X5,reset:()=>h2,validate:()=>K5});var Jr,O3=[],Nye=["white","black","asian","indian","other"],Eye=[15,23,28,35.5,45.5,55.5,65],w9=0,k9=0,M3=Number.MAX_SAFE_INTEGER;async function S9(e){return pe.initial&&(Jr=null),Jr?e.debug&&oe("cached model:",Jr.modelUrl):Jr=await Ge(e.face.gear),Jr}async function z3(e,t,n,r){var o,i;if(!Jr)return{age:0,gender:"unknown",genderScore:0,race:[]};let s=M3<(((o=t.face.gear)==null?void 0:o.skipFrames)||0),a=(((i=t.face.gear)==null?void 0:i.skipTime)||0)>le()-k9;return t.skipAllowed&&a&&s&&w9===r&&O3[n]?(M3++,O3[n]):(M3=0,new Promise(async l=>{var y,x;if(!(Jr!=null&&Jr.inputs[0].shape))return;let u={},c=[[0,.1,.9,.9]];u.resize=Se.cropAndResize(e,c,[0],[Jr.inputs[0].shape[2],Jr.inputs[0].shape[1]]);let p={age:0,gender:"unknown",genderScore:0,race:[]};(y=t.face.gear)!=null&&y.enabled&&([u.age,u.gender,u.race]=Jr.execute(u.resize,["age_output","gender_output","race_output"]));let d=await u.gender.data();p.gender=d[0]>d[1]?"male":"female",p.genderScore=Math.round(100*(d[0]>d[1]?d[0]:d[1]))/100;let h=await u.race.data();for(let A=0;A<h.length;A++)h[A]>(((x=t.face.gear)==null?void 0:x.minConfidence)||.2)&&p.race.push({score:Math.round(100*h[A])/100,race:Nye[A]});p.race.sort((A,b)=>b.score-A.score);let m=Array.from(await u.age.data()).map((A,b)=>[Eye[b],A]).sort((A,b)=>b[1]-A[1]),g=m[0][0];for(let A=1;A<m.length;A++)g+=m[A][1]*(m[A][0]-g);p.age=Math.round(10*g)/10,Object.keys(u).forEach(A=>ne(u[A])),O3[n]=p,w9=r,k9=le(),l(p)}))}var Je={tf255:255,tf1:1,tf2:2,tf05:.5,tf127:127.5,rgb:[.2989,.587,.114]};function C9(){Je.tf255=Ie(255,"float32"),Je.tf1=Ie(1,"float32"),Je.tf2=Ie(2,"float32"),Je.tf05=Ie(.5,"float32"),Je.tf127=Ie(127.5,"float32"),Je.rgb=Ct([.2989,.587,.114],"float32")}var xr,P0=[],T9=0,N9=0,L3=Number.MAX_SAFE_INTEGER;async function E9(e){return pe.initial&&(xr=null),xr?e.debug&&oe("cached model:",xr.modelUrl):xr=await Ge(e.face.ssrnet.modelPathAge),xr}async function B3(e,t,n,r){var o,i,l,u;if(!xr)return{age:0};let s=L3<(((o=t.face.ssrnet)==null?void 0:o.skipFrames)||0),a=(((i=t.face.ssrnet)==null?void 0:i.skipTime)||0)>le()-N9;return t.skipAllowed&&s&&a&&T9===r&&((l=P0[n])==null?void 0:l.age)&&((u=P0[n])==null?void 0:u.age)>0?(L3++,P0[n]):(L3=0,new Promise(async c=>{if(!(xr!=null&&xr.inputs)||!xr.inputs[0]||!xr.inputs[0].shape)return;let p={};p.resize=Se.resizeBilinear(e,[xr.inputs[0].shape[2],xr.inputs[0].shape[1]],!1),p.enhance=L(p.resize,Je.tf255);let d={age:0};if(t.face.ssrnet.enabled&&(p.age=xr.execute(p.enhance)),p.age){let h=await p.age.data();d.age=Math.trunc(10*h[0])/10}Object.keys(p).forEach(h=>ne(p[h])),P0[n]=d,T9=r,N9=le(),c(d)}))}var Qr,F0=[],_9=0,$9=0,W3=Number.MAX_SAFE_INTEGER,V3=[.2989,.587,.114];async function D9(e){return pe.initial&&(Qr=null),Qr?e.debug&&oe("cached model:",Qr.modelUrl):Qr=await Ge(e.face.ssrnet.modelPathGender),Qr}async function U3(e,t,n,r){var o,i,l,u;if(!Qr)return{gender:"unknown",genderScore:0};let s=W3<(((o=t.face.ssrnet)==null?void 0:o.skipFrames)||0),a=(((i=t.face.ssrnet)==null?void 0:i.skipTime)||0)>le()-$9;return t.skipAllowed&&s&&a&&_9===r&&((l=F0[n])==null?void 0:l.gender)&&((u=F0[n])==null?void 0:u.genderScore)>0?(W3++,F0[n]):(W3=0,new Promise(async c=>{if(!(Qr!=null&&Qr.inputs[0].shape))return;let p={};p.resize=Se.resizeBilinear(e,[Qr.inputs[0].shape[2],Qr.inputs[0].shape[1]],!1),p.enhance=K(()=>{let[f,m,g]=Yt(p.resize,3,3),y=L(f,V3[0]),x=L(m,V3[1]),A=L(g,V3[2]),b=km([y,x,A]);return L(he(b,Je.tf05),2)});let d={gender:"unknown",genderScore:0};t.face.ssrnet.enabled&&(p.gender=Qr.execute(p.enhance));let h=await p.gender.data();d.gender=h[0]>h[1]?"female":"male",d.genderScore=h[0]>h[1]?Math.trunc(100*h[0])/100:Math.trunc(100*h[1])/100,Object.keys(p).forEach(f=>ne(p[f])),F0[n]=d,_9=r,$9=le(),c(d)}))}var Rn,O0=[],G3=Number.MAX_SAFE_INTEGER,F9=0,O9=0;async function M9(e){var t;return pe.initial&&(Rn=null),Rn?e.debug&&oe("cached model:",Rn.modelUrl):Rn=await Ge((t=e.face.antispoof)==null?void 0:t.modelPath),Rn}async function H3(e,t,n,r){var o,i;if(!Rn)return 0;let s=(((o=t.face.antispoof)==null?void 0:o.skipTime)||0)>le()-O9,a=G3<(((i=t.face.antispoof)==null?void 0:i.skipFrames)||0);return t.skipAllowed&&s&&a&&F9===r&&O0[n]?(G3++,O0[n]):(G3=0,new Promise(async l=>{let u=Se.resizeBilinear(e,[Rn!=null&&Rn.inputs[0].shape?Rn.inputs[0].shape[2]:0,Rn!=null&&Rn.inputs[0].shape?Rn.inputs[0].shape[1]:0],!1),c=Rn==null?void 0:Rn.execute(u),p=(await c.data())[0];O0[n]=Math.round(100*p)/100,F9=r,O9=le(),ne([u,c]),l(O0[n])}))}var es={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]},j3={count:468,mouth:13,symmetryLine:[13,es.midwayBetweenEyes[0]]},Yp={leftEye:0,rightEye:1,nose:2,mouth:3,leftEar:4,rightEar:5,symmetryLine:[3,2]},q3=[{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]}],Jp=[[.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]],Bl=[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 _ye=[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],$ye=[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],Dye=[33,133,362,263,1,78,308],T7e=_ye.map(e=>Jp[e]),N7e=$ye.map(e=>Jp[e]),E7e=Dye.map(e=>Jp[e]);function Yo(e){let t=e.map(n=>n[0]);return t.push(e[e.length-1][1]),t}var Pye=[[61,146],[146,91],[91,181],[181,84],[84,17],[17,314],[314,405],[405,321],[321,375],[375,291],[61,185],[185,40],[40,39],[39,37],[37,0],[0,267],[267,269],[269,270],[270,409],[409,291],[78,95],[95,88],[88,178],[178,87],[87,14],[14,317],[317,402],[402,318],[318,324],[324,308],[78,191],[191,80],[80,81],[81,82],[82,13],[13,312],[312,311],[311,310],[310,415],[415,308]],Fye=[[263,249],[249,390],[390,373],[373,374],[374,380],[380,381],[381,382],[382,362],[263,466],[466,388],[388,387],[387,386],[386,385],[385,384],[384,398],[398,362]],Oye=[[276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]],Mye=[[474,475],[475,476],[476,477],[477,474]],zye=[[33,7],[7,163],[163,144],[144,145],[145,153],[153,154],[154,155],[155,133],[33,246],[246,161],[161,160],[160,159],[159,158],[158,157],[157,173],[173,133]],Lye=[[46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]],Bye=[[469,470],[470,471],[471,472],[472,469]],Wye=[[10,338],[338,297],[297,332],[332,284],[284,251],[251,389],[389,356],[356,454],[454,323],[323,361],[361,288],[288,397],[397,365],[365,379],[379,378],[378,400],[400,377],[377,152],[152,148],[148,176],[176,149],[149,150],[150,136],[136,172],[172,58],[58,132],[132,93],[93,234],[234,127],[127,162],[162,21],[21,54],[54,103],[103,67],[67,109],[109,10]],R7e={lips:Yo(Pye),leftEye:Yo(Fye),leftEyebrow:Yo(Oye),leftIris:Yo(Mye),rightEye:Yo(zye),rightEyebrow:Yo(Lye),rightIris:Yo(Bye),faceOval:Yo(Wye)};var Oc=e=>[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])],M0=e=>[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2,1],Y3=(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],J3=(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],W9=(e,t)=>{let n=[e.startPoint[0]*t[0],e.startPoint[1]*t[1]],r=[e.endPoint[0]*t[0],e.endPoint[1]*t[1]];return{startPoint:n,endPoint:r,landmarks:e.landmarks,confidence:e.confidence}},K3=(e,t,n)=>{let r=t.shape[1],s=t.shape[2],a=[e.startPoint[1]/r,e.startPoint[0]/s,e.endPoint[1]/r,e.endPoint[0]/s],o=Se.cropAndResize(t,[a],[0],n),i=de(o,Je.tf255);return ne(o),i},z0=(e,t)=>{let n=M0(e),r=Oc(e),s=[t*r[0]/2,t*r[1]/2];return{startPoint:[n[0]-s[0],n[1]-s[1]],endPoint:[n[0]+s[0],n[1]+s[1]],landmarks:e.landmarks,confidence:e.confidence}},L0=e=>{let t=M0(e),n=Oc(e),r=Math.max(...n)/2;return{startPoint:[Math.round(t[0]-r),Math.round(t[1]-r)],endPoint:[Math.round(t[0]+r),Math.round(t[1]+r)],landmarks:e.landmarks,confidence:e.confidence}},V9=e=>{let t=e.map(r=>r[0]),n=e.map(r=>r[1]);return{startPoint:[Math.min(...t),Math.min(...n)],endPoint:[Math.max(...t),Math.max(...n)],landmarks:e}},Z3=[[1,0,0],[0,1,0],[0,0,1]],Vye=e=>e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI)),Uye=(e,t)=>Vye(Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]));var L9=(e,t)=>[[1,0,e],[0,1,t],[0,0,1]],Wl=(e,t)=>{let n=0;for(let r=0;r<e.length;r++)n+=e[r]*t[r];return n},Gye=(e,t)=>{let n=[];for(let r=0;r<e.length;r++)n.push(e[r][t]);return n},B9=(e,t)=>{let n=[],r=e.length;for(let s=0;s<r;s++){n.push([]);for(let a=0;a<r;a++)n[s].push(Wl(e[s],Gye(t,a)))}return n},U9=(e,t)=>{let n=Math.cos(e),r=Math.sin(e),s=[[n,-r,0],[r,n,0],[0,0,1]],a=L9(t[0],t[1]),o=B9(a,s),i=L9(-t[0],-t[1]);return B9(o,i)},Hye=e=>{let t=[[e[0][0],e[1][0]],[e[0][1],e[1][1]]],n=[e[0][2],e[1][2]],r=[-Wl(t[0],n),-Wl(t[1],n)];return[t[0].concat(r[0]),t[1].concat(r[1]),[0,0,1]]},jye=(e,t)=>[Wl(e,t[0]),Wl(e,t[1])];function G9(e){let t={strides:[e/16,e/8],anchors:[2,6]},n=[];for(let r=0;r<t.strides.length;r++){let s=t.strides[r],a=Math.floor((e+s-1)/s),o=Math.floor((e+s-1)/s),i=t.anchors[r];for(let l=0;l<a;l++){let u=s*(l+.5);for(let c=0;c<o;c++){let p=s*(c+.5);for(let d=0;d<i;d++)n.push([p,u])}}}return n}function H9(e,t,n,r,s){let a=Oc(t),o=e.map(h=>[a[0]/s*(h[0]-s/2),a[1]/s*(h[1]-s/2),h[2]||0]),i=n&&n!==0&&Math.abs(n)>.2,l=i?U9(n,[0,0]):Z3,u=i?o.map(h=>[...jye(h,l),h[2]]):o,c=i?Hye(r):Z3,p=M0(t),d=[Wl(p,c[0]),Wl(p,c[1])];return u.map(h=>[Math.trunc(h[0]+d[0]),Math.trunc(h[1]+d[1]),Math.trunc(h[2]||0)])}function j9(e,t,n,r){let s=t.landmarks.length>=j3.count?j3.symmetryLine:Yp.symmetryLine,a=0,o=Z3,i;if(e&&pe.kernels.includes("rotatewithoffset"))if(a=Uye(t.landmarks[s[0]],t.landmarks[s[1]]),a&&a!==0&&Math.abs(a)>.2){let u=M0(t),c=[u[0]/n.shape[2],u[1]/n.shape[1]],p=Se.rotateWithOffset(n,a,0,c);o=U9(-a,u),i=K3(t,p,[r,r]),ne(p)}else i=K3(t,n,[r,r]);else i=K3(t,n,[r,r]);return[a,o,i]}var qye=e=>{let t=e.map(r=>r[0]),n=e.map(r=>r[1]);return[Math.min(...t)+(Math.max(...t)-Math.min(...t))/2,Math.min(...n)+(Math.max(...n)-Math.min(...n))/2]},q9=(e,t)=>{let n=qye(e),r=Oc(t);return{startPoint:[n[0]-r[0]/2,n[1]-r[1]/2],endPoint:[n[0]+r[0]/2,n[1]+r[1]/2]}};var X9=6,Xye=1.4,zs,K9=null,Jo=0,Qp=null,B0=()=>Jo;async function Z9(e){var t;return pe.initial&&(zs=null),zs?e.debug&&oe("cached model:",zs.modelUrl):zs=await Ge((t=e.face.detector)==null?void 0:t.modelPath),Jo=zs.inputs[0].shape?zs.inputs[0].shape[2]:0,Qp=Ie(Jo,"int32"),K9=ps(G9(Jo)),zs}function Kye(e){let t={};t.boxStarts=Pe(e,[0,1],[-1,2]),t.centers=ue(t.boxStarts,K9),t.boxSizes=Pe(e,[0,3],[-1,2]),t.boxSizesNormalized=de(t.boxSizes,Qp),t.centersNormalized=de(t.centers,Qp),t.halfBoxSize=de(t.boxSizesNormalized,Je.tf2),t.starts=he(t.centersNormalized,t.halfBoxSize),t.ends=ue(t.centersNormalized,t.halfBoxSize),t.startNormalized=L(t.starts,Qp),t.endNormalized=L(t.ends,Qp);let n=pc([t.startNormalized,t.endNormalized],1);return Object.keys(t).forEach(r=>ne(t[r])),n}async function Y9(e,t){var i,l,u,c;if(!e||e.isDisposedInternal||e.shape.length!==4||e.shape[1]<1||e.shape[2]<1)return[];let n={};n.resized=Se.resizeBilinear(e,[Jo,Jo]),n.div=de(n.resized,Je.tf127),n.normalized=he(n.div,Je.tf05);let r=zs==null?void 0:zs.execute(n.normalized);if(Array.isArray(r)){let p=r.sort((d,h)=>d.size-h.size);n.concat384=St([p[0],p[2]],2),n.concat512=St([p[1],p[3]],2),n.concat=St([n.concat512,n.concat384],1),n.batch=tt(n.concat,0)}else n.batch=tt(r);ne(r),n.boxes=Kye(n.batch),n.logits=Pe(n.batch,[0,0],[-1,1]),n.sigmoid=Tn(n.logits),n.scores=tt(n.sigmoid),n.nms=await Se.nonMaxSuppressionAsync(n.boxes,n.scores,((i=t.face.detector)==null?void 0:i.maxDetected)||0,((l=t.face.detector)==null?void 0:l.iouThreshold)||0,((u=t.face.detector)==null?void 0:u.minConfidence)||0);let s=await n.nms.array(),a=[],o=await n.scores.data();for(let p=0;p<s.length;p++){let d=o[s[p]];if(d>(((c=t.face.detector)==null?void 0:c.minConfidence)||0)){let h={};h.bbox=Pe(n.boxes,[s[p],0],[1,-1]),h.slice=Pe(n.batch,[s[p],X9-1],[1,-1]),h.squeeze=tt(h.slice),h.landmarks=H(h.squeeze,[X9,-1]);let f=await h.bbox.data(),m={startPoint:[f[0],f[1]],endPoint:[f[2],f[3]],landmarks:await h.landmarks.array(),confidence:d},g=W9(m,[(e.shape[2]||0)/Jo,(e.shape[1]||0)/Jo]),y=z0(g,t.face.scale||Xye),x=L0(y);a.push(x),Object.keys(h).forEach(A=>ne(h[A]))}}return Object.keys(n).forEach(p=>ne(n[p])),a}var W0={};wa(W0,{connected:()=>t5,kpt:()=>e5});var e5=["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"],t5={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 Q9=224,Zye,Yye=5,V0=[8,16,32,32,32];async function eT(){let e=[],t=0;for(;t<Yye;){let n=0,r=t;for(;r<V0.length&&V0[r]===V0[t];)n+=2,r++;let s=V0[t],a=Math.ceil(Q9/s),o=Math.ceil(Q9/s);for(let i=0;i<a;++i)for(let l=0;l<o;++l)for(let u=0;u<n;++u)e.push({x:(l+.5)/o,y:(i+.5)/a});t=r}Zye={x:Ct(e.map(n=>n.x)),y:Ct(e.map(n=>n.y))}}function da(e,t=[1,1]){let n=[e.map(i=>i[0]),e.map(i=>i[1])],r=[Math.min(...n[0]),Math.min(...n[1])],s=[Math.max(...n[0]),Math.max(...n[1])],a=[r[0],r[1],s[0]-r[0],s[1]-r[1]],o=[a[0]/t[0],a[1]/t[1],a[2]/t[0],a[3]/t[1]];return{box:a,boxRaw:o}}function tT(e,t=[1,1]){let n=[e.map(u=>u[0]),e.map(u=>u[1])],r=[Math.min(...n[0]),Math.min(...n[1])],s=[Math.max(...n[0]),Math.max(...n[1])],a=[(r[0]+s[0])/2,(r[1]+s[1])/2],o=Math.max(a[0]-r[0],a[1]-r[1],-a[0]+s[0],-a[1]+s[1]),i=[Math.trunc(a[0]-o),Math.trunc(a[1]-o),Math.trunc(2*o),Math.trunc(2*o)],l=[i[0]/t[0],i[1]/t[1],i[2]/t[0],i[3]/t[1]];return{box:i,boxRaw:l}}function U0(e,t){let n=[e[2]*t,e[3]*t];return[e[0]-(n[0]-e[2])/2,e[1]-(n[1]-e[3])/2,n[0],n[1]]}var sT={initial:!0},br={detector:null,landmarks:null},Mc={detector:[224,224],landmarks:[256,256]},n5=Number.MAX_SAFE_INTEGER,Qye={landmarks:["ld_3d","activation_segmentation","activation_heatmap","world_3d","output_poseflag"],detector:[]},H0=null,eh,Qo=[[0,0],[0,0],[0,0],[0,0]],nT=0,rT=e=>1-1/(1+Math.exp(e));async function aT(e){if(sT.initial&&(br.detector=null),!br.detector&&e.body.detector&&e.body.detector.modelPath){br.detector=await Ge(e.body.detector.modelPath);let t=Object.values(br.detector.modelSignature.inputs);Mc.detector[0]=Array.isArray(t)?parseInt(t[0].tensorShape.dim[1].size):0,Mc.detector[1]=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):0}else e.debug&&br.detector&&oe("cached model:",br.detector.modelUrl);return await eT(),br.detector}async function oT(e){if(sT.initial&&(br.landmarks=null),br.landmarks)e.debug&&oe("cached model:",br.landmarks.modelUrl);else{br.landmarks=await Ge(e.body.modelPath);let t=Object.values(br.landmarks.modelSignature.inputs);Mc.landmarks[0]=Array.isArray(t)?parseInt(t[0].tensorShape.dim[1].size):0,Mc.landmarks[1]=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):0}return br.landmarks}async function eAe(e,t){let n={};if(!e.shape||!e.shape[1]||!e.shape[2])return e;let r;if(eh&&(n.cropped=Se.cropAndResize(e,[eh],[0],[e.shape[1],e.shape[2]])),e.shape[1]!==e.shape[2]){let s=[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],a=[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];Qo=[[0,0],s,a,[0,0]],n.pad=Xr(n.cropped||e,Qo),n.resize=Se.resizeBilinear(n.pad,[t,t]),r=de(n.resize,Je.tf255)}else e.shape[1]!==t?(n.resize=Se.resizeBilinear(n.cropped||e,[t,t]),r=de(n.resize,Je.tf255)):r=de(n.cropped||e,Je.tf255);return Object.keys(n).forEach(s=>ne(n[s])),r}function tAe(e,t){for(let n of e)n.position=[Math.trunc(n.position[0]*(t[0]+Qo[2][0]+Qo[2][1])/t[0]-Qo[2][0]),Math.trunc(n.position[1]*(t[1]+Qo[1][0]+Qo[1][1])/t[1]-Qo[1][0]),n.position[2]],n.positionRaw=[n.position[0]/t[0],n.position[1]/t[1],2*n.position[2]/(t[0]+t[1])];if(eh)for(let n of e)n.positionRaw=[n.positionRaw[0]+eh[1],n.positionRaw[1]+eh[0],n.positionRaw[2]],n.position=[Math.trunc(n.positionRaw[0]*t[0]),Math.trunc(n.positionRaw[1]*t[1]),n.positionRaw[2]];return e}async function nAe(e){let t=e.find(i=>i.part==="leftPalm"),n=e.find(i=>i.part==="leftWrist"),r=e.find(i=>i.part==="leftIndex");t.position[2]=((n.position[2]||0)+(r.position[2]||0))/2;let s=e.find(i=>i.part==="rightPalm"),a=e.find(i=>i.part==="rightWrist"),o=e.find(i=>i.part==="rightIndex");s.position[2]=((a.position[2]||0)+(o.position[2]||0))/2}async function rAe(e,t,n){var f;let r={};[r.ld,r.segmentation,r.heatmap,r.world,r.poseflag]=(f=br.landmarks)==null?void 0:f.execute(e,Qye.landmarks);let s=(await r.poseflag.data())[0],a=await r.ld.data(),o=await r.world.data();Object.keys(r).forEach(m=>ne(r[m]));let i=[],l=5;for(let m=0;m<a.length/l;m++){let g=rT(a[l*m+3]),y=rT(a[l*m+4]),x=Math.trunc(100*g*y*s)/100,A=[a[l*m+0]/Mc.landmarks[0],a[l*m+1]/Mc.landmarks[1],a[l*m+2]+0],b=[Math.trunc(n[0]*A[0]),Math.trunc(n[1]*A[1]),A[2]],v=[o[l*m+0],o[l*m+1],o[l*m+2]+0];i.push({part:e5[m],positionRaw:A,position:b,distance:v,score:x})}if(s<(t.body.minConfidence||0))return null;nAe(i);let u=tAe(i,n),c=u.map(m=>m.position),p=da(c,[n[0],n[1]]),d={};for(let[m,g]of Object.entries(t5)){let y=[];for(let x=0;x<g.length-1;x++){let A=u.find(v=>v.part===g[x]),b=u.find(v=>v.part===g[x+1]);A&&b&&y.push([A.position,b.position])}d[m]=y}return{id:0,score:Math.trunc(100*s)/100,box:p.box,boxRaw:p.boxRaw,keypoints:u,annotations:d}}async function r5(e,t){let n=[e.shape[2]||0,e.shape[1]||0],r=(t.body.skipTime||0)>le()-nT,s=n5<(t.body.skipFrames||0);if(t.skipAllowed&&r&&s&&H0!==null)n5++;else{let a={};a.landmarks=await eAe(e,256),H0=await rAe(a.landmarks,t,n),Object.keys(a).forEach(o=>ne(a[o])),nT=le(),n5=0}return H0?[H0]:[]}var zc=[{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 pa,Vl=0,s5=[],lT=0,a5=Number.MAX_SAFE_INTEGER;async function uT(e){if(pe.initial&&(pa=null),pa)e.debug&&oe("cached model:",pa.modelUrl);else{pa=await Ge(e.object.modelPath);let t=Object.values(pa.modelSignature.inputs);Vl=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):0}return pa}async function sAe(e,t,n){if(!e)return[];let r={},s=[],a=await e.array();r.squeeze=tt(e);let o=Yt(r.squeeze,6,1);r.stack=cn([o[1],o[0],o[3],o[2]],1),r.boxes=tt(r.stack),r.scores=tt(o[4]),r.classes=tt(o[5]),ne([e,...o]),r.nms=await Se.nonMaxSuppressionAsync(r.boxes,r.scores,n.object.maxDetected,n.object.iouThreshold,n.object.minConfidence||0);let i=await r.nms.data(),l=0;for(let u of Array.from(i)){let c=Math.trunc(100*a[0][u][4])/100,p=a[0][u][5],d=zc[p].label,[h,f]=[a[0][u][0]/Vl,a[0][u][1]/Vl],m=[h,f,a[0][u][2]/Vl-h,a[0][u][3]/Vl-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])];s.push({id:l++,score:c,class:p,label:d,box:g,boxRaw:m})}return Object.keys(r).forEach(u=>ne(r[u])),s}async function o5(e,t){let n=(t.object.skipTime||0)>le()-lT,r=a5<(t.object.skipFrames||0);return t.skipAllowed&&n&&r&&s5.length>0?(a5++,s5):(a5=0,new Promise(async s=>{let a=[e.shape[2]||0,e.shape[1]||0],o=Se.resizeBilinear(e,[Vl,Vl]),i=t.object.enabled?pa==null?void 0:pa.execute(o,["tower_0/detections"]):null;lT=le(),ne(o);let l=await sAe(i,a,t);s5=l,s(l)}))}var j0={};wa(j0,{connected:()=>l5,kpt:()=>i5});var i5=["head","neck","rightShoulder","rightElbow","rightWrist","chest","leftShoulder","leftElbow","leftWrist","bodyCenter","rightHip","rightKnee","rightAnkle","leftHip","leftKnee","leftAnkle"],l5={leftLeg:["leftHip","leftKnee","leftAnkle"],rightLeg:["rightHip","rightKnee","rightAnkle"],torso:["leftShoulder","rightShoulder","rightHip","leftHip","leftShoulder"],leftArm:["leftShoulder","leftElbow","leftWrist"],rightArm:["rightShoulder","rightElbow","rightWrist"],head:[]};var _n,dT=0,Qn={id:0,keypoints:[],box:[0,0,0,0],boxRaw:[0,0,0,0],score:0,annotations:{}},u5=Number.MAX_SAFE_INTEGER;async function pT(e){return pe.initial&&(_n=null),_n?e.debug&&oe("cached model:",_n.modelUrl):_n=await Ge(e.body.modelPath),_n}async function aAe(e,t){let[n,r]=e.shape,s=H(e,[r*n]),a=gn(s,0),o=(await a.data())[0];if(ne([s,a]),o>t){let i=Rr(s,0),l=mc(i,n),u=(await l.data())[0],c=de(i,Ie(n,"int32")),p=(await c.data())[0];return ne([l,c]),[u,p,o]}return[0,0,o]}async function c5(e,t){let n=(t.body.skipTime||0)>le()-dT,r=u5<(t.body.skipFrames||0);return t.skipAllowed&&n&&r&&Object.keys(Qn.keypoints).length>0?(u5++,[Qn]):(u5=0,new Promise(async s=>{var p;let a=K(()=>{if(!(_n!=null&&_n.inputs[0].shape))return null;let d=Se.resizeBilinear(e,[_n.inputs[0].shape[2],_n.inputs[0].shape[1]],!1),h=L(d,Je.tf2);return he(h,Je.tf1)}),o;if(t.body.enabled&&(o=_n==null?void 0:_n.execute(a)),dT=le(),ne(a),o){Qn.keypoints.length=0;let d=o.squeeze();ne(o);let h=d.unstack(2);ne(d);for(let f=0;f<h.length;f++){let[m,g,y]=await aAe(h[f],t.body.minConfidence);y>(((p=t.body)==null?void 0:p.minConfidence)||0)&&Qn.keypoints.push({score:Math.round(100*y)/100,part:i5[f],positionRaw:[m/_n.inputs[0].shape[2],g/_n.inputs[0].shape[1]],position:[Math.round(e.shape[2]*m/_n.inputs[0].shape[2]),Math.round(e.shape[1]*g/_n.inputs[0].shape[1])]})}h.forEach(f=>ne(f))}Qn.score=Qn.keypoints.reduce((d,h)=>h.score>d?h.score:d,0);let i=Qn.keypoints.map(d=>d.position[0]),l=Qn.keypoints.map(d=>d.position[1]);Qn.box=[Math.min(...i),Math.min(...l),Math.max(...i)-Math.min(...i),Math.max(...l)-Math.min(...l)];let u=Qn.keypoints.map(d=>d.positionRaw[0]),c=Qn.keypoints.map(d=>d.positionRaw[1]);Qn.boxRaw=[Math.min(...u),Math.min(...c),Math.max(...u)-Math.min(...u),Math.max(...c)-Math.min(...c)];for(let[d,h]of Object.entries(l5)){let f=[];for(let m=0;m<h.length-1;m++){let g=Qn.keypoints.find(x=>x.part===h[m]),y=Qn.keypoints.find(x=>x.part===h[m+1]);g&&y&&g.score>(t.body.minConfidence||0)&&y.score>(t.body.minConfidence||0)&&f.push([g.position,y.position])}Qn.annotations[d]=f}s([Qn])}))}var oAe=["angry","disgust","fear","happy","sad","surprise","neutral"],Br,q0=[],fT=0,mT=0,d5=Number.MAX_SAFE_INTEGER;async function gT(e){var t;return pe.initial&&(Br=null),Br?e.debug&&oe("cached model:",Br.modelUrl):Br=await Ge((t=e.face.emotion)==null?void 0:t.modelPath),Br}async function p5(e,t,n,r){var o,i;if(!Br)return[];let s=d5<(((o=t.face.emotion)==null?void 0:o.skipFrames)||0),a=(((i=t.face.emotion)==null?void 0:i.skipTime)||0)>le()-mT;return t.skipAllowed&&a&&s&&fT===r&&q0[n]&&q0[n].length>0?(d5++,q0[n]):(d5=0,new Promise(async l=>{var c,p;let u=[];if((c=t.face.emotion)!=null&&c.enabled){let d={},h=Br!=null&&Br.inputs[0].shape?Br.inputs[0].shape[2]:0;d.resize=Se.resizeBilinear(e,[h,h],!1),d.channels=L(d.resize,Je.rgb),d.grayscale=ke(d.channels,3,!0),d.grayscaleSub=he(d.grayscale,Je.tf05),d.grayscaleMul=L(d.grayscaleSub,Je.tf2),d.emotion=Br==null?void 0:Br.execute(d.grayscaleMul),mT=le();let f=await d.emotion.data();for(let m=0;m<f.length;m++)f[m]>(((p=t.face.emotion)==null?void 0:p.minConfidence)||0)&&u.push({score:Math.min(.99,Math.trunc(100*f[m])/100),emotion:oAe[m]});u.sort((m,g)=>g.score-m.score),Object.keys(d).forEach(m=>ne(d[m]))}q0[n]=u,fT=r,l(u)}))}var vr,h5=[],AT=0,xT=0,bT=Number.MAX_SAFE_INTEGER;async function vT(e){return pe.initial&&(vr=null),vr?e.debug&&oe("cached model:",vr.modelUrl):vr=await Ge(e.face.mobilefacenet.modelPath),vr}async function f5(e,t,n,r){var o,i;if(!vr)return[];let s=bT<(((o=t.face.embedding)==null?void 0:o.skipFrames)||0),a=(((i=t.face.embedding)==null?void 0:i.skipTime)||0)>le()-xT;return t.skipAllowed&&a&&s&&AT===r&&h5[n]?(bT++,h5[n]):new Promise(async l=>{var c;let u=[];if(((c=t.face.embedding)==null?void 0:c.enabled)&&(vr==null?void 0:vr.inputs[0].shape)){let p={};p.crop=Se.resizeBilinear(e,[vr.inputs[0].shape[2],vr.inputs[0].shape[1]],!1),p.data=vr==null?void 0:vr.execute(p.crop);let d=await p.data.data();u=Array.from(d)}h5[n]=u,AT=r,xT=le(),l(u)})}var ha,ei=0,iAe=2.3,m5=es.leftEyeLower0,g5=es.rightEyeLower0,Lc={leftBounds:[m5[0],m5[m5.length-1]],rightBounds:[g5[0],g5[g5.length-1]]},Bc={upperCenter:3,lowerCenter:4,index:71,numCoordinates:76};async function CT(e){var t;return pe.initial&&(ha=null),ha?e.debug&&oe("cached model:",ha.modelUrl):ha=await Ge((t=e.face.iris)==null?void 0:t.modelPath),ei=ha.inputs[0].shape?ha.inputs[0].shape[2]:0,ei===-1&&(ei=64),ha}function X0(e,t,n,r){for(let s=0;s<q3.length;s++){let{key:a,indices:o}=q3[s],i=es[`${n}${a}`];if(!r||r.includes(a))for(let l=0;l<o.length;l++){let u=o[l];e[i[l]]=[t[u][0],t[u][1],(t[u][2]+e[i[l]][2])/2]}}}var lAe=e=>{let t=e[Lc.leftBounds[0]][2],n=e[Lc.rightBounds[0]][2];return t-n},kT=(e,t,n,r,s,a=!1)=>{let o=L0(z0(V9([e[n],e[r]]),iAe)),i=Oc(o),l=Se.cropAndResize(t,[[o.startPoint[1]/s,o.startPoint[0]/s,o.endPoint[1]/s,o.endPoint[0]/s]],[0],[ei,ei]);if(a&&pe.kernels.includes("flipleftright")){let u=Se.flipLeftRight(l);ne(l),l=u}return{box:o,boxSize:i,crop:l}},ST=(e,t,n,r=!1)=>{let s=[];for(let a=0;a<Bc.numCoordinates;a++){let o=e[a*3],i=e[a*3+1],l=e[a*3+2];s.push([(r?1-o/ei:o/ei)*n[0]+t.startPoint[0],i/ei*n[1]+t.startPoint[1],l])}return{rawCoords:s,iris:s.slice(Bc.index)}},IT=(e,t,n)=>{let r=e[es[`${n}EyeUpper0`][Bc.upperCenter]][2],s=e[es[`${n}EyeLower0`][Bc.lowerCenter]][2],a=(r+s)/2;return t.map((o,i)=>{let l=a;return i===2?l=r:i===4&&(l=s),[o[0],o[1],l]})};async function TT(e,t,n,r){if(!ha)return n.debug&&oe("face mesh iris detection requested, but model is not loaded"),e;let{box:s,boxSize:a,crop:o}=kT(e,t,Lc.leftBounds[0],Lc.leftBounds[1],r,!0),{box:i,boxSize:l,crop:u}=kT(e,t,Lc.rightBounds[0],Lc.rightBounds[1],r,!0),c=St([o,u]);ne(o),ne(u);let p=ha.execute(c);ne(c);let d=await p.data();ne(p);let h=d.slice(0,Bc.numCoordinates*3),{rawCoords:f,iris:m}=ST(h,s,a,!0),g=d.slice(Bc.numCoordinates*3),{rawCoords:y,iris:x}=ST(g,i,l,!1),A=lAe(e);Math.abs(A)<30?(X0(e,f,"left",null),X0(e,y,"right",null)):A<1?X0(e,f,"left",["EyeUpper0","EyeLower0"]):X0(e,y,"right",["EyeUpper0","EyeLower0"]);let b=IT(e,m,"left"),v=IT(e,x,"right");return e.concat(b).concat(v)}var ti={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 ET(e,t){let n={irisL:t[3].dataSync(),irisR:t[1].dataSync(),eyeL:t[0].dataSync(),eyeR:t[6].dataSync(),lips:t[5].dataSync()},r=ti.eyeRLower.reduce((a,o)=>a+=e[o][2],0)/ti.eyeRLower.length;for(let a=0;a<n.irisR.length/2;a++)e.push([n.irisR[2*a+0],n.irisR[2*a+1],r]);let s=ti.eyeLLower.reduce((a,o)=>a+=e[o][2],0)/ti.eyeLLower.length;for(let a=0;a<n.irisL.length/2;a++)e.push([n.irisL[2*a+0],n.irisL[2*a+1],s]);for(let a=0;a<n.eyeL.length/2;a++)e[ti.eyeL[a]]=[n.eyeL[2*a+0],n.eyeL[2*a+1],e[ti.eyeL[a]][2]];for(let a=0;a<n.eyeR.length/2;a++)e[ti.eyeR[a]]=[n.eyeR[2*a+0],n.eyeR[2*a+1],e[ti.eyeR[a]][2]];return e}var Ls={boxes:[],skipped:Number.MAX_SAFE_INTEGER,timestamp:0},Bs=null,Wc=0;async function RT(e,t){var i,l,u,c,p,d,h,f,m,g;let n=(((i=t.face.detector)==null?void 0:i.skipTime)||0)>le()-Ls.timestamp,r=Ls.skipped<(((l=t.face.detector)==null?void 0:l.skipFrames)||0);!t.skipAllowed||!n||!r||Ls.boxes.length===0?(Ls.boxes=await Y9(e,t),Ls.timestamp=le(),Ls.skipped=0):Ls.skipped++;let s=[],a=[],o=0;for(let y=0;y<Ls.boxes.length;y++){let x=Ls.boxes[y],A=0,b,v={id:o++,mesh:[],meshRaw:[],box:[0,0,0,0],boxRaw:[0,0,0,0],score:0,boxScore:0,faceScore:0,annotations:{}};if([A,b,v.tensor]=j9((u=t.face.detector)==null?void 0:u.rotation,x,e,(c=t.face.mesh)!=null&&c.enabled?Wc:B0()),(p=t==null?void 0:t.filter)!=null&&p.equalization){let S=await _0(v.tensor);ne(v.tensor),v.tensor=S}if(v.boxScore=Math.round(100*x.confidence)/100,(d=t.face.mesh)!=null&&d.enabled)if(!Bs)t.debug&&oe("face mesh detection requested, but model is not loaded");else{let S=Bs.execute(v.tensor),I=S.find(D=>D.shape[D.shape.length-1]===1),E=S.find(D=>D.shape[D.shape.length-1]===1404),R=await I.data();v.faceScore=Math.round(100*R[0])/100;let P=H(E,[-1,3]),_=await P.array();if(v.faceScore<(((h=t.face.detector)==null?void 0:h.minConfidence)||1))x.confidence=v.faceScore;else{(f=t.face.attention)!=null&&f.enabled?_=await ET(_,S):(m=t.face.iris)!=null&&m.enabled&&(_=await TT(_,v.tensor,t,Wc)),v.mesh=H9(_,x,A,b,Wc),v.meshRaw=v.mesh.map(T=>[T[0]/(e.shape[2]||0),T[1]/(e.shape[1]||0),(T[2]||0)/Wc]);for(let T of Object.keys(es))v.annotations[T]=es[T].map(F=>v.mesh[F]);v.score=v.faceScore;let D={...q9(v.mesh,x),confidence:x.confidence,landmarks:x.landmarks};v.box=Y3(D,e),v.boxRaw=J3(D,e),a.push(D)}ne([...S,P])}else{v.box=Y3(x,e),v.boxRaw=J3(x,e),v.score=v.boxScore,v.mesh=x.landmarks.map(S=>[(x.startPoint[0]+x.endPoint[0])/2+(x.endPoint[0]+x.startPoint[0])*S[0]/B0(),(x.startPoint[1]+x.endPoint[1])/2+(x.endPoint[1]+x.startPoint[1])*S[1]/B0()]),v.meshRaw=v.mesh.map(S=>[S[0]/(e.shape[2]||0),S[1]/(e.shape[1]||0),(S[2]||0)/Wc]);for(let S of Object.keys(Yp))v.annotations[S]=[v.mesh[Yp[S]]]}v.score>(((g=t.face.detector)==null?void 0:g.minConfidence)||1)?s.push(v):ne(v.tensor)}return Ls.boxes=a,s}async function _T(e){var t,n,r;return pe.initial&&(Bs=null),Bs?e.debug&&oe("cached model:",Bs.modelUrl):(t=e.face.attention)!=null&&t.enabled?Bs=await Ge((n=e.face.attention)==null?void 0:n.modelPath):Bs=await Ge((r=e.face.mesh)==null?void 0:r.modelPath),Wc=Bs.inputs[0].shape?Bs.inputs[0].shape[2]:0,Bs}var $T=Bl,DT=Jp;var wr,K0=[],PT=0,FT=0,A5=Number.MAX_SAFE_INTEGER;async function OT(e){var t;return pe.initial&&(wr=null),wr?e.debug&&oe("cached model:",wr.modelUrl):wr=await Ge((t=e.face.description)==null?void 0:t.modelPath),wr}function x5(e){let t=e.image||e.tensor||e;if(!(wr!=null&&wr.inputs[0].shape))return t;let n=Se.resizeBilinear(t,[wr.inputs[0].shape[2],wr.inputs[0].shape[1]],!1),r=L(n,Je.tf255);return ne(n),r}async function b5(e,t,n,r){var o,i,l,u;if(!wr)return{age:0,gender:"unknown",genderScore:0,descriptor:[]};let s=A5<(((o=t.face.description)==null?void 0:o.skipFrames)||0),a=(((i=t.face.description)==null?void 0:i.skipTime)||0)>le()-PT;return t.skipAllowed&&s&&a&&FT===r&&((l=K0[n])==null?void 0:l.age)&&((u=K0[n])==null?void 0:u.age)>0?(A5++,K0[n]):(A5=0,new Promise(async c=>{var d,h;let p={age:0,gender:"unknown",genderScore:0,descriptor:[]};if((d=t.face.description)!=null&&d.enabled){let f=x5(e),m=wr==null?void 0:wr.execute(f);PT=le(),ne(f);let y=await(await m.find(R=>R.shape[1]===1)).data(),x=Math.trunc(200*Math.abs(y[0]-.5))/100;x>(((h=t.face.description)==null?void 0:h.minConfidence)||0)&&(p.gender=y[0]<=.5?"female":"male",p.genderScore=Math.min(.99,x));let A=Rr(m.find(R=>R.shape[1]===100),1),b=(await A.data())[0];ne(A);let S=await m.find(R=>R.shape[1]===100).data();p.age=Math.round(S[b-1]>S[b+1]?10*b-100*S[b-1]:10*b+100*S[b+1])/10;let I=m.find(R=>R.shape[1]===1024),E=I?await I.data():[];p.descriptor=Array.from(E),m.forEach(R=>ne(R))}K0[n]=p,FT=r,c(p)}))}function Z0(e){return[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])]}function th(e){return[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2]}function LT(e,t,n){let r=t.shape[1],s=t.shape[2],a=[[e.startPoint[1]/r,e.startPoint[0]/s,e.endPoint[1]/r,e.endPoint[0]/s]];return Se.cropAndResize(t,a,[0],n)}function BT(e,t){let n=[e.startPoint[0]*t[0],e.startPoint[1]*t[1]],r=[e.endPoint[0]*t[0],e.endPoint[1]*t[1]],s=e.palmLandmarks.map(a=>[a[0]*t[0],a[1]*t[1]]);return{startPoint:n,endPoint:r,palmLandmarks:s,confidence:e.confidence}}function Y0(e,t=1.5){let n=th(e),r=Z0(e),s=[t*r[0]/2,t*r[1]/2],a=[n[0]-s[0],n[1]-s[1]],o=[n[0]+s[0],n[1]+s[1]];return{startPoint:a,endPoint:o,palmLandmarks:e.palmLandmarks}}function J0(e){let t=th(e),n=Z0(e),s=Math.max(...n)/2,a=[t[0]-s,t[1]-s],o=[t[0]+s,t[1]+s];return{startPoint:a,endPoint:o,palmLandmarks:e.palmLandmarks}}function cAe(e){return e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI))}function WT(e,t){let n=Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]);return cAe(n)}var MT=(e,t)=>[[1,0,e],[0,1,t],[0,0,1]];function ni(e,t){let n=0;for(let r=0;r<e.length;r++)n+=e[r]*t[r];return n}function dAe(e,t){let n=[];for(let r=0;r<e.length;r++)n.push(e[r][t]);return n}function zT(e,t){let n=[],r=e.length;for(let s=0;s<r;s++){n.push([]);for(let a=0;a<r;a++)n[s].push(ni(e[s],dAe(t,a)))}return n}function w5(e,t){let n=Math.cos(e),r=Math.sin(e),s=[[n,-r,0],[r,n,0],[0,0,1]],a=MT(t[0],t[1]),o=zT(a,s),i=MT(-t[0],-t[1]);return zT(o,i)}function VT(e){let t=[[e[0][0],e[1][0]],[e[0][1],e[1][1]]],n=[e[0][2],e[1][2]],r=[-ni(t[0],n),-ni(t[1],n)];return[t[0].concat(r[0]),t[1].concat(r[1]),[0,0,1]]}function k5(e,t){return[ni(e,t[0]),ni(e,t[1])]}var GT=[{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 Q0=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=GT.map(n=>[n.x,n.y]),this.anchorsTensor=ps(this.anchors),this.inputSize=this.model&&this.model.inputs&&this.model.inputs[0].shape?this.model.inputs[0].shape[2]:0,this.inputSizeTensor=Ct([this.inputSize,this.inputSize]),this.doubleInputSizeTensor=Ct([this.inputSize*2,this.inputSize*2])}normalizeBoxes(t){let n={};n.boxOffsets=Pe(t,[0,0],[-1,2]),n.boxSizes=Pe(t,[0,2],[-1,2]),n.div=de(n.boxOffsets,this.inputSizeTensor),n.boxCenterPoints=ue(n.div,this.anchorsTensor),n.halfBoxSizes=de(n.boxSizes,this.doubleInputSizeTensor),n.sub=he(n.boxCenterPoints,n.halfBoxSizes),n.startPoints=L(n.sub,this.inputSizeTensor),n.add=ue(n.boxCenterPoints,n.halfBoxSizes),n.endPoints=L(n.add,this.inputSizeTensor);let r=pc([n.startPoints,n.endPoints],1);return Object.keys(n).forEach(s=>ne(n[s])),r}normalizeLandmarks(t,n){let r={};r.reshape=H(t,[-1,7,2]),r.div=de(r.reshape,this.inputSizeTensor),r.landmarks=ue(r.div,this.anchors[n]);let s=L(r.landmarks,this.inputSizeTensor);return Object.keys(r).forEach(a=>ne(r[a])),s}async predict(t,n){let r={};r.resize=Se.resizeBilinear(t,[this.inputSize,this.inputSize]),r.div=de(r.resize,Je.tf127),r.image=he(r.div,Je.tf1),r.batched=this.model.execute(r.image),r.predictions=tt(r.batched),r.slice=Pe(r.predictions,[0,0],[-1,1]),r.sigmoid=Tn(r.slice),r.scores=tt(r.sigmoid);let s=await r.scores.data();r.boxes=Pe(r.predictions,[0,1],[-1,4]),r.norm=this.normalizeBoxes(r.boxes),r.nms=await Se.nonMaxSuppressionAsync(r.norm,r.scores,3*n.hand.maxDetected,n.hand.iouThreshold,n.hand.minConfidence);let a=await r.nms.array(),o=[];for(let i of a){let l={};l.box=Pe(r.norm,[i,0],[1,-1]),l.slice=Pe(r.predictions,[i,5],[1,14]),l.norm=this.normalizeLandmarks(l.slice,i),l.palmLandmarks=H(l.norm,[-1,2]);let u=await l.box.data(),c=u.slice(0,2),p=u.slice(2,4),d=await l.palmLandmarks.array(),h={startPoint:c,endPoint:p,palmLandmarks:d,confidence:s[i]},f=BT(h,[t.shape[2]/this.inputSize,t.shape[1]/this.inputSize]);o.push(f),Object.keys(l).forEach(m=>ne(l[m]))}return Object.keys(r).forEach(i=>ne(r[i])),o}};var fAe=5,HT=1.65,jT=[0,5,9,13,17,1,2],mAe=0,gAe=2,qT=0,e2=class{constructor(t,n){fe(this,"handDetector");fe(this,"handPoseModel");fe(this,"inputSize");fe(this,"storedBoxes");fe(this,"skipped");fe(this,"detectedHands");this.handDetector=t,this.handPoseModel=n,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 n=t.map(o=>o[0]),r=t.map(o=>o[1]),s=[Math.min(...n),Math.min(...r)],a=[Math.max(...n),Math.max(...r)];return{startPoint:s,endPoint:a}}getBoxForPalmLandmarks(t,n){let r=t.map(a=>k5([...a,1],n)),s=this.calculateLandmarksBoundingBox(r);return Y0(J0(s),fAe)}getBoxForHandLandmarks(t){let n=this.calculateLandmarksBoundingBox(t),r=Y0(J0(n),HT);r.palmLandmarks=[];for(let s=0;s<jT.length;s++)r.palmLandmarks.push(t[jT[s]].slice(0,2));return r}transformRawCoords(t,n,r,s){let a=Z0(n),o=[a[0]/this.inputSize,a[1]/this.inputSize,(a[0]+a[1])/this.inputSize/2],i=t.map(h=>[o[0]*(h[0]-this.inputSize/2),o[1]*(h[1]-this.inputSize/2),o[2]*h[2]]),l=w5(r,[0,0]),u=i.map(h=>[...k5(h,l),h[2]]),c=VT(s),p=[...th(n),1],d=[ni(p,c[0]),ni(p,c[1])];return u.map(h=>[Math.trunc(h[0]+d[0]),Math.trunc(h[1]+d[1]),Math.trunc(h[2])])}async estimateHands(t,n){let r=!1,s,a=(n.hand.skipTime||0)>le()-qT,o=this.skipped<(n.hand.skipFrames||0);n.skipAllowed&&a&&o&&(s=await this.handDetector.predict(t,n),this.skipped=0),n.skipAllowed&&this.skipped++,s&&s.length>0&&(s.length!==this.detectedHands&&this.detectedHands!==n.hand.maxDetected||!n.hand.landmarks)&&(this.detectedHands=0,this.storedBoxes=[...s],this.storedBoxes.length>0&&(r=!0));let i=[];for(let l=0;l<this.storedBoxes.length;l++){let u=this.storedBoxes[l];if(!!u)if(n.hand.landmarks){let c=n.hand.rotation?WT(u.palmLandmarks[mAe],u.palmLandmarks[gAe]):0,p=th(u),d=[p[0]/t.shape[2],p[1]/t.shape[1]],h=n.hand.rotation&&pe.kernels.includes("rotatewithoffset")?Se.rotateWithOffset(t,c,0,d):t.clone(),f=w5(-c,p),m=r?this.getBoxForPalmLandmarks(u.palmLandmarks,f):u,g=LT(m,h,[this.inputSize,this.inputSize]),y=de(g,Je.tf255);ne(g),ne(h);let[x,A]=this.handPoseModel.execute(y);qT=le(),ne(y);let b=(await x.data())[0];if(ne(x),b>=n.hand.minConfidence/4){let v=H(A,[-1,3]),S=await v.array();ne(A),ne(v);let I=this.transformRawCoords(S,m,c,f),E=this.getBoxForHandLandmarks(I);this.storedBoxes[l]={...E,confidence:b};let R={landmarks:I,confidence:b,boxConfidence:u.confidence,fingerConfidence:b,box:{topLeft:E.startPoint,bottomRight:E.endPoint}};i.push(R)}else this.storedBoxes[l]=null;ne(A)}else{let c=Y0(J0(u),HT),p={confidence:u.confidence,boxConfidence:u.confidence,fingerConfidence:0,box:{topLeft:c.startPoint,bottomRight:c.endPoint},landmarks:[]};i.push(p)}}return this.storedBoxes=this.storedBoxes.filter(l=>l!==null),this.detectedHands=i.length,i.length>n.hand.maxDetected&&(i.length=n.hand.maxDetected),i}};var er={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=>er.nameMapping[e],getPoints:e=>er.pointsMapping[e]},si={none:0,half:1,full:2,nameMapping:{0:"none",1:"half",2:"full"},getName:e=>si.nameMapping[e]},Bt={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=>Bt.nameMapping[e]},ri=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,n,r){typeof this.curls[t]=="undefined"&&(this.curls[t]=[]),this.curls[t].push([n,r])}direction(t,n,r){this.directions[t]||(this.directions[t]=[]),this.directions[t].push([n,r])}weight(t,n){this.weights[t]=n;let r=this.weights.reduce((s,a)=>s+a,0);this.weightsRelative=this.weights.map(s=>s*5/r)}matchAgainst(t,n){let r=0;for(let s in t){let a=t[s],o=this.curls[s];if(typeof o=="undefined"){r+=this.weightsRelative[s];continue}for(let[i,l]of o)if(a===i){r+=l*this.weightsRelative[s];break}}for(let s in n){let a=n[s],o=this.directions[s];if(typeof o=="undefined"){r+=this.weightsRelative[s];continue}for(let[i,l]of o)if(a===i){r+=l*this.weightsRelative[s];break}}return r/10}};var{thumb:vs,index:fa,middle:ma,ring:Ul,pinky:Gl}=er,{none:ws,half:AAe,full:ks}=si,{verticalUp:Vc,verticalDown:x6e,horizontalLeft:S5,horizontalRight:xAe,diagonalUpRight:bAe,diagonalUpLeft:Uc,diagonalDownRight:b6e,diagonalDownLeft:v6e}=Bt,ai=new ri("thumbs up");ai.curl(vs,ws,1);ai.direction(vs,Vc,1);ai.direction(vs,Uc,.25);ai.direction(vs,bAe,.25);for(let e of[er.index,er.middle,er.ring,er.pinky])ai.curl(e,ks,1),ai.direction(e,S5,1),ai.direction(e,xAe,1);var tn=new ri("victory");tn.curl(vs,AAe,.5);tn.curl(vs,ws,.5);tn.direction(vs,Vc,1);tn.direction(vs,Uc,1);tn.curl(fa,ws,1);tn.direction(fa,Vc,.75);tn.direction(fa,Uc,1);tn.curl(ma,ws,1);tn.direction(ma,Vc,1);tn.direction(ma,Uc,.75);tn.curl(Ul,ks,1);tn.direction(Ul,Vc,.2);tn.direction(Ul,Uc,1);tn.direction(Ul,S5,.2);tn.curl(Gl,ks,1);tn.direction(Gl,Vc,.2);tn.direction(Gl,Uc,1);tn.direction(Gl,S5,.2);tn.weight(fa,2);tn.weight(ma,2);var oi=new ri("point");oi.curl(vs,ks,1);oi.curl(fa,ws,.5);oi.curl(ma,ks,.5);oi.curl(Ul,ks,.5);oi.curl(Gl,ks,.5);oi.weight(fa,2);oi.weight(ma,2);var ii=new ri("middle finger");ii.curl(vs,ws,1);ii.curl(fa,ks,.5);ii.curl(ma,ks,.5);ii.curl(Ul,ks,.5);ii.curl(Gl,ks,.5);ii.weight(fa,2);ii.weight(ma,2);var Gc=new ri("open palm");Gc.curl(vs,ws,.75);Gc.curl(fa,ws,.75);Gc.curl(ma,ws,.75);Gc.curl(Ul,ws,.75);Gc.curl(Gl,ws,.75);var XT=[ai,tn,oi,ii,Gc];var vAe=.7,Hl={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 KT(e,t,n,r){let s=(t-r)/(e-n),a=Math.atan(s)*180/Math.PI;return a<=0?a=-a:a>0&&(a=180-a),a}function YT(e,t){if(!e||!t)return[0,0];let n=KT(e[0],e[1],t[0],t[1]);if(e.length===2)return n;let r=KT(e[1],e[2],t[1],t[2]);return[n,r]}function ZT(e,t=1){let n=0,r=0,s=0;return e>=75&&e<=105?n=1*t:e>=25&&e<=155?r=1*t:s=1*t,[n,r,s]}function wAe(e,t,n){let r=e[0]-t[0],s=e[0]-n[0],a=t[0]-n[0],o=e[1]-t[1],i=e[1]-n[1],l=t[1]-n[1],u=e[2]-t[2],c=e[2]-n[2],p=t[2]-n[2],d=Math.sqrt(r*r+o*o+u*u),h=Math.sqrt(s*s+i*i+c*c),f=Math.sqrt(a*a+l*l+p*p),m=(f*f+d*d-h*h)/(2*f*d);m>1?m=1:m<-1&&(m=-1);let g=Math.acos(m);g=57.2958*g%180;let y;return g>Hl.NO_CURL_START_LIMIT?y=si.none:g>Hl.HALF_CURL_START_LIMIT?y=si.half:y=si.full,y}function JT(e,t,n,r){let s;return r===Math.abs(e)?e>0?s=Bt.horizontalLeft:s=Bt.horizontalRight:r===Math.abs(t)?t>0?s=Bt.horizontalLeft:s=Bt.horizontalRight:n>0?s=Bt.horizontalLeft:s=Bt.horizontalRight,s}function QT(e,t,n,r){let s;return r===Math.abs(e)?e<0?s=Bt.verticalDown:s=Bt.verticalUp:r===Math.abs(t)?t<0?s=Bt.verticalDown:s=Bt.verticalUp:n<0?s=Bt.verticalDown:s=Bt.verticalUp,s}function kAe(e,t,n,r,s,a,o,i){let l,u=QT(e,t,n,r),c=JT(s,a,o,i);return u===Bt.verticalUp?c===Bt.horizontalLeft?l=Bt.diagonalUpLeft:l=Bt.diagonalUpRight:c===Bt.horizontalLeft?l=Bt.diagonalDownLeft:l=Bt.diagonalDownRight,l}function SAe(e,t,n,r){let s=e[0]-t[0],a=e[0]-n[0],o=t[0]-n[0],i=e[1]-t[1],l=e[1]-n[1],u=t[1]-n[1],c=Math.max(Math.abs(s),Math.abs(a),Math.abs(o)),p=Math.max(Math.abs(i),Math.abs(l),Math.abs(u)),d=0,h=0,f=0,m=p/(c+1e-5);m>1.5?d+=Hl.DISTANCE_VOTE_POWER:m>.66?h+=Hl.DISTANCE_VOTE_POWER:f+=Hl.DISTANCE_VOTE_POWER;let g=Math.sqrt(s*s+i*i),y=Math.sqrt(a*a+l*l),x=Math.sqrt(o*o+u*u),A=Math.max(g,y,x),b=e[0],v=e[1],S=n[0],I=n[1];A===g?(S=n[0],I=n[1]):A===x&&(b=t[0],v=t[1]);let P=YT([b,v],[S,I]),_=ZT(P,Hl.TOTAL_ANGLE_VOTE_POWER);d+=_[0],h+=_[1],f+=_[2];for(let T of r){let F=ZT(T,Hl.SINGLE_ANGLE_VOTE_POWER);d+=F[0],h+=F[1],f+=F[2]}let D;return d===Math.max(d,h,f)?D=QT(l,i,u,p):f===Math.max(h,f)?D=JT(a,s,o,c):D=kAe(l,i,u,p,a,s,o,c),D}function eN(e){let t=[],n=[],r=[],s=[];if(!e)return{curls:r,directions:s};for(let a of er.all){let o=er.getPoints(a),i=[],l=[];for(let u of o){let c=e[u[0]],p=e[u[1]],d=YT(c,p),h=d[0],f=d[1];i.push(h),l.push(f)}t.push(i),n.push(l)}for(let a of er.all){let o=a===er.thumb?1:0,i=er.getPoints(a),l=e[i[o][0]],u=e[i[o+1][1]],c=e[i[3][1]],p=wAe(l,u,c),d=SAe(l,u,c,t[a].slice(o));r[a]=p,s[a]=d}return{curls:r,directions:s}}function t2(e){if(!e||e.length===0)return null;let t=eN(e),n={};for(let r of er.all)n[er.getName(r)]={curl:si.getName(t.curls[r]),direction:Bt.getName(t.directions[r])};return n}function tN(e){let t=[];if(!e||e.length===0)return t;let n=eN(e);for(let r of XT){let s=r.matchAgainst(n.curls,n.directions);s>=vAe&&t.push({name:r.name,confidence:s})}return t}var nN={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]},Hc,jc,rN;async function C5(e,t){let n=await rN.estimateHands(e,t);if(!n)return[];let r=[];for(let s=0;s<n.length;s++){let a={};if(n[s].landmarks)for(let c of Object.keys(nN))a[c]=nN[c].map(p=>n[s].landmarks[p]);let o=n[s].landmarks,i=[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,0,0],l=[0,0,0,0];if(o&&o.length>0){for(let c of o)c[0]<i[0]&&(i[0]=c[0]),c[1]<i[1]&&(i[1]=c[1]),c[0]>i[2]&&(i[2]=c[0]),c[1]>i[3]&&(i[3]=c[1]);i[2]-=i[0],i[3]-=i[1],l=[i[0]/(e.shape[2]||0),i[1]/(e.shape[1]||0),i[2]/(e.shape[2]||0),i[3]/(e.shape[1]||0)]}else i=n[s].box?[Math.trunc(Math.max(0,n[s].box.topLeft[0])),Math.trunc(Math.max(0,n[s].box.topLeft[1])),Math.trunc(Math.min(e.shape[2]||0,n[s].box.bottomRight[0])-Math.max(0,n[s].box.topLeft[0])),Math.trunc(Math.min(e.shape[1]||0,n[s].box.bottomRight[1])-Math.max(0,n[s].box.topLeft[1]))]:[0,0,0,0],l=[n[s].box.topLeft[0]/(e.shape[2]||0),n[s].box.topLeft[1]/(e.shape[1]||0),(n[s].box.bottomRight[0]-n[s].box.topLeft[0])/(e.shape[2]||0),(n[s].box.bottomRight[1]-n[s].box.topLeft[1])/(e.shape[1]||0)];let u=t2(o);r.push({id:s,score:Math.round(100*n[s].confidence)/100,boxScore:Math.round(100*n[s].boxConfidence)/100,fingerScore:Math.round(100*n[s].fingerConfidence)/100,label:"hand",box:i,boxRaw:l,keypoints:o,annotations:a,landmarks:u})}return r}async function T5(e){var n,r;pe.initial&&(Hc=null,jc=null),!Hc||!jc?[Hc,jc]=await Promise.all([e.hand.enabled?Ge((n=e.hand.detector)==null?void 0:n.modelPath):null,e.hand.landmarks?Ge((r=e.hand.skeleton)==null?void 0:r.modelPath):null]):(e.debug&&oe("cached model:",Hc.modelUrl),e.debug&&oe("cached model:",jc.modelUrl));let t=new Q0(Hc);return rN=new e2(t,jc),[Hc,jc]}var pn=[null,null],IAe=["StatefulPartitionedCall/Postprocessor/Slice","StatefulPartitionedCall/Postprocessor/ExpandDims_1"],li=[[0,0],[0,0]],CAe=["hand","fist","pinch","point","face","tip","pinchtip"],aN=4,oN=1.6,TAe=512,NAe=1.4,n2=Number.MAX_SAFE_INTEGER,N5=0,ga=[0,0],jt={boxes:[],hands:[]},iN={thumb:[1,2,3,4],index:[5,6,7,8],middle:[9,10,11,12],ring:[13,14,15,16],pinky:[17,18,19,20],base:[0],palm:[0,17,13,9,5,1,0]};async function lN(e){var t;if(pe.initial&&(pn[0]=null),pn[0])e.debug&&oe("cached model:",pn[0].modelUrl);else{r2(["tensorlistreserve","enter","tensorlistfromtensor","merge","loopcond","switch","exit","tensorliststack","nextiteration","tensorlistsetitem","tensorlistgetitem","reciprocal","shape","split","where"],e),pn[0]=await Ge((t=e.hand.detector)==null?void 0:t.modelPath);let n=Object.values(pn[0].modelSignature.inputs);li[0][0]=Array.isArray(n)?parseInt(n[0].tensorShape.dim[1].size):0,li[0][1]=Array.isArray(n)?parseInt(n[0].tensorShape.dim[2].size):0}return pn[0]}async function uN(e){var t;if(pe.initial&&(pn[1]=null),pn[1])e.debug&&oe("cached model:",pn[1].modelUrl);else{pn[1]=await Ge((t=e.hand.skeleton)==null?void 0:t.modelPath);let n=Object.values(pn[1].modelSignature.inputs);li[1][0]=Array.isArray(n)?parseInt(n[0].tensorShape.dim[1].size):0,li[1][1]=Array.isArray(n)?parseInt(n[0].tensorShape.dim[2].size):0}return pn[1]}async function EAe(e,t){let n=[];if(!e||!pn[0])return n;let r={},s=(e.shape[2]||1)/(e.shape[1]||1),a=Math.min(Math.round((e.shape[1]||0)/8)*8,TAe),o=Math.round(a*s/8)*8;r.resize=Se.resizeBilinear(e,[a,o]),r.cast=ge(r.resize,"int32"),[r.rawScores,r.rawBoxes]=await pn[0].executeAsync(r.cast,IAe),r.boxes=tt(r.rawBoxes,[0,2]),r.scores=tt(r.rawScores,[0]);let i=rr(r.scores,1);ne(i[aN]),i.splice(aN,1),r.filtered=cn(i,1),ne(i),r.max=gn(r.filtered,1),r.argmax=Rr(r.filtered,1);let l=0;r.nms=await Se.nonMaxSuppressionAsync(r.boxes,r.max,(t.hand.maxDetected||0)+1,t.hand.iouThreshold||0,t.hand.minConfidence||1);let u=await r.nms.data(),c=await r.max.data(),p=await r.argmax.data();for(let d of Array.from(u)){let h=Pe(r.boxes,d,1),f=await h.data();ne(h);let m=[f[1],f[0],f[3]-f[1],f[2]-f[0]],g=U0(m,NAe),y=[Math.trunc(m[0]*ga[0]),Math.trunc(m[1]*ga[1]),Math.trunc(m[2]*ga[0]),Math.trunc(m[3]*ga[1])],x=c[d],A=CAe[p[d]],b={id:l++,score:x,box:y,boxRaw:g,label:A};n.push(b)}return Object.keys(r).forEach(d=>ne(r[d])),n.sort((d,h)=>h.score-d.score),n.length>(t.hand.maxDetected||1)&&(n.length=t.hand.maxDetected||1),n}async function E5(e,t,n){let r={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&&pn[1]&&n.hand.landmarks&&t.score>(n.hand.minConfidence||0)){let s={},a=[t.boxRaw[1],t.boxRaw[0],t.boxRaw[3]+t.boxRaw[1],t.boxRaw[2]+t.boxRaw[0]];s.crop=Se.cropAndResize(e,[a],[0],[li[1][0],li[1][1]],"bilinear"),s.div=de(s.crop,Je.tf255),[s.score,s.keypoints]=pn[1].execute(s.div,["Identity_1","Identity"]);let o=(await s.score.data())[0],i=(100-Math.trunc(100/(1+Math.exp(o))))/100;if(i>=(n.hand.minConfidence||0)){r.fingerScore=i,s.reshaped=H(s.keypoints,[-1,3]);let c=(await s.reshaped.array()).map(p=>[p[0]/li[1][1],p[1]/li[1][0],p[2]||0]).map(p=>[p[0]*t.boxRaw[2],p[1]*t.boxRaw[3],p[2]||0]);r.keypoints=c.map(p=>[ga[0]*(p[0]+t.boxRaw[0]),ga[1]*(p[1]+t.boxRaw[1]),p[2]||0]),r.landmarks=t2(r.keypoints);for(let p of Object.keys(iN))r.annotations[p]=iN[p].map(d=>r.landmarks&&r.keypoints[d]?r.keypoints[d]:null)}Object.keys(s).forEach(l=>ne(s[l]))}return r}async function R5(e,t){var s,a;if(!pn[0]||!pn[1]||!((s=pn[0])!=null&&s.inputs[0].shape)||!((a=pn[1])!=null&&a.inputs[0].shape))return[];ga=[e.shape[2]||0,e.shape[1]||0],n2++;let n=(t.hand.skipTime||0)>le()-N5,r=n2<(t.hand.skipFrames||0);return t.skipAllowed&&n&&r?jt.hands:new Promise(async o=>{let i=3*(t.hand.skipTime||0)>le()-N5,l=n2<3*(t.hand.skipFrames||0);t.skipAllowed&&jt.hands.length===t.hand.maxDetected?jt.hands=await Promise.all(jt.boxes.map(c=>E5(e,c,t))):t.skipAllowed&&i&&l&&jt.hands.length>0?jt.hands=await Promise.all(jt.boxes.map(c=>E5(e,c,t))):(jt.boxes=await EAe(e,t),N5=le(),jt.hands=await Promise.all(jt.boxes.map(c=>E5(e,c,t))),n2=0);let u=[...jt.boxes];if(jt.boxes.length=0,t.cacheSensitivity>0)for(let c=0;c<jt.hands.length;c++){let p=tT(jt.hands[c].keypoints,ga);if(p.box[2]/(e.shape[2]||1)>.05&&p.box[3]/(e.shape[1]||1)>.05&&jt.hands[c].fingerScore&&jt.hands[c].fingerScore>(t.hand.minConfidence||0)){let d=U0(p.box,oN),h=U0(p.boxRaw,oN);jt.boxes.push({...u[c],box:d,boxRaw:h})}}for(let c=0;c<jt.hands.length;c++){let p=da(jt.hands[c].keypoints,ga);jt.hands[c].box=p.box,jt.hands[c].boxRaw=p.boxRaw}o(jt.hands)})}var $n,s2=[],_5=Number.MAX_SAFE_INTEGER,dN=0,pN=0;async function hN(e){var t;return pe.initial&&($n=null),$n?e.debug&&oe("cached model:",$n.modelUrl):$n=await Ge((t=e.face.liveness)==null?void 0:t.modelPath),$n}async function $5(e,t,n,r){var o,i;if(!$n)return 0;let s=(((o=t.face.liveness)==null?void 0:o.skipTime)||0)>le()-pN,a=_5<(((i=t.face.liveness)==null?void 0:i.skipFrames)||0);return t.skipAllowed&&s&&a&&dN===r&&s2[n]?(_5++,s2[n]):(_5=0,new Promise(async l=>{let u=Se.resizeBilinear(e,[$n!=null&&$n.inputs[0].shape?$n.inputs[0].shape[2]:0,$n!=null&&$n.inputs[0].shape?$n.inputs[0].shape[1]:0],!1),c=$n==null?void 0:$n.execute(u),p=(await c.data())[0];s2[n]=Math.round(100*p)/100,dN=r,pN=le(),ne([u,c]),l(s2[n])}))}var nh={};wa(nh,{connected:()=>o2,horizontal:()=>D5,kpt:()=>a2,relative:()=>F5,vertical:()=>P5});var a2=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],D5=[["leftEye","rightEye"],["leftEar","rightEar"],["leftShoulder","rightShoulder"],["leftElbow","rightElbow"],["leftWrist","rightWrist"],["leftHip","rightHip"],["leftKnee","rightKnee"],["leftAnkle","rightAnkle"]],P5=[["leftKnee","leftShoulder"],["rightKnee","rightShoulder"],["leftAnkle","leftKnee"],["rightAnkle","rightKnee"]],F5=[[["leftHip","rightHip"],["leftShoulder","rightShoulder"]],[["leftElbow","rightElbow"],["leftShoulder","rightShoulder"]]],o2={leftLeg:["leftHip","leftKnee","leftAnkle"],rightLeg:["rightHip","rightKnee","rightAnkle"],torso:["leftShoulder","rightShoulder","rightHip","leftHip","leftShoulder"],leftArm:["leftShoulder","leftElbow","leftWrist"],rightArm:["rightShoulder","rightElbow","rightWrist"],head:[]};var mN=.005,kr={keypoints:[],padding:[[0,0],[0,0],[0,0],[0,0]]};function O5(e){for(let t of D5){let n=e.keypoints.findIndex(s=>s.part===t[0]),r=e.keypoints.findIndex(s=>s.part===t[1]);if(e.keypoints[n]&&e.keypoints[r]&&e.keypoints[n].position[0]<e.keypoints[r].position[0]){let s=e.keypoints[n];e.keypoints[n]=e.keypoints[r],e.keypoints[r]=s}}for(let t of P5){let n=e.keypoints.findIndex(s=>s&&s.part===t[0]),r=e.keypoints.findIndex(s=>s&&s.part===t[1]);e.keypoints[n]&&e.keypoints[r]&&e.keypoints[n].position[1]<e.keypoints[r].position[1]&&e.keypoints.splice(n,1)}for(let[t,n]of F5){let r=e.keypoints.findIndex(u=>u&&u.part===t[0]),s=e.keypoints.findIndex(u=>u&&u.part===t[1]),a=e.keypoints.findIndex(u=>u&&u.part===n[0]),o=e.keypoints.findIndex(u=>u&&u.part===n[1]);if(!e.keypoints[a]||!e.keypoints[o])continue;let i=e.keypoints[r]?[Math.abs(e.keypoints[a].position[0]-e.keypoints[r].position[0]),Math.abs(e.keypoints[o].position[0]-e.keypoints[r].position[0])]:[0,0],l=e.keypoints[s]?[Math.abs(e.keypoints[o].position[0]-e.keypoints[s].position[0]),Math.abs(e.keypoints[a].position[0]-e.keypoints[s].position[0])]:[0,0];if(i[0]>i[1]||l[0]>l[1]){let u=e.keypoints[r];e.keypoints[r]=e.keypoints[s],e.keypoints[s]=u}}}function gN(e){for(let t=0;t<e.length;t++)if(e[t]&&kr.keypoints[t]){let n=[Math.abs(e[t].positionRaw[0]-kr.keypoints[t].positionRaw[0]),Math.abs(e[t].positionRaw[1]-kr.keypoints[t].positionRaw[1])];n[0]<mN&&n[1]<mN?e[t]=kr.keypoints[t]:kr.keypoints[t]=e[t]}else kr.keypoints[t]=e[t];return e}function yN(e,t){let n={};if(!e.shape||!e.shape[1]||!e.shape[2])return e;kr.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]],n.pad=Xr(e,kr.padding),n.resize=Se.resizeBilinear(n.pad,[t,t]);let r=ge(n.resize,"int32");return Object.keys(n).forEach(s=>ne(n[s])),r}function AN(e,t){e.keypoints=e.keypoints.filter(r=>r&&r.position);for(let r of e.keypoints)r.position=[r.position[0]*(t[0]+kr.padding[2][0]+kr.padding[2][1])/t[0]-kr.padding[2][0],r.position[1]*(t[1]+kr.padding[1][0]+kr.padding[1][1])/t[1]-kr.padding[1][0]],r.positionRaw=[r.position[0]/t[0],r.position[1]/t[1]];let n=da(e.keypoints.map(r=>r.position),t);return e.box=n.box,e.boxRaw=n.boxRaw,e}var Sr,i2=0,M5=Number.MAX_SAFE_INTEGER,jl={boxes:[],bodies:[],last:0};async function xN(e){return pe.initial&&(Sr=null),Sr?e.debug&&oe("cached model:",Sr.modelUrl):(r2(["size"],e),Sr=await Ge(e.body.modelPath)),i2=Sr.inputs[0].shape?Sr.inputs[0].shape[2]:0,i2<64&&(i2=256),Sr}async function _Ae(e,t,n){let r=e[0][0],s=[],a=0;for(let c=0;c<r.length;c++)if(a=r[c][2],a>t.body.minConfidence){let p=[r[c][1],r[c][0]];s.push({score:Math.round(100*a)/100,part:a2[c],positionRaw:p,position:[Math.round((n.shape[2]||0)*p[0]),Math.round((n.shape[1]||0)*p[1])]})}a=s.reduce((c,p)=>p.score>c?p.score:c,0);let o=[],i=da(s.map(c=>c.position),[n.shape[2],n.shape[1]]),l={};for(let[c,p]of Object.entries(o2)){let d=[];for(let h=0;h<p.length-1;h++){let f=s.find(g=>g.part===p[h]),m=s.find(g=>g.part===p[h+1]);f&&m&&f.score>(t.body.minConfidence||0)&&m.score>(t.body.minConfidence||0)&&d.push([f.position,m.position])}l[c]=d}let u={id:0,score:a,box:i.box,boxRaw:i.boxRaw,keypoints:s,annotations:l};return O5(u),o.push(u),o}async function $Ae(e,t,n){let r=[];for(let s=0;s<e[0].length;s++){let a=e[0][s],o=Math.round(100*a[51+4])/100;if(o>t.body.minConfidence){let i=[];for(let p=0;p<17;p++){let d=a[3*p+2];if(d>t.body.minConfidence){let h=[a[3*p+1],a[3*p+0]];i.push({part:a2[p],score:Math.round(100*d)/100,positionRaw:h,position:[Math.round((n.shape[2]||0)*h[0]),Math.round((n.shape[1]||0)*h[1])]})}}let l=da(i.map(p=>p.position),[n.shape[2],n.shape[1]]),u={};for(let[p,d]of Object.entries(o2)){let h=[];for(let f=0;f<d.length-1;f++){let m=i.find(y=>y.part===d[f]),g=i.find(y=>y.part===d[f+1]);m&&g&&m.score>(t.body.minConfidence||0)&&g.score>(t.body.minConfidence||0)&&h.push([m.position,g.position])}u[p]=h}let c={id:s,score:o,box:l.box,boxRaw:l.boxRaw,keypoints:[...i],annotations:u};O5(c),r.push(c)}}return r.sort((s,a)=>a.score-s.score),r.length>t.body.maxDetected&&(r.length=t.body.maxDetected),r}async function z5(e,t){if(!Sr||!(Sr!=null&&Sr.inputs[0].shape))return[];t.skipAllowed||(jl.boxes.length=0),M5++;let n=(t.body.skipTime||0)>le()-jl.last,r=M5<(t.body.skipFrames||0);return t.skipAllowed&&n&&r?jl.bodies:new Promise(async s=>{let a={};M5=0,a.input=yN(e,i2),a.res=Sr==null?void 0:Sr.execute(a.input),jl.last=le();let o=await a.res.array();jl.bodies=a.res.shape[2]===17?await _Ae(o,t,e):await $Ae(o,t,e);for(let i of jl.bodies)AN(i,[e.shape[2]||1,e.shape[1]||1]),gN(i.keypoints);Object.keys(a).forEach(i=>ne(a[i])),s(jl.bodies)})}var qc,l2=[],vN=0,L5=Number.MAX_SAFE_INTEGER,c2=0,u2=2.5;async function wN(e){if(!qc||pe.initial){qc=await Ge(e.object.modelPath);let t=Object.values(qc.modelSignature.inputs);c2=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):0}else e.debug&&oe("cached model:",qc.modelUrl);return qc}async function DAe(e,t,n){let r=0,s=[];for(let l of[1,2,4])K(async()=>{let u=l*13,c=tt(e.find(m=>m.shape[1]===u**2&&(m.shape[2]||0)===zc.length)),p=tt(e.find(m=>m.shape[1]===u**2&&(m.shape[2]||0)<zc.length)),h=await p.reshape([-1,4,p.shape[1]/4]).argMax(2).array(),f=await c.array();for(let m=0;m<c.shape[0];m++)for(let g=0;g<c.shape[1];g++){let y=f[m][g];if(y>(n.object.minConfidence||0)&&g!==61){let x=(.5+Math.trunc(m%u))/u,A=(.5+Math.trunc(m/u))/u,b=h[m].map(D=>D*(u/l/c2)),[v,S]=[x-u2/l*b[0],A-u2/l*b[1]],[I,E]=[x+u2/l*b[2]-v,A+u2/l*b[3]-S],R=[v,S,I,E];R=R.map(D=>Math.max(0,Math.min(D,1)));let P=[R[0]*t[0],R[1]*t[1],R[2]*t[0],R[3]*t[1]],_={id:r++,score:Math.round(100*y)/100,class:g+1,label:zc[g].label,box:P.map(D=>Math.trunc(D)),boxRaw:R};s.push(_)}}});e.forEach(l=>ne(l));let a=s.map(l=>[l.boxRaw[1],l.boxRaw[0],l.boxRaw[3],l.boxRaw[2]]),o=s.map(l=>l.score),i=[];if(a&&a.length>0){let l=await Se.nonMaxSuppressionAsync(a,o,n.object.maxDetected,n.object.iouThreshold,n.object.minConfidence);i=await l.data(),ne(l)}return s=s.filter((l,u)=>i.includes(u)).sort((l,u)=>u.score-l.score),s}async function B5(e,t){let n=(t.object.skipTime||0)>le()-vN,r=L5<(t.object.skipFrames||0);return t.skipAllowed&&n&&r&&l2.length>0?(L5++,l2):(L5=0,!pe.kernels.includes("mod")||!pe.kernels.includes("sparsetodense")?l2:new Promise(async s=>{let a=[e.shape[2]||0,e.shape[1]||0],o=Se.resizeBilinear(e,[c2,c2],!1),i=de(o,Je.tf255),l=i.transpose([0,3,1,2]);ne(i),ne(o);let u;t.object.enabled&&(u=qc.execute(l)),vN=le(),ne(l);let c=await DAe(u,a,t);l2=c,s(c)}))}var sh=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"],PAe=sh.length,rh=sh.reduce((e,t,n)=>(e[t]=n,e),{}),FAe=[["leftHip","leftShoulder"],["leftElbow","leftShoulder"],["leftElbow","leftWrist"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["rightHip","rightShoulder"],["rightElbow","rightShoulder"],["rightElbow","rightWrist"],["rightHip","rightKnee"],["rightKnee","rightAnkle"],["leftShoulder","rightShoulder"],["leftHip","rightHip"]],H6e=FAe.map(([e,t])=>[rh[e],rh[t]]),SN=[["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 IN(e){let t=e.reduce(({maxX:n,maxY:r,minX:s,minY:a},{position:{x:o,y:i}})=>({maxX:Math.max(n,o),maxY:Math.max(r,i),minX:Math.min(s,o),minY:Math.min(a,i)}),{maxX:Number.NEGATIVE_INFINITY,maxY:Number.NEGATIVE_INFINITY,minX:Number.POSITIVE_INFINITY,minY:Number.POSITIVE_INFINITY});return[t.minX,t.minY,t.maxX-t.minX,t.maxY-t.minY]}function CN(e,[t,n],[r,s]){let a=t/r,o=n/s,i=(u,c)=>({id:c,score:u.score,boxRaw:[u.box[0]/s,u.box[1]/r,u.box[2]/s,u.box[3]/r],box:[Math.trunc(u.box[0]*o),Math.trunc(u.box[1]*a),Math.trunc(u.box[2]*o),Math.trunc(u.box[3]*a)],keypoints:u.keypoints.map(({score:p,part:d,position:h})=>({score:p,part:d,position:[Math.trunc(h.x*o),Math.trunc(h.y*a)],positionRaw:[h.x/r,h.y/r]})),annotations:{}});return e.map((u,c)=>i(u,c))}var d2=class{constructor(t,n){fe(this,"priorityQueue");fe(this,"numberOfElements");fe(this,"getElementValue");this.priorityQueue=new Array(t),this.numberOfElements=-1,this.getElementValue=n}enqueue(t){this.priorityQueue[++this.numberOfElements]=t,this.swim(this.numberOfElements)}dequeue(){let t=this.priorityQueue[0];return this.exchange(0,this.numberOfElements--),this.sink(0),this.priorityQueue[this.numberOfElements+1]=null,t}empty(){return this.numberOfElements===-1}size(){return this.numberOfElements+1}all(){return this.priorityQueue.slice(0,this.numberOfElements+1)}max(){return this.priorityQueue[0]}swim(t){for(;t>0&&this.less(Math.floor(t/2),t);)this.exchange(t,Math.floor(t/2)),t=Math.floor(t/2)}sink(t){for(;2*t<=this.numberOfElements;){let n=2*t;if(n<this.numberOfElements&&this.less(n,n+1)&&n++,!this.less(t,n))break;this.exchange(t,n),t=n}}getValueAt(t){return this.getElementValue(this.priorityQueue[t])}less(t,n){return this.getValueAt(t)<this.getValueAt(n)}exchange(t,n){let r=this.priorityQueue[t];this.priorityQueue[t]=this.priorityQueue[n],this.priorityQueue[n]=r}};function W5(e,t,n,r){return{y:r.get(e,t,n),x:r.get(e,t,n+PAe)}}function V5(e,t,n){let{heatmapY:r,heatmapX:s,id:a}=e,{y:o,x:i}=W5(r,s,a,n);return{x:e.heatmapX*t+i,y:e.heatmapY*t+o}}function U5(e,t,n){return e<t?t:e>n?n:e}function TN(e,t,n,r){let s=n-e,a=r-t;return s*s+a*a}function G5(e,t){return{x:e.x+t.x,y:e.y+t.y}}var Ss,MAe=["MobilenetV1/offset_2/BiasAdd","MobilenetV1/heatmap_2/BiasAdd","MobilenetV1/displacement_fwd_2/BiasAdd","MobilenetV1/displacement_bwd_2/BiasAdd"],p2=1,Xc=16,zAe=50**2;function NN(e,t,n,r,s,a,o=2){let i=y=>({y:a.get(y.y,y.x,e),x:a.get(y.y,y.x,a.shape[2]/2+e)}),l=(y,x,A)=>({y:U5(Math.round(y.y/Xc),0,x-1),x:U5(Math.round(y.x/Xc),0,A-1)}),[u,c]=r.shape,p=l(t.position,u,c),d=i(p),f=G5(t.position,d);for(let y=0;y<o;y++){let x=l(f,u,c),A=W5(x.y,x.x,n,s);f=G5({x:x.x*Xc,y:x.y*Xc},{x:A.x,y:A.y})}let m=l(f,u,c),g=r.get(m.y,m.x,n);return{position:f,part:sh[n],score:g}}function LAe(e,t,n,r,s){let a=SN.map(([d,h])=>[rh[d],rh[h]]),o=a.map(([,d])=>d),i=a.map(([d])=>d),l=t.shape[2],u=o.length,c=new Array(l),p=V5(e.part,Xc,n);c[e.part.id]={score:e.score,part:sh[e.part.id],position:p};for(let d=u-1;d>=0;--d){let h=o[d],f=i[d];c[h]&&!c[f]&&(c[f]=NN(d,c[h],f,t,n,s))}for(let d=0;d<u;++d){let h=i[d],f=o[d];c[h]&&!c[f]&&(c[f]=NN(d,c[h],f,t,n,r))}return c}function BAe(e,t,n,r,s){let[a,o]=s.shape,i=!0,l=Math.max(n-p2,0),u=Math.min(n+p2+1,a);for(let c=l;c<u;++c){let p=Math.max(r-p2,0),d=Math.min(r+p2+1,o);for(let h=p;h<d;++h)if(s.get(c,h,e)>t){i=!1;break}if(!i)break}return i}function WAe(e,t){let[n,r,s]=t.shape,a=new d2(n*r*s,({score:o})=>o);for(let o=0;o<n;++o)for(let i=0;i<r;++i)for(let l=0;l<s;++l){let u=t.get(o,i,l);u<e||BAe(l,u,o,i,t)&&a.enqueue({score:u,part:{heatmapY:o,heatmapX:i,id:l}})}return a}function EN(e,{x:t,y:n},r){return e.some(({keypoints:s})=>{var o;let a=(o=s[r])==null?void 0:o.position;return a?TN(n,t,a.y,a.x)<=zAe:!1})}function VAe(e,t){return t.reduce((r,{position:s,score:a},o)=>(EN(e,s,o)||(r+=a),r),0)/t.length}function UAe(e,t,n,r,s,a){let o=[],i=WAe(a,t);for(;o.length<s&&!i.empty();){let l=i.dequeue(),u=V5(l.part,Xc,e);if(EN(o,u,l.part.id))continue;let c=LAe(l,t,e,n,r);c=c.filter(h=>h.score>a);let p=VAe(o,c),d=IN(c);p>a&&o.push({keypoints:c,box:d,score:Math.round(100*p)/100})}return o}async function H5(e,t){let n=K(()=>{if(!Ss.inputs[0].shape)return[];let o=Se.resizeBilinear(e,[Ss.inputs[0].shape[2],Ss.inputs[0].shape[1]]),i=he(de(ge(o,"float32"),127.5),1),u=Ss.execute(i,MAe).map(c=>tt(c,[0]));return u[1]=Tn(u[1]),u}),r=await Promise.all(n.map(o=>o.buffer()));for(let o of n)ne(o);let s=await UAe(r[0],r[1],r[2],r[3],t.body.maxDetected,t.body.minConfidence);return Ss.inputs[0].shape?CN(s,[e.shape[1],e.shape[2]],[Ss.inputs[0].shape[2],Ss.inputs[0].shape[1]]):[]}async function RN(e){return!Ss||pe.initial?Ss=await Ge(e.body.modelPath):e.debug&&oe("cached model:",Ss.modelUrl),Ss}var Ws,j5=!1;async function q5(e){return!Ws||pe.initial?Ws=await Ge(e.segmentation.modelPath):e.debug&&oe("cached model:",Ws.modelUrl),Ws}async function $N(e,t,n){var m,g;if(j5)return{data:[],canvas:null,alpha:null};j5=!0,Ws||await q5(n);let r=await Fc(e,n),s=((m=r.tensor)==null?void 0:m.shape[2])||0,a=((g=r.tensor)==null?void 0:g.shape[1])||0;if(!r.tensor)return{data:[],canvas:null,alpha:null};let o={};o.resize=Se.resizeBilinear(r.tensor,[Ws.inputs[0].shape?Ws.inputs[0].shape[1]:0,Ws.inputs[0].shape?Ws.inputs[0].shape[2]:0],!1),ne(r.tensor),o.norm=de(o.resize,Je.tf255),o.res=Ws.execute(o.norm),o.squeeze=tt(o.res,0),o.squeeze.shape[2]===2?(o.softmax=yc(o.squeeze),[o.bg,o.fg]=rr(o.softmax,2),o.expand=Kt(o.fg,2),o.pad=Kt(o.expand,0),o.crop=Se.cropAndResize(o.pad,[[0,0,.5,.5]],[0],[s,a]),o.data=tt(o.crop,0)):o.data=Se.resizeBilinear(o.squeeze,[a,s]);let i=Array.from(await o.data.data());if(pe.node&&!pe.Canvas&&typeof ImageData=="undefined")return n.debug&&oe("canvas support missing"),Object.keys(o).forEach(y=>ne(o[y])),{data:i,canvas:null,alpha:null};let l=Jn(s,a);Mr&&await Mr.toPixels(o.data,l);let u=l.getContext("2d");n.segmentation.blur&&n.segmentation.blur>0&&(u.filter=`blur(${n.segmentation.blur}px)`);let c=u.getImageData(0,0,s,a),p=Jn(s,a),d=p.getContext("2d");r.canvas&&d.drawImage(r.canvas,0,0),d.globalCompositeOperation="darken",n.segmentation.blur&&n.segmentation.blur>0&&(d.filter=`blur(${n.segmentation.blur}px)`),d.drawImage(l,0,0),d.globalCompositeOperation="source-over",d.filter="none";let h=d.getImageData(0,0,s,a);for(let y=0;y<s*a;y++)h.data[4*y+3]=c.data[4*y+0];d.putImageData(h,0,0);let f=null;if(t&&p){f=Jn(s,a);let y=await Fc(t,n);ne(y.tensor);let x=f.getContext("2d");x.drawImage(y.canvas,0,0,f.width,f.height),x.drawImage(p,0,0)}return Object.keys(o).forEach(y=>ne(o[y])),j5=!1,{data:i,canvas:p,alpha:l}}var ah=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 h2(e){for(let t of Object.keys(e.models))e.models[t]=null}async function X5(e){var t,n,r,s,a,o,i,l,u,c,p,d,h,f,m,g,y,x,A,b,v,S,I,E,R,P,_,D,T,F,U;pe.initial&&h2(e),e.config.hand.enabled&&(!e.models.handpose&&((n=(t=e.config.hand.detector)==null?void 0:t.modelPath)==null?void 0:n.includes("handdetect"))&&([e.models.handpose,e.models.handskeleton]=await T5(e.config)),!e.models.handskeleton&&e.config.hand.landmarks&&((s=(r=e.config.hand.detector)==null?void 0:r.modelPath)==null?void 0:s.includes("handdetect"))&&([e.models.handpose,e.models.handskeleton]=await T5(e.config))),e.config.body.enabled&&!e.models.blazepose&&((o=(a=e.config.body)==null?void 0:a.modelPath)==null?void 0:o.includes("blazepose"))&&(e.models.blazepose=oT(e.config)),e.config.body.enabled&&!e.models.blazeposedetect&&e.config.body.detector&&e.config.body.detector.modelPath&&(e.models.blazeposedetect=aT(e.config)),e.config.body.enabled&&!e.models.efficientpose&&((l=(i=e.config.body)==null?void 0:i.modelPath)==null?void 0:l.includes("efficientpose"))&&(e.models.efficientpose=pT(e.config)),e.config.body.enabled&&!e.models.movenet&&((c=(u=e.config.body)==null?void 0:u.modelPath)==null?void 0:c.includes("movenet"))&&(e.models.movenet=xN(e.config)),e.config.body.enabled&&!e.models.posenet&&((d=(p=e.config.body)==null?void 0:p.modelPath)==null?void 0:d.includes("posenet"))&&(e.models.posenet=RN(e.config)),e.config.face.enabled&&!e.models.facedetect&&(e.models.facedetect=Z9(e.config)),e.config.face.enabled&&((h=e.config.face.antispoof)==null?void 0:h.enabled)&&!e.models.antispoof&&(e.models.antispoof=M9(e.config)),e.config.face.enabled&&((f=e.config.face.liveness)==null?void 0:f.enabled)&&!e.models.liveness&&(e.models.liveness=hN(e.config)),e.config.face.enabled&&((m=e.config.face.description)==null?void 0:m.enabled)&&!e.models.faceres&&(e.models.faceres=OT(e.config)),e.config.face.enabled&&((g=e.config.face.emotion)==null?void 0:g.enabled)&&!e.models.emotion&&(e.models.emotion=gT(e.config)),e.config.face.enabled&&((y=e.config.face.iris)==null?void 0:y.enabled)&&!((x=e.config.face.attention)!=null&&x.enabled)&&!e.models.faceiris&&(e.models.faceiris=CT(e.config)),e.config.face.enabled&&((A=e.config.face.mesh)==null?void 0:A.enabled)&&!e.models.facemesh&&(e.models.facemesh=_T(e.config)),e.config.face.enabled&&((b=e.config.face.gear)==null?void 0:b.enabled)&&!e.models.gear&&(e.models.gear=S9(e.config)),e.config.face.enabled&&((v=e.config.face.ssrnet)==null?void 0:v.enabled)&&!e.models.ssrnetage&&(e.models.ssrnetage=E9(e.config)),e.config.face.enabled&&((S=e.config.face.ssrnet)==null?void 0:S.enabled)&&!e.models.ssrnetgender&&(e.models.ssrnetgender=D9(e.config)),e.config.face.enabled&&((I=e.config.face.mobilefacenet)==null?void 0:I.enabled)&&!e.models.mobilefacenet&&(e.models.mobilefacenet=vT(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=lN(e.config)),e.config.hand.enabled&&e.config.hand.landmarks&&!e.models.handskeleton&&((_=(P=e.config.hand.detector)==null?void 0:P.modelPath)==null?void 0:_.includes("handtrack"))&&(e.models.handskeleton=uN(e.config)),e.config.object.enabled&&!e.models.centernet&&((T=(D=e.config.object)==null?void 0:D.modelPath)==null?void 0:T.includes("centernet"))&&(e.models.centernet=uT(e.config)),e.config.object.enabled&&!e.models.nanodet&&((U=(F=e.config.object)==null?void 0:F.modelPath)==null?void 0:U.includes("nanodet"))&&(e.models.nanodet=wN(e.config)),e.config.segmentation.enabled&&!e.models.segmentation&&(e.models.segmentation=q5(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 K5(e){let t=["const","placeholder","noop","pad","squeeze","add","sub","mul","div"];for(let n of Object.keys(e.models)){let r=e.models[n];if(!r)continue;let s=[],a=r==null?void 0:r.executor;if(a&&a.graph.nodes)for(let i of Object.values(a.graph.nodes)){let l=i.op.toLowerCase();s.includes(l)||s.push(l)}else!a&&e.config.debug&&oe("model signature not determined:",n);let o=[];for(let i of s)!t.includes(i)&&!e.env.kernels.includes(i)&&!e.env.kernels.includes(i.replace("_",""))&&!e.env.kernels.includes(i.replace("native",""))&&!e.env.kernels.includes(i.replace("v2",""))&&o.push(i);e.config.debug&&o.length>0&&oe("model validation failed:",n,o)}}var Et={name:"humangl",priority:999,canvas:null,gl:null,extensions:[],webGLattr:{alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!1,desynchronized:!0}};function GAe(){let e=Et.gl;!e||(Et.extensions=e.getSupportedExtensions())}async function PN(e){var t;if(e.config.backend==="humangl"&&(Et.name in sn().registry&&(!Et.gl||!Et.gl.getParameter(Et.gl.VERSION))&&(oe("error: humangl backend invalid context"),h2(e)),!Py(Et.name))){try{Et.canvas=await Jn(100,100)}catch(r){oe("error: cannot create canvas:",r);return}try{if(Et.gl=(t=Et.canvas)==null?void 0:t.getContext("webgl2",Et.webGLattr),!Et.gl.getParameter(Et.gl.VERSION).includes("2.0")){oe("override: using fallback webgl backend as webgl 2.0 is not detected"),e.config.backend="webgl";return}Et.canvas&&(Et.canvas.addEventListener("webglcontextlost",async s=>{throw oe("error: humangl:",s.type),oe("possible browser memory leak using webgl or conflict with multiple backend registrations"),e.emit("error"),new Error("backend error: webgl context lost")}),Et.canvas.addEventListener("webglcontextrestored",s=>{oe("error: humangl context restored:",s)}),Et.canvas.addEventListener("webglcontextcreationerror",s=>{oe("error: humangl context create:",s)}))}catch(r){oe("error: cannot get WebGL context:",r);return}try{v0(2,Et.gl)}catch(r){oe("error: cannot set WebGL context:",r);return}try{let r=new vu(Et.gl);Rl(Et.name,()=>new Bp(r),Et.priority)}catch(r){oe("error: cannot register WebGL backend:",r);return}try{_s("webgl").forEach(s=>{let a={...s,backendName:Et.name};qr(a)})}catch(r){oe("error: cannot update WebGL backend registration:",r);return}let n=zr().getGPGPUContext?zr().getGPGPUContext().gl:null;if(n)oe(`humangl webgl version:${n.getParameter(n.VERSION)} renderer:${n.getParameter(n.RENDERER)}`);else{oe("error: no current gl context:",n,Et.gl);return}try{xs.set("WEBGL_VERSION",2)}catch(r){oe("error: cannot set WebGL backend flags:",r);return}GAe(),oe("backend registered:",Et.name)}}function HAe(){if(!pe.kernels.includes("mod")){let e={kernelName:"Mod",backendName:qn(),kernelFunc:t=>K(()=>he(t.inputs.a,L(de(t.inputs.a,t.inputs.b),t.inputs.b)))};qr(e),pe.kernels.push("mod")}if(!pe.kernels.includes("floormod")){let e={kernelName:"FloorMod",backendName:qn(),kernelFunc:t=>K(()=>xp(t.inputs.a/t.inputs.b)*t.inputs.b+mc(t.inputs.a,t.inputs.b))};qr(e),pe.kernels.push("floormod")}}async function m2(e,t=!1){if(e.state="backend",t||pe.initial||e.config.backend&&e.config.backend.length>0&&qn()!==e.config.backend){let n=le();if(e.config.backend&&e.config.backend.length>0){if(typeof window=="undefined"&&typeof WorkerGlobalScope!="undefined"&&e.config.debug&&e.config.debug&&oe("running inside web worker"),pe.browser&&e.config.backend==="tensorflow"&&(e.config.debug&&oe("override: backend set to tensorflow while running in browser"),e.config.backend="humangl"),pe.node&&(e.config.backend==="webgl"||e.config.backend==="humangl")&&(e.config.debug&&oe(`override: backend set to ${e.config.backend} while running in nodejs`),e.config.backend="tensorflow"),pe.browser&&e.config.backend==="webgpu")if(typeof navigator=="undefined"||typeof navigator.gpu=="undefined")oe("override: backend set to webgpu but browser does not support webgpu"),e.config.backend="humangl";else{let s=await navigator.gpu.requestAdapter();e.config.debug&&oe("enumerated webgpu adapter:",s)}e.config.backend==="humangl"&&await PN(e);let r=Object.keys(sn().registryFactory);if(e.config.debug&&oe("available backends:",r),r.includes(e.config.backend)||(oe(`error: backend ${e.config.backend} not found in registry`),e.config.backend=pe.node?"tensorflow":"webgl",e.config.debug&&oe(`override: setting backend ${e.config.backend}`)),e.config.debug&&oe("setting backend:",e.config.backend),e.config.backend==="wasm"){if(e.config.debug&&oe("wasm path:",e.config.wasmPath),typeof(Ue==null?void 0:Ue.setWasmPaths)!="undefined")await _3(e.config.wasmPath,e.config.wasmPlatformFetch);else throw new Error("backend error: attempting to use wasm backend but wasm path is not set");let s=await Y().getAsync("WASM_HAS_SIMD_SUPPORT"),a=await Y().getAsync("WASM_HAS_MULTITHREAD_SUPPORT");e.config.debug&&oe(`wasm execution: ${s?"SIMD":"no SIMD"} ${a?"multithreaded":"singlethreaded"}`),e.config.debug&&!s&&oe("warning: wasm simd support is not enabled")}try{await Dy(e.config.backend),await dc(),C9()}catch(s){return oe("error: cannot set backend:",e.config.backend,s),!1}}if(qn()==="humangl"&&(xs.set("CHECK_COMPUTATION_FOR_ERRORS",!1),xs.set("WEBGL_CPU_FORWARD",!0),xs.set("WEBGL_USE_SHAPES_UNIFORMS",!0),xs.set("CPU_HANDOFF_SIZE_THRESHOLD",256),typeof e.config.deallocate!="undefined"&&e.config.deallocate&&(oe("changing webgl: WEBGL_DELETE_TEXTURE_THRESHOLD:",!0),xs.set("WEBGL_DELETE_TEXTURE_THRESHOLD",0)),zr().getGPGPUContext)){let r=await zr().getGPGPUContext().gl;e.config.debug&&oe(`gl version:${r.getParameter(r.VERSION)} renderer:${r.getParameter(r.RENDERER)}`)}qn(),_y(),await dc(),e.performance.initBackend=Math.trunc(le()-n),e.config.backend=qn(),await pe.updateBackend(),HAe()}return!0}function r2(e,t){for(let n of e){let r={kernelName:n,backendName:t.backend,kernelFunc:()=>{t.debug&&oe("kernelFunc",n,t.backend)}};qr(r)}pe.kernels=_s(qn()).map(n=>n.kernelName.toLowerCase())}var nb={};wa(nb,{all:()=>tb,body:()=>Zc,canvas:()=>eb,face:()=>Kc,gesture:()=>Qc,hand:()=>Yc,object:()=>Jc,options:()=>Dn,person:()=>Q5});var Wr=e=>{if(!e)oe("draw error: invalid canvas");else if(!e.getContext)oe("draw error: canvas context not defined");else{let t=e.getContext("2d");if(!t)oe("draw error: cannot get canvas context");else return t}return null},ql=e=>Math.round(e*180/Math.PI),ya=(e,t)=>{if(!t.useDepth||typeof e=="undefined")return t.color;let n=Uint8ClampedArray.from([127+2*e,127-2*e,255]);return`rgba(${n[0]}, ${n[1]}, ${n[2]}, ${t.alpha})`};function Xl(e,t,n,r,s){e.fillStyle=ya(r,s),e.beginPath(),e.arc(t,n,s.pointSize,0,2*Math.PI),e.fill()}function Vs(e,t,n,r,s,a){if(e.beginPath(),e.lineWidth=a.lineWidth,a.useCurves){let o=(t+t+r)/2,i=(n+n+s)/2;e.ellipse(o,i,r/2,s/2,0,0,2*Math.PI)}else e.moveTo(t+a.roundRect,n),e.lineTo(t+r-a.roundRect,n),e.quadraticCurveTo(t+r,n,t+r,n+a.roundRect),e.lineTo(t+r,n+s-a.roundRect),e.quadraticCurveTo(t+r,n+s,t+r-a.roundRect,n+s),e.lineTo(t+a.roundRect,n+s),e.quadraticCurveTo(t,n+s,t,n+s-a.roundRect),e.lineTo(t,n+a.roundRect),e.quadraticCurveTo(t,n,t+a.roundRect,n),e.closePath();e.stroke()}function Z5(e,t,n){if(!(t.length<2)){e.beginPath(),e.moveTo(t[0][0],t[0][1]);for(let r of t)e.strokeStyle=ya(r[2],n),e.lineTo(Math.trunc(r[0]),Math.trunc(r[1]));e.stroke(),n.fillPolygons&&(e.closePath(),e.fill())}}function ON(e,t,n){if(!(t.length<2)){if(e.lineWidth=n.lineWidth,!n.useCurves||t.length<=2){Z5(e,t,n);return}e.moveTo(t[0][0],t[0][1]);for(let r=0;r<t.length-2;r++){let s=(t[r][0]+t[r+1][0])/2,a=(t[r][1]+t[r+1][1])/2;e.quadraticCurveTo(t[r][0],t[r][1],s,a)}e.quadraticCurveTo(t[t.length-2][0],t[t.length-2][1],t[t.length-1][0],t[t.length-1][1]),e.stroke(),n.fillPolygons&&(e.closePath(),e.fill())}}function Y5(e,t,n,r=5){let s,a,o;e.beginPath(),e.moveTo(t[0],t[1]),e.lineTo(n[0],n[1]),s=Math.atan2(n[1]-t[1],n[0]-t[0]),a=r*Math.cos(s)+n[0],o=r*Math.sin(s)+n[1],e.moveTo(a,o),s+=1/3*(2*Math.PI),a=r*Math.cos(s)+n[0],o=r*Math.sin(s)+n[1],e.lineTo(a,o),s+=1/3*(2*Math.PI),a=r*Math.cos(s)+n[0],o=r*Math.sin(s)+n[1],e.lineTo(a,o),e.closePath(),e.stroke(),e.fill()}var Dn={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 ht;function qAe(e,t){if(ht.drawLabels){let n=[];if(n.push(`face: ${Math.trunc(100*e.score)}%`),e.genderScore&&n.push(`${e.gender||""} ${Math.trunc(100*e.genderScore)}%`),e.age&&n.push(`age: ${e.age||""}`),e.iris&&n.push(`distance: ${e.iris}`),e.real&&n.push(`real: ${Math.trunc(100*e.real)}%`),e.live&&n.push(`live: ${Math.trunc(100*e.live)}%`),e.emotion&&e.emotion.length>0){let r=e.emotion.map(s=>`${Math.trunc(100*s.score)}% ${s.emotion}`);r.length>3&&(r.length=3),n.push(r.join(" "))}e.rotation&&e.rotation.angle&&e.rotation.gaze&&(e.rotation.angle.roll&&n.push(`roll: ${ql(e.rotation.angle.roll)}\xB0 yaw:${ql(e.rotation.angle.yaw)}\xB0 pitch:${ql(e.rotation.angle.pitch)}\xB0`),e.rotation.gaze.bearing&&n.push(`gaze: ${ql(e.rotation.gaze.bearing)}\xB0`)),n.length===0&&n.push("face"),t.fillStyle=ht.color;for(let r=n.length-1;r>=0;r--){let s=Math.max(e.box[0],0),a=r*ht.lineHeight+e.box[1];ht.shadowColor&&ht.shadowColor!==""&&(t.fillStyle=ht.shadowColor,t.fillText(n[r],s+5,a+16)),t.fillStyle=ht.labelColor,t.fillText(n[r],s+4,a+15)}}}function XAe(e,t){if(e.annotations&&e.annotations.leftEyeIris&&e.annotations.leftEyeIris[0]){t.strokeStyle=ht.useDepth?"rgba(255, 200, 255, 0.3)":ht.color,t.beginPath();let n=Math.abs(e.annotations.leftEyeIris[3][0]-e.annotations.leftEyeIris[1][0])/2,r=Math.abs(e.annotations.leftEyeIris[4][1]-e.annotations.leftEyeIris[2][1])/2;t.ellipse(e.annotations.leftEyeIris[0][0],e.annotations.leftEyeIris[0][1],n,r,0,0,2*Math.PI),t.stroke(),ht.fillPolygons&&(t.fillStyle=ht.useDepth?"rgba(255, 255, 200, 0.3)":ht.color,t.fill())}if(e.annotations&&e.annotations.rightEyeIris&&e.annotations.rightEyeIris[0]){t.strokeStyle=ht.useDepth?"rgba(255, 200, 255, 0.3)":ht.color,t.beginPath();let n=Math.abs(e.annotations.rightEyeIris[3][0]-e.annotations.rightEyeIris[1][0])/2,r=Math.abs(e.annotations.rightEyeIris[4][1]-e.annotations.rightEyeIris[2][1])/2;t.ellipse(e.annotations.rightEyeIris[0][0],e.annotations.rightEyeIris[0][1],n,r,0,0,2*Math.PI),t.stroke(),ht.fillPolygons&&(t.fillStyle=ht.useDepth?"rgba(255, 255, 200, 0.3)":ht.color,t.fill())}}function KAe(e,t){var n;if(ht.drawGaze&&((n=e.rotation)==null?void 0:n.angle)&&typeof Path2D!="undefined"){t.strokeStyle="pink";let r=e.box[0]+e.box[2]/2-e.box[3]*ql(e.rotation.angle.yaw)/90,s=e.box[1]+e.box[3]/2+e.box[2]*ql(e.rotation.angle.pitch)/90,a=new Path2D(`
|
|
M ${e.box[0]+e.box[2]/2} ${e.box[1]}
|
|
C
|
|
${r} ${e.box[1]},
|
|
${r} ${e.box[1]+e.box[3]},
|
|
${e.box[0]+e.box[2]/2} ${e.box[1]+e.box[3]}
|
|
`),o=new Path2D(`
|
|
M ${e.box[0]} ${e.box[1]+e.box[3]/2}
|
|
C
|
|
${e.box[0]} ${s},
|
|
${e.box[0]+e.box[2]} ${s},
|
|
${e.box[0]+e.box[2]} ${e.box[1]+e.box[3]/2}
|
|
`);t.stroke(o),t.stroke(a)}}function ZAe(e,t){var n,r,s,a;if(ht.drawGaze&&((r=(n=e.rotation)==null?void 0:n.gaze)==null?void 0:r.strength)&&((a=(s=e.rotation)==null?void 0:s.gaze)==null?void 0:a.bearing)&&e.annotations.leftEyeIris&&e.annotations.rightEyeIris&&e.annotations.leftEyeIris[0]&&e.annotations.rightEyeIris[0]){t.strokeStyle="pink",t.fillStyle="pink";let o=[e.annotations.leftEyeIris[0][0]+Math.sin(e.rotation.gaze.bearing)*e.rotation.gaze.strength*e.box[3],e.annotations.leftEyeIris[0][1]+Math.cos(e.rotation.gaze.bearing)*e.rotation.gaze.strength*e.box[2]];Y5(t,[e.annotations.leftEyeIris[0][0],e.annotations.leftEyeIris[0][1]],[o[0],o[1]],4);let i=[e.annotations.rightEyeIris[0][0]+Math.sin(e.rotation.gaze.bearing)*e.rotation.gaze.strength*e.box[3],e.annotations.rightEyeIris[0][1]+Math.cos(e.rotation.gaze.bearing)*e.rotation.gaze.strength*e.box[2]];Y5(t,[e.annotations.rightEyeIris[0][0],e.annotations.rightEyeIris[0][1]],[i[0],i[1]],4)}}function YAe(e,t){if(ht.drawPolygons&&e.mesh.length>=468){t.lineWidth=1;for(let n=0;n<Bl.length/3;n++){let r=[Bl[n*3+0],Bl[n*3+1],Bl[n*3+2]].map(s=>e.mesh[s]);Z5(t,r,ht)}XAe(e,t)}}function JAe(e,t){let n=Math.max(468,e.mesh.length);if(ht.drawPoints&&e.mesh.length>=468)for(let r=0;r<n;r++)Xl(t,e.mesh[r][0],e.mesh[r][1],e.mesh[r][2],ht);if(ht.drawAttention&&e.mesh.length>468)for(let r=468;r<e.mesh.length;r++)Xl(t,e.mesh[r][0],e.mesh[r][1],e.mesh[r][2],ht)}function QAe(e,t){ht.drawBoxes&&Vs(t,e.box[0],e.box[1],e.box[2],e.box[3],ht)}async function Kc(e,t,n){if(ht=Gt(Dn,n),!t||!e)return;let r=Wr(e);if(!!r){r.font=ht.font,r.strokeStyle=ht.color,r.fillStyle=ht.color;for(let s of t)QAe(s,r),qAe(s,r),s.mesh&&s.mesh.length>0&&(JAe(s,r),YAe(s,r),KAe(s,r),ZAe(s,r))}}async function Zc(e,t,n){var a;let r=Gt(Dn,n);if(!t||!e)return;let s=Wr(e);if(!!s){s.lineJoin="round";for(let o=0;o<t.length;o++){if(s.strokeStyle=r.color,s.fillStyle=r.color,s.lineWidth=r.lineWidth,s.font=r.font,r.drawBoxes&&t[o].box&&((a=t[o].box)==null?void 0:a.length)===4&&(Vs(s,t[o].box[0],t[o].box[1],t[o].box[2],t[o].box[3],r),r.drawLabels&&(r.shadowColor&&r.shadowColor!==""&&(s.fillStyle=r.shadowColor,s.fillText(`body ${100*t[o].score}%`,t[o].box[0]+3,1+t[o].box[1]+r.lineHeight,t[o].box[2])),s.fillStyle=r.labelColor,s.fillText(`body ${100*t[o].score}%`,t[o].box[0]+2,0+t[o].box[1]+r.lineHeight,t[o].box[2]))),r.drawPoints&&t[o].keypoints)for(let i=0;i<t[o].keypoints.length;i++)!t[o].keypoints[i].score||t[o].keypoints[i].score===0||(s.fillStyle=ya(t[o].keypoints[i].position[2],r),Xl(s,t[o].keypoints[i].position[0],t[o].keypoints[i].position[1],0,r));if(r.drawLabels&&t[o].keypoints){s.font=r.font;for(let i of t[o].keypoints)!i.score||i.score===0||(s.fillStyle=ya(i.position[2],r),s.fillText(`${i.part} ${Math.trunc(100*i.score)}%`,i.position[0]+4,i.position[1]+4))}if(r.drawPolygons&&t[o].keypoints&&t[o].annotations)for(let i of Object.values(t[o].annotations))for(let l of i)ON(s,l,r)}}}async function Yc(e,t,n){let r=Gt(Dn,n);if(!t||!e)return;let s=Wr(e);if(!!s){s.lineJoin="round",s.font=r.font;for(let a of t){if(r.drawBoxes&&(s.strokeStyle=r.color,s.fillStyle=r.color,Vs(s,a.box[0],a.box[1],a.box[2],a.box[3],r),r.drawLabels&&(r.shadowColor&&r.shadowColor!==""&&(s.fillStyle=r.shadowColor,s.fillText(`hand:${Math.trunc(100*a.score)}%`,a.box[0]+3,1+a.box[1]+r.lineHeight,a.box[2])),s.fillStyle=r.labelColor,s.fillText(`hand:${Math.trunc(100*a.score)}%`,a.box[0]+2,0+a.box[1]+r.lineHeight,a.box[2])),s.stroke()),r.drawPoints&&a.keypoints&&a.keypoints.length>0)for(let o of a.keypoints)s.fillStyle=ya(o[2],r),Xl(s,o[0],o[1],0,r);if(r.drawLabels&&a.annotations){let o=(i,l)=>{if(!i||i.length===0||!i[0])return;let u=i[i.length-1][2]||-256;s.fillStyle=ya(u,r),s.fillText(l,i[i.length-1][0]+4,i[i.length-1][1]+4)};s.font=r.font,o(a.annotations.index,"index"),o(a.annotations.middle,"middle"),o(a.annotations.ring,"ring"),o(a.annotations.pinky,"pinky"),o(a.annotations.thumb,"thumb"),o(a.annotations.palm,"palm")}if(r.drawPolygons&&a.annotations){let o=i=>{if(!(!i||i.length===0||!i[0]))for(let l=0;l<i.length;l++){s.beginPath();let u=i[l][2]||0;s.strokeStyle=ya(l*u,r),s.moveTo(i[l>0?l-1:0][0],i[l>0?l-1:0][1]),s.lineTo(i[l][0],i[l][1]),s.stroke()}};s.lineWidth=r.lineWidth,o(a.annotations.index),o(a.annotations.middle),o(a.annotations.ring),o(a.annotations.pinky),o(a.annotations.thumb)}}}}async function Jc(e,t,n){let r=Gt(Dn,n);if(!t||!e)return;let s=Wr(e);if(!!s){s.lineJoin="round",s.font=r.font;for(let a of t)if(r.drawBoxes){if(s.strokeStyle=r.color,s.fillStyle=r.color,Vs(s,a.box[0],a.box[1],a.box[2],a.box[3],r),r.drawLabels){let o=`${a.label} ${Math.round(100*a.score)}%`;r.shadowColor&&r.shadowColor!==""&&(s.fillStyle=r.shadowColor,s.fillText(o,a.box[0]+3,1+a.box[1]+r.lineHeight,a.box[2])),s.fillStyle=r.labelColor,s.fillText(o,a.box[0]+2,0+a.box[1]+r.lineHeight,a.box[2])}s.stroke()}}}async function Qc(e,t,n){let r=Gt(Dn,n);if(!(!t||!e)&&r.drawGestures){let s=Wr(e);if(!s)return;s.font=r.font,s.fillStyle=r.color;let a=1;for(let o=0;o<t.length;o++){let i=[],l=[];if([i,l]=Object.entries(t[o]),l.length>1&&l[1].length>0){let u=i[1]>0?`#${i[1]}`:"",c=`${i[0]} ${u}: ${l[1]}`;r.shadowColor&&r.shadowColor!==""&&(s.fillStyle=r.shadowColor,s.fillText(c,8,2+a*r.lineHeight)),s.fillStyle=r.labelColor,s.fillText(c,6,0+a*r.lineHeight),a+=1}}}}var J5=0;async function Q5(e,t,n){let r=Gt(Dn,n);if(!t||!e)return;let s=Wr(e);if(!!s){s.lineJoin="round",s.font=r.font;for(let a=0;a<t.length;a++)if(r.drawBoxes){if(s.strokeStyle=r.color,s.fillStyle=r.color,Vs(s,t[a].box[0],t[a].box[1],t[a].box[2],t[a].box[3],r),r.drawLabels){let o=`person #${a}`;r.shadowColor&&r.shadowColor!==""&&(s.fillStyle=r.shadowColor,s.fillText(o,t[a].box[0]+3,1+t[a].box[1]+r.lineHeight,t[a].box[2])),s.fillStyle=r.labelColor,s.fillText(o,t[a].box[0]+2,0+t[a].box[1]+r.lineHeight,t[a].box[2])}s.stroke()}}}async function eb(e,t){if(!e||!t)return;let n=Wr(t);!n||n.drawImage(e,0,0)}async function tb(e,t,n){if(!t||!t.performance||!t||!e)return null;let r=le(),s=Gt(Dn,n),a=Promise.all([Kc(e,t.face,s),Zc(e,t.body,s),Yc(e,t.hand,s),Jc(e,t.object,s),Qc(e,t.gesture,s)]);return J5=pe.perfadd?J5+Math.round(le()-r):Math.round(le()-r),t.performance.draw=J5,a}var ed=.1,rb=.5;function exe(e,t,n){let r=!1,s=n.length-1;for(let a=0;a<n.length;s=a++)n[a].y>t!=n[s].y>t&&e<(n[s].x-n[a].x)*(t-n[a].y)/(n[s].y-n[a].y)+n[a].x&&(r=!r);return r}async function MN(e){if(!e.tensor||!e.mesh||e.mesh.length<100)return e.tensor;let t=e.tensor.shape[2]||0,n=e.tensor.shape[1]||0,r=await e.tensor.buffer(),s=[];for(let o of es.silhouette)s.push({x:(e.mesh[o][0]-e.box[0])/e.box[2],y:(e.mesh[o][1]-e.box[1])/e.box[3]});ed&&ed>0&&(s=s.map(o=>({x:o.x>.5?o.x+ed:o.x-ed,y:o.y>.5?o.y+ed:o.y-ed})));for(let o=0;o<t;o++)for(let i=0;i<n;i++)exe(o/t,i/t,s)||(r.set(rb*r.get(0,i,o,0),0,i,o,0),r.set(rb*r.get(0,i,o,1),0,i,o,1),r.set(rb*r.get(0,i,o,2),0,i,o,2));let a=r.toTensor();return ne(r),a}var nxe=e=>{let t=(p,d)=>Math.atan2(p[1]-d[1],p[0]-d[0]);if(!e.annotations.rightEyeIris||!e.annotations.leftEyeIris)return{bearing:0,strength:0};let n=[0,-.1],r=1,s=(e.mesh[33][2]||0)>(e.mesh[263][2]||0),a=s?e.mesh[473]:e.mesh[468],o=s?[(e.mesh[133][0]+e.mesh[33][0])/2,(e.mesh[133][1]+e.mesh[33][1])/2]:[(e.mesh[263][0]+e.mesh[362][0])/2,(e.mesh[263][1]+e.mesh[362][1])/2],i=s?[e.mesh[133][0]-e.mesh[33][0],e.mesh[23][1]-e.mesh[27][1]]:[e.mesh[263][0]-e.mesh[362][0],e.mesh[253][1]-e.mesh[257][1]],l=[(o[0]-a[0])/i[0]-n[0],r*(a[1]-o[1])/i[1]-n[1]],u=Math.sqrt(l[0]*l[0]+l[1]*l[1]);return u=Math.min(u,e.boxRaw[2]/2,e.boxRaw[3]/2),{bearing:(t([0,0],l)+Math.PI/2)%Math.PI,strength:u}},zN=(e,t)=>{let n=m=>{let g=Math.sqrt(m[0]*m[0]+m[1]*m[1]+m[2]*m[2]);return m[0]/=g,m[1]/=g,m[2]/=g,m},r=(m,g)=>{let y=m[0]-g[0],x=m[1]-g[1],A=m[2]-g[2];return[y,x,A]},s=(m,g)=>{let y=m[1]*g[2]-m[2]*g[1],x=m[2]*g[0]-m[0]*g[2],A=m[0]*g[1]-m[1]*g[0];return[y,x,A]},a=m=>{let[g,y,x,A,b,v,S,I,E]=m,R,P,_;return A<1?A>-1?(_=Math.asin(A),P=Math.atan2(-S,g),R=Math.atan2(-v,b)):(_=-Math.PI/2,P=-Math.atan2(I,E),R=0):(_=Math.PI/2,P=Math.atan2(I,E),R=0),isNaN(R)&&(R=0),isNaN(P)&&(P=0),isNaN(_)&&(_=0),{pitch:2*-R,yaw:2*-P,roll:2*-_}},o=e.meshRaw;if(!o||o.length<300)return{angle:{pitch:0,yaw:0,roll:0},matrix:[1,0,0,0,1,0,0,0,1],gaze:{bearing:0,strength:0}};let i=Math.max(e.boxRaw[2]*t[0],e.boxRaw[3]*t[1])/1.5,l=[o[10],o[152],o[234],o[454]].map(m=>[m[0]*t[0]/i,m[1]*t[1]/i,m[2]]),u=n(r(l[1],l[0])),c=n(r(l[3],l[2])),p=n(s(c,u));c=s(u,p);let d=[c[0],c[1],c[2],u[0],u[1],u[2],p[0],p[1],p[2]],h=a(d),f=o.length===478?nxe(e):{bearing:0,strength:0};return{angle:h,matrix:d,gaze:f}};var sb=async(e,t)=>{var h,f,m,g,y,x,A,b,v,S,I,E,R,P,_,D,T,F,U,X,z,Z;let n=le(),r,s,a,o,i,l,u,c,p=[];e.state="run:face";let d=await RT(t,e.config);if(e.performance.face=pe.perfadd?(e.performance.face||0)+Math.trunc(le()-n):Math.trunc(le()-n),!t.shape||t.shape.length!==4)return[];if(!d)return[];for(let W=0;W<d.length;W++){if(e.analyze("Get Face"),!d[W].tensor||d[W].tensor.isDisposedInternal){oe("Face object is disposed:",d[W].tensor);continue}if((h=e.config.face.detector)!=null&&h.mask){let se=await MN(d[W]);ne(d[W].tensor),d[W].tensor=se}let ee=d[W].mesh&&d[W].mesh.length>200?zN(d[W],[t.shape[2],t.shape[1]]):null;e.analyze("Start Emotion:"),e.config.async?o=(f=e.config.face.emotion)!=null&&f.enabled?p5(d[W].tensor||pt([]),e.config,W,d.length):[]:(e.state="run:emotion",n=le(),o=(m=e.config.face.emotion)!=null&&m.enabled?await p5(d[W].tensor||pt([]),e.config,W,d.length):[],e.performance.emotion=pe.perfadd?(e.performance.emotion||0)+Math.trunc(le()-n):Math.trunc(le()-n)),e.analyze("End Emotion:"),e.analyze("Start AntiSpoof:"),e.config.async?l=(g=e.config.face.antispoof)!=null&&g.enabled?H3(d[W].tensor||pt([]),e.config,W,d.length):0:(e.state="run:antispoof",n=le(),l=(y=e.config.face.antispoof)!=null&&y.enabled?await H3(d[W].tensor||pt([]),e.config,W,d.length):0,e.performance.antispoof=pe.perfadd?(e.performance.antispoof||0)+Math.trunc(le()-n):Math.trunc(le()-n)),e.analyze("End AntiSpoof:"),e.analyze("Start Liveness:"),e.config.async?u=(x=e.config.face.liveness)!=null&&x.enabled?$5(d[W].tensor||pt([]),e.config,W,d.length):0:(e.state="run:liveness",n=le(),u=(A=e.config.face.liveness)!=null&&A.enabled?await $5(d[W].tensor||pt([]),e.config,W,d.length):0,e.performance.liveness=pe.perfadd?(e.performance.antispoof||0)+Math.trunc(le()-n):Math.trunc(le()-n)),e.analyze("End Liveness:"),e.analyze("Start GEAR:"),e.config.async?s=(b=e.config.face.gear)!=null&&b.enabled?z3(d[W].tensor||pt([]),e.config,W,d.length):null:(e.state="run:gear",n=le(),s=(v=e.config.face.gear)!=null&&v.enabled?await z3(d[W].tensor||pt([]),e.config,W,d.length):null,e.performance.gear=Math.trunc(le()-n)),e.analyze("End GEAR:"),e.analyze("Start SSRNet:"),e.config.async?(r=(S=e.config.face.ssrnet)!=null&&S.enabled?B3(d[W].tensor||pt([]),e.config,W,d.length):null,a=(I=e.config.face.ssrnet)!=null&&I.enabled?U3(d[W].tensor||pt([]),e.config,W,d.length):null):(e.state="run:ssrnet",n=le(),r=(E=e.config.face.ssrnet)!=null&&E.enabled?await B3(d[W].tensor||pt([]),e.config,W,d.length):null,a=(R=e.config.face.ssrnet)!=null&&R.enabled?await U3(d[W].tensor||pt([]),e.config,W,d.length):null,e.performance.ssrnet=Math.trunc(le()-n)),e.analyze("End SSRNet:"),e.analyze("Start MobileFaceNet:"),e.config.async?i=(P=e.config.face.mobilefacenet)!=null&&P.enabled?f5(d[W].tensor||pt([]),e.config,W,d.length):null:(e.state="run:mobilefacenet",n=le(),i=(_=e.config.face.mobilefacenet)!=null&&_.enabled?await f5(d[W].tensor||pt([]),e.config,W,d.length):null,e.performance.mobilefacenet=Math.trunc(le()-n)),e.analyze("End MobileFaceNet:"),e.analyze("Start Description:"),e.config.async?c=(D=e.config.face.description)!=null&&D.enabled?b5(d[W].tensor||pt([]),e.config,W,d.length):null:(e.state="run:description",n=le(),c=(T=e.config.face.description)!=null&&T.enabled?await b5(d[W].tensor||pt([]),e.config,W,d.length):null,e.performance.description=pe.perfadd?(e.performance.description||0)+Math.trunc(le()-n):Math.trunc(le()-n)),e.analyze("End Description:"),e.config.async&&([r,a,o,i,c,s,l,u]=await Promise.all([r,a,o,i,c,s,l,u])),e.analyze("Finish Face:"),((F=e.config.face.ssrnet)==null?void 0:F.enabled)&&r&&a&&(c={...c,age:r.age,gender:a.gender,genderScore:a.genderScore}),((U=e.config.face.gear)==null?void 0:U.enabled)&&s&&(c={...c,age:s.age,gender:s.gender,genderScore:s.genderScore,race:s.race}),((X=e.config.face.mobilefacenet)==null?void 0:X.enabled)&&i&&(c.descriptor=i),(z=e.config.face.iris)!=null&&z.enabled;let Q=d[W].annotations&&d[W].annotations.leftEyeIris&&d[W].annotations.leftEyeIris[0]&&d[W].annotations.rightEyeIris&&d[W].annotations.rightEyeIris[0]&&d[W].annotations.leftEyeIris.length>0&&d[W].annotations.rightEyeIris.length>0&&d[W].annotations.leftEyeIris[0]!==null&&d[W].annotations.rightEyeIris[0]!==null?Math.max(Math.abs(d[W].annotations.leftEyeIris[3][0]-d[W].annotations.leftEyeIris[1][0]),Math.abs(d[W].annotations.rightEyeIris[4][1]-d[W].annotations.rightEyeIris[2][1]))/t.shape[2]:0,ae=(Z=e.config.face.detector)!=null&&Z.return?tt(d[W].tensor):null;ne(d[W].tensor),d[W].tensor&&delete d[W].tensor;let J={...d[W],id:W};c!=null&&c.age&&(J.age=c.age),c!=null&&c.gender&&(J.gender=c.gender),c!=null&&c.genderScore&&(J.genderScore=c==null?void 0:c.genderScore),c!=null&&c.descriptor&&(J.embedding=c==null?void 0:c.descriptor),c!=null&&c.race&&(J.race=c==null?void 0:c.race),o&&(J.emotion=o),l&&(J.real=l),u&&(J.live=u),Q&&Q!==0&&(J.iris=Math.trunc(500/Q/11.7)/100),ee&&(J.rotation=ee),ae&&(J.tensor=ae),p.push(J),e.analyze("End Face")}return e.analyze("End FaceMesh:"),e.config.async&&(e.performance.face&&delete e.performance.face,e.performance.age&&delete e.performance.age,e.performance.gender&&delete e.performance.gender,e.performance.emotion&&delete e.performance.emotion),p};var LN=e=>{if(!e)return[];let t=[];for(let n=0;n<e.length;n++){let r=e[n].keypoints.find(l=>l.part==="leftWrist"),s=e[n].keypoints.find(l=>l.part==="rightWrist"),a=e[n].keypoints.find(l=>l.part==="nose");a&&r&&s&&r.position[1]<a.position[1]&&s.position[1]<a.position[1]?t.push({body:n,gesture:"i give up"}):a&&r&&r.position[1]<a.position[1]?t.push({body:n,gesture:"raise left hand"}):a&&s&&s.position[1]<a.position[1]&&t.push({body:n,gesture:"raise right hand"});let o=e[n].keypoints.find(l=>l.part==="leftShoulder"),i=e[n].keypoints.find(l=>l.part==="rightShoulder");o&&i&&Math.abs(o.positionRaw[1]-i.positionRaw[1])>.1&&t.push({body:n,gesture:`leaning ${o.position[1]>i.position[1]?"left":"right"}`})}return t},BN=e=>{if(!e)return[];let t=[];for(let n=0;n<e.length;n++)if(e[n].mesh&&e[n].mesh.length>450){let r=(e[n].mesh[33][2]||0)-(e[n].mesh[263][2]||0),s=e[n].mesh[33][0]-e[n].mesh[263][0];Math.abs(r/s)<=.15?t.push({face:n,gesture:"facing center"}):t.push({face:n,gesture:`facing ${r<0?"left":"right"}`}),Math.abs(e[n].mesh[374][1]-e[n].mesh[386][1])/Math.abs(e[n].mesh[443][1]-e[n].mesh[450][1])<.2&&t.push({face:n,gesture:"blink left eye"}),Math.abs(e[n].mesh[145][1]-e[n].mesh[159][1])/Math.abs(e[n].mesh[223][1]-e[n].mesh[230][1])<.2&&t.push({face:n,gesture:"blink right eye"});let i=Math.min(100,500*Math.abs(e[n].mesh[13][1]-e[n].mesh[14][1])/Math.abs(e[n].mesh[10][1]-e[n].mesh[152][1]));i>10&&t.push({face:n,gesture:`mouth ${Math.trunc(i)}% open`});let l=e[n].mesh[152][2]||0;Math.abs(l)>10&&t.push({face:n,gesture:`head ${l<0?"up":"down"}`})}return t},WN=e=>{if(!e)return[];let t=[];for(let n=0;n<e.length;n++){if(!e[n].annotations||!e[n].annotations.leftEyeIris||!e[n].annotations.leftEyeIris[0]||!e[n].annotations.rightEyeIris||!e[n].annotations.rightEyeIris[0])continue;let r=e[n].annotations.leftEyeIris[3][0]-e[n].annotations.leftEyeIris[1][0],s=e[n].annotations.leftEyeIris[4][1]-e[n].annotations.leftEyeIris[2][1],a=Math.abs(r*s),o=e[n].annotations.rightEyeIris[3][0]-e[n].annotations.rightEyeIris[1][0],i=e[n].annotations.rightEyeIris[4][1]-e[n].annotations.rightEyeIris[2][1],l=Math.abs(o*i),u=!1;Math.abs(a-l)/Math.max(a,l)<.25&&(u=!0,t.push({iris:n,gesture:"facing center"}));let p=Math.abs(e[n].mesh[263][0]-e[n].annotations.leftEyeIris[0][0])/e[n].box[2],d=Math.abs(e[n].mesh[33][0]-e[n].annotations.rightEyeIris[0][0])/e[n].box[2];(p>.06||d>.06)&&(u=!1),p>d?p>.05&&t.push({iris:n,gesture:"looking right"}):d>.05&&t.push({iris:n,gesture:"looking left"});let h=Math.abs(e[n].mesh[145][1]-e[n].annotations.rightEyeIris[0][1])/e[n].box[3],f=Math.abs(e[n].mesh[374][1]-e[n].annotations.leftEyeIris[0][1])/e[n].box[3];(f<.01||h<.01||f>.022||h>.022)&&(u=!1),(f<.01||h<.01)&&t.push({iris:n,gesture:"looking down"}),(f>.022||h>.022)&&t.push({iris:n,gesture:"looking up"}),u&&t.push({iris:n,gesture:"looking center"})}return t},VN=e=>{if(!e)return[];let t=[];for(let n=0;n<e.length;n++){let r=[];if(e[n].annotations)for(let[s,a]of Object.entries(e[n].annotations))s!=="palmBase"&&Array.isArray(a)&&a[0]&&r.push({name:s.toLowerCase(),position:a[0]});if(r&&r.length>0){let s=r.reduce((o,i)=>(o.position[2]||0)<(i.position[2]||0)?o:i);t.push({hand:n,gesture:`${s.name} forward`});let a=r.reduce((o,i)=>o.position[1]<i.position[1]?o:i);t.push({hand:n,gesture:`${a.name} up`})}if(e[n].keypoints){let s=tN(e[n].keypoints);for(let a of s)t.push({hand:n,gesture:a.name})}}return t};var Ne={face:[],body:[],hand:[],gesture:[],object:[],persons:[],performance:{},timestamp:0,error:null},ab=0;function UN(e,t){var o,i,l,u,c,p,d,h,f,m,g,y,x,A,b,v,S,I,E,R,P,_,D,T,F,U,X;let n=le();if(!e)return{face:[],body:[],hand:[],gesture:[],object:[],persons:[],performance:{},timestamp:0,error:null};let r=Date.now()-e.timestamp,s=r<1e3?8-Math.log(r+1):1;if(e.canvas&&(Ne.canvas=e.canvas),e.error&&(Ne.error=e.error),!Ne.body||e.body.length!==Ne.body.length)Ne.body=JSON.parse(JSON.stringify(e.body));else for(let z=0;z<e.body.length;z++){let Z=e.body[z].box.map((J,se)=>((s-1)*Ne.body[z].box[se]+J)/s),W=e.body[z].boxRaw.map((J,se)=>((s-1)*Ne.body[z].boxRaw[se]+J)/s),ee=e.body[z].keypoints.map((J,se)=>{var ie,me,be,Ee,Re,ze,Be,nt,it;return{score:J.score,part:J.part,position:[Ne.body[z].keypoints[se]?((s-1)*(Ne.body[z].keypoints[se].position[0]||0)+(J.position[0]||0))/s:J.position[0],Ne.body[z].keypoints[se]?((s-1)*(Ne.body[z].keypoints[se].position[1]||0)+(J.position[1]||0))/s:J.position[1],Ne.body[z].keypoints[se]?((s-1)*(Ne.body[z].keypoints[se].position[2]||0)+(J.position[2]||0))/s:J.position[2]],positionRaw:[Ne.body[z].keypoints[se]?((s-1)*(Ne.body[z].keypoints[se].positionRaw[0]||0)+(J.positionRaw[0]||0))/s:J.positionRaw[0],Ne.body[z].keypoints[se]?((s-1)*(Ne.body[z].keypoints[se].positionRaw[1]||0)+(J.positionRaw[1]||0))/s:J.positionRaw[1],Ne.body[z].keypoints[se]?((s-1)*(Ne.body[z].keypoints[se].positionRaw[2]||0)+(J.positionRaw[2]||0))/s:J.positionRaw[2]],distance:[Ne.body[z].keypoints[se]?((s-1)*(((ie=Ne.body[z].keypoints[se].distance)==null?void 0:ie[0])||0)+(((me=J.distance)==null?void 0:me[0])||0))/s:(be=J.distance)==null?void 0:be[0],Ne.body[z].keypoints[se]?((s-1)*(((Ee=Ne.body[z].keypoints[se].distance)==null?void 0:Ee[1])||0)+(((Re=J.distance)==null?void 0:Re[1])||0))/s:(ze=J.distance)==null?void 0:ze[1],Ne.body[z].keypoints[se]?((s-1)*(((Be=Ne.body[z].keypoints[se].distance)==null?void 0:Be[2])||0)+(((nt=J.distance)==null?void 0:nt[2])||0))/s:(it=J.distance)==null?void 0:it[2]]}}),Q={},ae={connected:{}};(i=(o=t.body)==null?void 0:o.modelPath)!=null&&i.includes("efficientpose")?ae=j0:(u=(l=t.body)==null?void 0:l.modelPath)!=null&&u.includes("blazepose")?ae=W0:(p=(c=t.body)==null?void 0:c.modelPath)!=null&&p.includes("movenet")&&(ae=nh);for(let[J,se]of Object.entries(ae.connected)){let ie=[];for(let me=0;me<se.length-1;me++){let be=ee.find(Re=>Re.part===se[me]),Ee=ee.find(Re=>Re.part===se[me+1]);be&&Ee&&ie.push([be.position,Ee.position])}Q[J]=ie}Ne.body[z]={...e.body[z],box:Z,boxRaw:W,keypoints:ee,annotations:Q}}if(!Ne.hand||e.hand.length!==Ne.hand.length)Ne.hand=JSON.parse(JSON.stringify(e.hand));else for(let z=0;z<e.hand.length;z++){let Z=e.hand[z].box.map((ae,J)=>((s-1)*Ne.hand[z].box[J]+ae)/s),W=e.hand[z].boxRaw.map((ae,J)=>((s-1)*Ne.hand[z].boxRaw[J]+ae)/s);Ne.hand[z].keypoints.length!==e.hand[z].keypoints.length&&(Ne.hand[z].keypoints=e.hand[z].keypoints);let ee=e.hand[z].keypoints&&e.hand[z].keypoints.length>0?e.hand[z].keypoints.map((ae,J)=>ae.map((se,ie)=>((s-1)*(Ne.hand[z].keypoints[J][ie]||1)+(se||0))/s)):[],Q={};if(Object.keys(Ne.hand[z].annotations).length!==Object.keys(e.hand[z].annotations).length)Ne.hand[z].annotations=e.hand[z].annotations,Q=Ne.hand[z].annotations;else if(e.hand[z].annotations)for(let ae of Object.keys(e.hand[z].annotations))Q[ae]=e.hand[z].annotations[ae]&&e.hand[z].annotations[ae][0]?e.hand[z].annotations[ae].map((J,se)=>J.map((ie,me)=>((s-1)*Ne.hand[z].annotations[ae][se][me]+ie)/s)):null;Ne.hand[z]={...e.hand[z],box:Z,boxRaw:W,keypoints:ee,annotations:Q}}if(!Ne.face||e.face.length!==Ne.face.length)Ne.face=JSON.parse(JSON.stringify(e.face));else for(let z=0;z<e.face.length;z++){let Z=e.face[z].box.map((ee,Q)=>((s-1)*Ne.face[z].box[Q]+ee)/s),W=e.face[z].boxRaw.map((ee,Q)=>((s-1)*Ne.face[z].boxRaw[Q]+ee)/s);if(e.face[z].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=(d=e.face[z].rotation)==null?void 0:d.matrix,ee.angle={roll:((s-1)*(((f=(h=Ne.face[z].rotation)==null?void 0:h.angle)==null?void 0:f.roll)||0)+(((g=(m=e.face[z].rotation)==null?void 0:m.angle)==null?void 0:g.roll)||0))/s,yaw:((s-1)*(((x=(y=Ne.face[z].rotation)==null?void 0:y.angle)==null?void 0:x.yaw)||0)+(((b=(A=e.face[z].rotation)==null?void 0:A.angle)==null?void 0:b.yaw)||0))/s,pitch:((s-1)*(((S=(v=Ne.face[z].rotation)==null?void 0:v.angle)==null?void 0:S.pitch)||0)+(((E=(I=e.face[z].rotation)==null?void 0:I.angle)==null?void 0:E.pitch)||0))/s},ee.gaze={bearing:((s-1)*(((P=(R=Ne.face[z].rotation)==null?void 0:R.gaze)==null?void 0:P.bearing)||0)+(((D=(_=e.face[z].rotation)==null?void 0:_.gaze)==null?void 0:D.bearing)||0))/s,strength:((s-1)*(((F=(T=Ne.face[z].rotation)==null?void 0:T.gaze)==null?void 0:F.strength)||0)+(((X=(U=e.face[z].rotation)==null?void 0:U.gaze)==null?void 0:X.strength)||0))/s},Ne.face[z]={...e.face[z],rotation:ee,box:Z,boxRaw:W}}Ne.face[z]={...e.face[z],box:Z,boxRaw:W}}if(!Ne.object||e.object.length!==Ne.object.length)Ne.object=JSON.parse(JSON.stringify(e.object));else for(let z=0;z<e.object.length;z++){let Z=e.object[z].box.map((ee,Q)=>((s-1)*Ne.object[z].box[Q]+ee)/s),W=e.object[z].boxRaw.map((ee,Q)=>((s-1)*Ne.object[z].boxRaw[Q]+ee)/s);Ne.object[z]={...e.object[z],box:Z,boxRaw:W}}if(e.persons){let z=e.persons;if(!Ne.persons||z.length!==Ne.persons.length)Ne.persons=JSON.parse(JSON.stringify(z));else for(let Z=0;Z<z.length;Z++)Ne.persons[Z].box=z[Z].box.map((W,ee)=>((s-1)*Ne.persons[Z].box[ee]+W)/s)}e.gesture&&(Ne.gesture=e.gesture);let a=le();return ab=pe.perfadd?ab+Math.round(a-n):Math.round(a-n),e.performance&&(Ne.performance={...e.performance,interpolate:ab}),Ne}var lb={};wa(lb,{distance:()=>oh,match:()=>ib,similarity:()=>ob});function oh(e,t,n={order:2,multiplier:25}){let r=0;for(let s=0;s<e.length;s++){let a=!n.order||n.order===2?e[s]-t[s]:Math.abs(e[s]-t[s]);r+=!n.order||n.order===2?a*a:a**n.order}return(n.multiplier||20)*r}var GN=(e,t,n,r)=>{if(e===0)return 1;let s=t===2?Math.sqrt(e):e**(1/t),a=(1-s/100-n)/(r-n);return Math.max(Math.min(a,1),0)};function ob(e,t,n={order:2,multiplier:25,min:.2,max:.8}){let r=oh(e,t,n);return GN(r,n.order||2,n.min||0,n.max||1)}function ib(e,t,n={order:2,multiplier:25,threshold:0,min:.2,max:.8}){if(!Array.isArray(e)||!Array.isArray(t)||e.length<64||t.length===0||e.length!==t[0].length)return{index:-1,distance:Number.POSITIVE_INFINITY,similarity:0};let r=Number.MAX_SAFE_INTEGER,s=-1;for(let o=0;o<t.length;o++){let i=oh(e,t[o],n);if(i<r&&(r=i,s=o),r<(n.threshold||0))break}let a=GN(r,n.order||2,n.min||0,n.max||1);return{index:s,distance:r,similarity:a}}function HN(e,t,n,r,s){var i,l,u,c,p,d,h,f,m,g,y,x,A,b,v,S;let a=0,o=[];for(let I of e){let E={id:a++,face:I,body:null,hands:{left:null,right:null},gestures:[],box:[0,0,0,0]};for(let F of t)I.box[0]>F.box[0]&&I.box[0]<F.box[0]+F.box[2]&&I.box[1]+I.box[3]>F.box[1]&&I.box[1]+I.box[3]<F.box[1]+F.box[3]&&(E.body=F);if(E.body)for(let F of n)F.box[0]+F.box[2]>E.body.box[0]&&F.box[0]+F.box[2]<E.body.box[0]+E.body.box[2]&&F.box[1]+F.box[3]>E.body.box[1]&&F.box[1]+F.box[3]<E.body.box[1]+E.body.box[3]&&E.hands&&(E.hands.left=F),F.box[0]<E.body.box[0]+E.body.box[2]&&F.box[0]>E.body.box[0]&&F.box[1]+F.box[3]>E.body.box[1]&&F.box[1]+F.box[3]<E.body.box[1]+E.body.box[3]&&E.hands&&(E.hands.right=F);for(let F of r)F.face!==void 0&&F.face===I.id?(i=E.gestures)==null||i.push(F):F.iris!==void 0&&F.iris===I.id?(l=E.gestures)==null||l.push(F):F.body!==void 0&&F.body===((u=E.body)==null?void 0:u.id)?(c=E.gestures)==null||c.push(F):F.hand!==void 0&&F.hand===((d=(p=E.hands)==null?void 0:p.left)==null?void 0:d.id)?(h=E.gestures)==null||h.push(F):F.hand!==void 0&&F.hand===((m=(f=E.hands)==null?void 0:f.right)==null?void 0:m.id)&&((g=E.gestures)==null||g.push(F));let R=[],P=[],_=F=>{F&&F.length===4&&(R.push(F[0],F[0]+F[2]),P.push(F[1],F[1]+F[3]))};_((y=E.face)==null?void 0:y.box),_((x=E.body)==null?void 0:x.box),_((b=(A=E.hands)==null?void 0:A.left)==null?void 0:b.box),_((S=(v=E.hands)==null?void 0:v.right)==null?void 0:S.box);let D=Math.min(...R),T=Math.min(...P);E.box=[D,T,Math.max(...R)-D,Math.max(...P)-T],s&&s[1]&&s[2]&&(E.boxRaw=[E.box[0]/s[2],E.box[1]/s[1],E.box[2]/s[2],E.box[3]/s[1]]),o.push(E)}return o}var g2=`
|
|
/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==`,y2=`
|
|
/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 lxe(e){let t=(s,a="application/octet-stream")=>fetch(`data:${a};base64,${s}`).then(o=>o.blob()),n,r;switch(e.config.warmup){case"face":n=await t(g2);break;case"body":case"full":n=await t(y2);break;default:n=null}if(n){let s=await createImageBitmap(n);r=await e.detect(s,e.config),s.close()}return r}async function uxe(e){return new Promise(t=>{let n;switch(e.config.warmup){case"face":n="data:image/jpeg;base64,"+g2;break;case"full":case"body":n="data:image/jpeg;base64,"+y2;break;default:n=null}let r;if(typeof Image!="undefined")r=new Image;else if(pe.Image)r=new pe.Image;else return;r.onload=async()=>{let s=Jn(r.naturalWidth,r.naturalHeight);if(!s)oe("Warmup: Canvas not found"),t(void 0);else{let a=s.getContext("2d");a&&a.drawImage(r,0,0);let o=await e.image(s),i=await e.detect(o.tensor,e.config);t(i)}},n?r.src=n:t(void 0)})}async function cxe(e){let t=s=>Buffer.from(s,"base64"),n;e.config.warmup==="face"?n=t(g2):n=t(y2);let r;if("node"in Ue){let s=(void 0).decodeJpeg(n),a=s.expandDims(0);e.tf.dispose(s),r=await e.detect(a,e.config),e.tf.dispose(a)}else e.config.debug&&oe("Warmup tfjs-node not loaded");return r}async function dxe(e){let t;return typeof createImageBitmap=="function"?t=await lxe(e):typeof Image!="undefined"||pe.Canvas!==void 0?t=await uxe(e):t=await cxe(e),t}async function pxe(e){let t=qn(),n=zr();if(t!=="webgl"&&t!=="humangl"||!n||!n.checkCompileCompletion)return;Y().set("ENGINE_COMPILE_ONLY",!0);let r=sn().state.numTensors,s=[];for(let[i,l]of Object.entries(e).filter(([u,c])=>u!==null&&c!==null)){let u=l.inputs&&l.inputs[0]&&l.inputs[0].shape?[...l.inputs[0].shape]:[1,64,64,3],c=l.inputs&&l.inputs[0]&&l.inputs[0].dtype?l.inputs[0].dtype:"float32";for(let d=0;d<u.length;d++)u[d]===-1&&(u[d]=d===0?1:64);let p=Ft(u,c);try{let d=l.execute(p);s.push(i),Array.isArray(d)?d.forEach(h=>ne(h)):ne(d)}catch(d){oe("compile fail model:",i)}ne(p)}let a=await n.checkCompileCompletionAsync();n.getUniformLocations(),oe("compile pass models:",s),oe("compile pass kernels:",a.length),Y().set("ENGINE_COMPILE_ONLY",!1);let o=sn().state.numTensors;o-r>0&&oe("tensor leak:",o-r)}async function jN(e,t){let n=le();return e.state="warmup",t&&(e.config=Gt(e.config,t)),!e.config.warmup||e.config.warmup.length===0||e.config.warmup==="none"?{face:[],body:[],hand:[],gesture:[],object:[],performance:e.performance,timestamp:le(),persons:[],error:null}:new Promise(async r=>{await pxe(e.models);let s=await dxe(e),a=le();e.config.debug&&oe("warmup",e.config.warmup,Math.round(a-n),"ms"),e.emit("warmup"),r(s)})}var td,ih,lh,A2,ub=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");md(this,td,void 0);md(this,ih,void 0);md(this,lh,void 0);fe(this,"gl");fe(this,"analyze",(...t)=>{if(!fd(this,ih))return;let n=this.tf.engine().state.numTensors,r=fd(this,td);gd(this,td,n);let s=n-r;s!==0&&oe(...t,s)});md(this,A2,t=>{if(!fd(this,lh))return null;if(!t)return"input is not defined";if(this.env.node&&!(t instanceof rt))return"input must be a tensor";try{this.tf.getBackend()}catch(n){return"backend not loaded"}return null});fe(this,"similarity",ob);fe(this,"distance",oh);fe(this,"match",ib);fe(this,"emit",t=>{var n;this.events&&this.events.dispatchEvent&&((n=this.events)==null||n.dispatchEvent(new Event(t)))});this.env=pe,ka.wasmPath=Kp["tfjs-core"].includes("-")?"https://vladmandic.github.io/tfjs/dist/":`https://cdn.jsdelivr.net/npm/@tensorflow/tfjs-backend-wasm@${Ry}/dist/`,ka.modelBasePath=pe.browser?"../models/":"file://models/",ka.backend=pe.browser?"humangl":"tensorflow",this.version=F3,Object.defineProperty(this,"version",{value:F3}),this.config=JSON.parse(JSON.stringify(ka)),Object.seal(this.config),this.config.cacheModels=typeof indexedDB!="undefined",t&&(this.config=Gt(this.config,t)),v9(this.config),this.tf=Ue,this.state="idle",gd(this,td,0),gd(this,ih,!1),gd(this,lh,!1),this.performance={},this.events=typeof EventTarget!="undefined"?new EventTarget:void 0,this.models=new ah,this.draw={options:Dn,canvas:(n,r)=>eb(n,r),face:(n,r,s)=>Kc(n,r,s),body:(n,r,s)=>Zc(n,r,s),hand:(n,r,s)=>Yc(n,r,s),gesture:(n,r,s)=>Qc(n,r,s),object:(n,r,s)=>Jc(n,r,s),person:(n,r,s)=>Q5(n,r,s),all:(n,r,s)=>tb(n,r,s)},this.result={face:[],body:[],hand:[],gesture:[],object:[],performance:{},timestamp:0,persons:[],error:null},this.process={tensor:null,canvas:null},this.faceTriangulation=$T,this.faceUVMap=DT,this.gl=Et,this.emit("create")}reset(){let t=this.config.backend;this.config=JSON.parse(JSON.stringify(ka)),this.config.backend=t}validate(t){return Z1(ka,t||this.config)}now(){return le()}image(t,n=!0){return Fc(t,this.config,n)}async segmentation(t,n){return $N(t,n,this.config)}enhance(t){return x5(t)}compare(t,n){return b9(this.config,t,n)}async init(){await m2(this,!0),await this.tf.ready()}async load(t){this.state="load";let n=le(),r=Object.values(this.models).filter(o=>o).length;t&&(this.config=Gt(this.config,t)),this.env.initial&&(this.config.debug&&oe(`version: ${this.version}`),this.config.debug&&oe(`tfjs version: ${this.tf.version["tfjs-core"]}`),await m2(this)||oe("error: backend check failed"),await dc(),this.env.browser&&(this.config.debug&&oe("configuration:",this.config),this.config.debug&&oe("environment:",this.env),this.config.debug&&oe("tf flags:",this.tf.ENV.flags))),await X5(this),this.env.initial&&this.config.debug&&oe("tf engine state:",this.tf.engine().state.numBytes,"bytes",this.tf.engine().state.numTensors,"tensors"),this.env.initial=!1,Object.values(this.models).filter(o=>o).length!==r&&(await K5(this),this.emit("load"));let a=Math.trunc(le()-n);a>(this.performance.loadModels||0)&&(this.performance.loadModels=this.env.perfadd?(this.performance.loadModels||0)+a:a)}next(t=this.result){return UN(t,this.config)}async warmup(t){let n=le(),r=await jN(this,t),s=le();return this.performance.warmup=Math.trunc(s-n),r}async profile(t,n){let r=await this.tf.profile(()=>this.detect(t,n)),s={};for(let i of r.kernels)s[i.name]?s[i.name]+=i.kernelTimeMs:s[i.name]=i.kernelTimeMs;let a=[];Object.entries(s).forEach(i=>a.push({name:i[0],ms:i[1]})),a.sort((i,l)=>l.ms-i.ms),a.length=20;let o={};for(let i of a)o[i.name]=i.ms;return o}async detect(t,n){return this.state="detect",new Promise(async r=>{var g,y,x,A,b,v,S,I,E,R,P,_,D,T,F,U,X,z,Z,W,ee,Q;this.state="config";let s;this.config=Gt(this.config,n),this.state="check";let a=fd(this,A2).call(this,t);a&&(oe(a,t),this.emit("error"),r({face:[],body:[],hand:[],gesture:[],object:[],performance:this.performance,timestamp:le(),persons:[],error:a}));let o=le();await m2(this),await this.load(),s=le(),this.state="image";let i=await Fc(t,this.config);if(this.process=i,this.performance.inputProcess=this.env.perfadd?(this.performance.inputProcess||0)+Math.trunc(le()-s):Math.trunc(le()-s),this.analyze("Get Image:"),!i.tensor){this.config.debug&&oe("could not convert input to tensor"),this.emit("error"),r({face:[],body:[],hand:[],gesture:[],object:[],performance:this.performance,timestamp:le(),persons:[],error:"could not convert input to tensor"});return}this.emit("image"),s=le(),this.config.skipAllowed=await x9(this.config,i.tensor),this.performance.totalFrames||(this.performance.totalFrames=0),this.performance.cachedFrames||(this.performance.cachedFrames=0),this.performance.totalFrames++,this.config.skipAllowed&&this.performance.cachedFrames++,this.performance.cacheCheck=this.env.perfadd?(this.performance.cacheCheck||0)+Math.trunc(le()-s):Math.trunc(le()-s),this.analyze("Check Changed:");let l=[],u=[],c=[],p=[];this.state="detect:face",this.config.async?(l=this.config.face.enabled?sb(this,i.tensor):[],this.performance.face&&delete this.performance.face):(s=le(),l=this.config.face.enabled?await sb(this,i.tensor):[],this.performance.face=this.env.perfadd?(this.performance.face||0)+Math.trunc(le()-s):Math.trunc(le()-s)),this.config.async&&(this.config.body.maxDetected===-1||this.config.hand.maxDetected===-1)&&(l=await l),this.analyze("Start Body:"),this.state="detect:body";let d=this.config.body.maxDetected===-1?Gt(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?H5(i.tensor,d):[]:(y=this.config.body.modelPath)!=null&&y.includes("blazepose")?u=this.config.body.enabled?r5(i.tensor,d):[]:(x=this.config.body.modelPath)!=null&&x.includes("efficientpose")?u=this.config.body.enabled?c5(i.tensor,d):[]:(A=this.config.body.modelPath)!=null&&A.includes("movenet")&&(u=this.config.body.enabled?z5(i.tensor,d):[]),this.performance.body&&delete this.performance.body):(s=le(),(b=this.config.body.modelPath)!=null&&b.includes("posenet")?u=this.config.body.enabled?await H5(i.tensor,d):[]:(v=this.config.body.modelPath)!=null&&v.includes("blazepose")?u=this.config.body.enabled?await r5(i.tensor,d):[]:(S=this.config.body.modelPath)!=null&&S.includes("efficientpose")?u=this.config.body.enabled?await c5(i.tensor,d):[]:(I=this.config.body.modelPath)!=null&&I.includes("movenet")&&(u=this.config.body.enabled?await z5(i.tensor,d):[]),this.performance.body=this.env.perfadd?(this.performance.body||0)+Math.trunc(le()-s):Math.trunc(le()-s)),this.analyze("End Body:"),this.analyze("Start Hand:"),this.state="detect:hand";let h=this.config.hand.maxDetected===-1?Gt(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")?c=this.config.hand.enabled?C5(i.tensor,h):[]:(_=(P=this.config.hand.detector)==null?void 0:P.modelPath)!=null&&_.includes("handtrack")&&(c=this.config.hand.enabled?R5(i.tensor,h):[]),this.performance.hand&&delete this.performance.hand):(s=le(),(T=(D=this.config.hand.detector)==null?void 0:D.modelPath)!=null&&T.includes("handdetect")?c=this.config.hand.enabled?await C5(i.tensor,h):[]:(U=(F=this.config.hand.detector)==null?void 0:F.modelPath)!=null&&U.includes("handtrack")&&(c=this.config.hand.enabled?await R5(i.tensor,h):[]),this.performance.hand=this.env.perfadd?(this.performance.hand||0)+Math.trunc(le()-s):Math.trunc(le()-s)),this.analyze("End Hand:"),this.analyze("Start Object:"),this.state="detect:object",this.config.async?((X=this.config.object.modelPath)!=null&&X.includes("nanodet")?p=this.config.object.enabled?B5(i.tensor,this.config):[]:(z=this.config.object.modelPath)!=null&&z.includes("centernet")&&(p=this.config.object.enabled?o5(i.tensor,this.config):[]),this.performance.object&&delete this.performance.object):(s=le(),(Z=this.config.object.modelPath)!=null&&Z.includes("nanodet")?p=this.config.object.enabled?await B5(i.tensor,this.config):[]:(W=this.config.object.modelPath)!=null&&W.includes("centernet")&&(p=this.config.object.enabled?await o5(i.tensor,this.config):[]),this.performance.object=this.env.perfadd?(this.performance.object||0)+Math.trunc(le()-s):Math.trunc(le()-s)),this.analyze("End Object:"),this.state="detect:await",this.config.async&&([l,u,c,p]=await Promise.all([l,u,c,p])),this.state="detect:gesture";let f=[];this.config.gesture.enabled&&(s=le(),f=[...BN(l),...LN(u),...VN(c),...WN(l)],this.config.async?this.performance.gesture&&delete this.performance.gesture:this.performance.gesture=this.env.perfadd?(this.performance.gesture||0)+Math.trunc(le()-s):Math.trunc(le()-s)),this.performance.total=this.env.perfadd?(this.performance.total||0)+Math.trunc(le()-o):Math.trunc(le()-o);let m=((Q=(ee=this.process)==null?void 0:ee.tensor)==null?void 0:Q.shape)||[];this.result={face:l,body:u,hand:c,gesture:f,object:p,performance:this.performance,canvas:this.process.canvas,timestamp:Date.now(),error:null,get persons(){return HN(l,u,c,f,m)}},ne(i.tensor),this.emit("detect"),this.state="idle",r(this.result)})}};td=new WeakMap,ih=new WeakMap,lh=new WeakMap,A2=new WeakMap;return HE(fxe);})();
|
|
/**
|
|
* @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. */
|