/* Human library homepage: author: ' */ var Human=(()=>{var eR=Object.defineProperty;var Jg=e=>{if(typeof require!="undefined")return require(e);throw new Error('Dynamic require of "'+e+'" is not supported')};var Qg=(e,t)=>{for(var n in t)eR(e,n,{get:t[n],enumerable:!0})};var R3=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)};var Fn=(e,t,n)=>(R3(e,t,"read from private field"),n?n.call(e):t.get(e)),wa=(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)},Ja=(e,t,n,a)=>(R3(e,t,"write to private field"),a?a.call(e,n):t.set(e,n),n);var hwe={};Qg(hwe,{Human:()=>h$,default:()=>h$});function Mt(e,t){let n=e.endsWith("/")?"":"/",r=t.startsWith(".")||t.startsWith("/")||t.startsWith("http:")||t.startsWith("https:")||t.startsWith("file:")?`${t}`:`${e}${n}${t}`;if(!r.toLocaleLowerCase().includes(".json"))throw new Error(`Human: ModelPath Error: ${r} Expecting JSON file`);return r}function ge(...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)}var st=()=>typeof performance!="undefined"?performance.now():parseInt((Number(process.hrtime.bigint())/1e3/1e3).toString());function ia(...e){let t=n=>n&&typeof n=="object";return e.reduce((n,a)=>(Object.keys(a||{}).forEach(r=>{let s=n[r],i=a[r];Array.isArray(s)&&Array.isArray(i)?n[r]=s.concat(...i):t(s)&&t(i)?n[r]=ia(s,i):n[r]=i}),n),{})}var F3={backend:"webgl",modelBasePath:"../models/",wasmPath:"../node_modules/@tensorflow/tfjs-backend-wasm/dist/",debug:!0,async:!0,warmup:"full",cacheSensitivity:.75,skipFrame:!1,filter:{enabled:!0,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:15,skipFrames:15,minConfidence:.2,iouThreshold:.1,return:!1},mesh:{enabled:!0,modelPath:"facemesh.json"},iris:{enabled:!0,modelPath:"iris.json"},description:{enabled:!0,modelPath:"faceres.json",skipFrames:11,minConfidence:.1},emotion:{enabled:!0,minConfidence:.1,skipFrames:17,modelPath:"emotion.json"}},body:{enabled:!0,modelPath:"movenet-lightning.json",maxDetected:1,minConfidence:.2,skipFrames:1},hand:{enabled:!0,rotation:!0,skipFrames:18,minConfidence:.1,iouThreshold:.1,maxDetected:2,landmarks:!0,detector:{modelPath:"handdetect.json"},skeleton:{modelPath:"handskeleton.json"}},object:{enabled:!1,modelPath:"mb3-centernet.json",minConfidence:.2,iouThreshold:.4,maxDetected:10,skipFrames:19},segmentation:{enabled:!1,modelPath:"selfie.json"}};function O3(){let e,t;if(typeof navigator!="undefined"){let n=navigator.userAgent.match(/\(([^()]+)\)/g);if(n&&n[0]){let a=n[0].match(/\(([^()]+)\)/g);e=a?a[0].replace(/\(|\)/g,""):"",t=navigator.userAgent.replace(n[0],""),e[1]&&(t=t.replace(n[1],"")),t=t.replace(/ /g," ")}}else typeof process!="undefined"&&(e=`${process.platform} ${process.arch}`,t=`NodeJS ${process.version}`);return{platform:e,agent:t}}var bp={};Qg(bp,{Abs:()=>Q3,Acos:()=>ev,Acosh:()=>tv,AdadeltaOptimizer:()=>Oc,AdagradOptimizer:()=>Dc,AdamOptimizer:()=>_c,AdamaxOptimizer:()=>zc,Add:()=>oy,AddN:()=>nv,All:()=>av,Any:()=>rv,ArgMax:()=>sv,ArgMin:()=>iv,Asin:()=>ov,Asinh:()=>lv,Atan:()=>uv,Atan2:()=>hv,Atanh:()=>dv,AvgPool:()=>pv,AvgPool3D:()=>cv,AvgPool3DGrad:()=>sF,AvgPoolGrad:()=>rF,BackendWasm:()=>uM,BatchMatMul:()=>fv,BatchToSpaceND:()=>mv,Bincount:()=>gv,BroadcastTo:()=>iF,Callback:()=>PS,CallbackList:()=>NI,Cast:()=>ly,Ceil:()=>yv,ClipByValue:()=>Av,Complex:()=>xv,ComplexAbs:()=>bv,Concat:()=>vv,Conv2D:()=>wv,Conv2DBackpropFilter:()=>kv,Conv2DBackpropInput:()=>Iv,Conv3D:()=>Sv,Conv3DBackpropFilterV2:()=>oF,Conv3DBackpropInputV2:()=>Nv,Cos:()=>Tv,Cosh:()=>Ev,CropAndResize:()=>Mv,Cumsum:()=>Cv,CustomCallback:()=>EI,DataStorage:()=>zR,DenseBincount:()=>$v,DepthToSpace:()=>Rv,DepthwiseConv2dNative:()=>Fv,DepthwiseConv2dNativeBackpropFilter:()=>Ov,DepthwiseConv2dNativeBackpropInput:()=>Dv,Diag:()=>_v,Dilation2D:()=>zv,Dilation2DBackpropFilter:()=>uF,Dilation2DBackpropInput:()=>lF,ENV:()=>ka,EarlyStopping:()=>WS,Einsum:()=>Lv,Elu:()=>Wv,EluGrad:()=>dF,Environment:()=>Y3,Equal:()=>Vv,Erf:()=>Bv,Exp:()=>Uv,ExpandDims:()=>jv,Expm1:()=>Hv,FFT:()=>Gv,Fill:()=>qv,FlipLeftRight:()=>Kv,Floor:()=>Xv,FloorDiv:()=>Zv,FromPixels:()=>hy,FusedBatchNorm:()=>Yv,FusedConv2D:()=>cy,FusedDepthwiseConv2D:()=>fy,GPGPUContext:()=>W0,GatherNd:()=>Qv,GatherV2:()=>Jv,GraphModel:()=>A9,Greater:()=>ew,GreaterEqual:()=>tw,History:()=>TI,IFFT:()=>nw,Identity:()=>uy,Imag:()=>aw,InputSpec:()=>tn,IsFinite:()=>rw,IsInf:()=>sw,IsNan:()=>iw,KernelBackend:()=>L3,LRN:()=>gw,LRNGrad:()=>pF,LayerVariable:()=>vI,LayersModel:()=>ps,LeakyRelu:()=>ow,Less:()=>lw,LessEqual:()=>uw,LinSpace:()=>dw,Log:()=>hw,Log1p:()=>pw,LogSoftmax:()=>hF,LogicalAnd:()=>cw,LogicalNot:()=>fw,LogicalOr:()=>mw,MathBackendCPU:()=>M5,MathBackendWebGL:()=>hp,Max:()=>yw,MaxPool:()=>xw,MaxPool3D:()=>bw,MaxPool3DGrad:()=>fF,MaxPoolGrad:()=>cF,MaxPoolWithArgmax:()=>vw,Maximum:()=>Aw,Mean:()=>ww,Min:()=>kw,Minimum:()=>Iw,MirrorPad:()=>Sw,Mod:()=>Nw,MomentumOptimizer:()=>Pc,Multinomial:()=>Tw,Multiply:()=>Ew,Neg:()=>Cw,NonMaxSuppressionV3:()=>$w,NonMaxSuppressionV4:()=>Rw,NonMaxSuppressionV5:()=>Fw,NotEqual:()=>Mw,OP_SCOPE_SUFFIX:()=>Z7,OneHot:()=>Dw,OnesLike:()=>Ow,Optimizer:()=>Rs,Pack:()=>_w,PadV2:()=>zw,Pool:()=>mF,Pow:()=>Pw,Prelu:()=>Lw,Prod:()=>Ww,RMSPropOptimizer:()=>Lc,RNN:()=>cs,Range:()=>Bw,Rank:()=>xy,Real:()=>Vw,RealDiv:()=>Pv,Reciprocal:()=>Uw,Reduction:()=>_n,Relu:()=>jw,Relu6:()=>Kw,Reshape:()=>Hw,ResizeBilinear:()=>qw,ResizeBilinearGrad:()=>yF,ResizeNearestNeighbor:()=>Gw,ResizeNearestNeighborGrad:()=>gF,Reverse:()=>Xw,RotateWithOffset:()=>F7,Round:()=>Zw,Rsqrt:()=>Yw,SGDOptimizer:()=>md,ScatterNd:()=>Jw,Select:()=>Qw,Selu:()=>e7,Sequential:()=>c0,Sigmoid:()=>s7,Sign:()=>r7,Sin:()=>n7,Sinh:()=>a7,Slice:()=>t7,Softmax:()=>h7,Softplus:()=>i7,SpaceToBatchND:()=>u7,SparseFillEmptyRows:()=>p7,SparseReshape:()=>c7,SparseSegmentMean:()=>f7,SparseSegmentSum:()=>m7,SparseToDense:()=>g7,SplitV:()=>d7,Sqrt:()=>o7,Square:()=>AF,SquaredDifference:()=>y7,Step:()=>R7,StridedSlice:()=>A7,StringNGrams:()=>x7,StringSplit:()=>b7,StringToHashBucketFast:()=>v7,Sub:()=>w7,Sum:()=>l7,SymbolicTensor:()=>pr,Tan:()=>k7,Tanh:()=>I7,Tensor:()=>St,TensorBuffer:()=>uc,Tile:()=>dy,TopK:()=>S7,Transform:()=>N7,Transpose:()=>T7,Unique:()=>E7,Unpack:()=>C7,UnsortedSegmentSum:()=>M7,Variable:()=>ad,ZerosLike:()=>$7,_FusedMatMul:()=>py,abs:()=>Sa,acos:()=>PD,acosh:()=>WD,add:()=>De,addN:()=>Xy,all:()=>UD,any:()=>HD,argMax:()=>Zy,argMin:()=>KD,asin:()=>ZD,asinh:()=>JD,atan:()=>e_,atan2:()=>n_,atanh:()=>r_,avgPool:()=>Wk,avgPool3d:()=>f_,backend:()=>MD,backend_util:()=>C6,basicLSTMCell:()=>b_,batchNorm:()=>Ac,batchNorm2d:()=>S_,batchNorm3d:()=>T_,batchNorm4d:()=>C_,batchToSpaceND:()=>Bk,bincount:()=>Vk,booleanMaskAsync:()=>PW,broadcastTo:()=>xc,browser:()=>Ua,buffer:()=>Zr,callbacks:()=>Rae,cast:()=>zt,ceil:()=>F_,clipByValue:()=>D_,clone:()=>Yr,complex:()=>mi,concat:()=>sn,concat1d:()=>z_,concat2d:()=>ld,concat3d:()=>W_,concat4d:()=>V_,constraints:()=>eI,conv1d:()=>H_,conv2d:()=>bc,conv2dTranspose:()=>K_,conv3d:()=>Z_,conv3dTranspose:()=>ez,copyRegisteredKernels:()=>wF,cos:()=>nz,cosh:()=>rz,cosineWindow:()=>d1,cumsum:()=>iz,customGrad:()=>Nr,data:()=>x9,denseBincount:()=>lz,deprecationWarn:()=>Ok,depthToSpace:()=>dz,depthwiseConv2d:()=>e1,deregisterOp:()=>Oae,device_util:()=>G7,diag:()=>cz,dilation2d:()=>mz,disableDeprecationWarnings:()=>xD,dispose:()=>Ve,disposeVariables:()=>bD,div:()=>Qe,divNoNan:()=>vz,dot:()=>kz,dropout:()=>YW,einsum:()=>Sz,elu:()=>Gk,enableDebugMode:()=>AD,enableProdMode:()=>yD,enclosingPowerOfTwo:()=>b6,engine:()=>vD,env:()=>ht,equal:()=>Hk,erf:()=>Ez,exp:()=>vi,expandDims:()=>Qr,expm1:()=>Rz,eye:()=>qk,fft:()=>o1,fill:()=>wc,findBackend:()=>qy,findBackendFactory:()=>CD,floor:()=>Kk,floorDiv:()=>_k,forceHalfFloat:()=>bE,fused:()=>v6,gather:()=>Xk,gatherND:()=>KW,gather_util:()=>mk,getBackend:()=>TD,getGradient:()=>my,getKernel:()=>ac,getKernelsForBackend:()=>Lo,gpgpu_util:()=>vT,grad:()=>tP,grads:()=>nP,greater:()=>kc,greaterEqual:()=>Zk,ifft:()=>Cc,imag:()=>t1,image:()=>Ye,inTopKAsync:()=>QW,initializers:()=>oI,input:()=>YI,io:()=>ok,irfft:()=>f6,isFinite:()=>Bz,isInf:()=>Uz,isNaN:()=>Hz,keep:()=>Dk,kernel_impls:()=>F6,layers:()=>AI,leakyRelu:()=>Yk,less:()=>Kz,lessEqual:()=>n1,linalg:()=>PV,linspace:()=>Zz,loadGraphModel:()=>Et,loadLayersModel:()=>Ute,localResponseNormalization:()=>Jz,log:()=>ud,log1p:()=>Jk,logSigmoid:()=>lP,logSoftmax:()=>cP,logSumExp:()=>n6,logicalAnd:()=>Sc,logicalNot:()=>a6,logicalOr:()=>r6,logicalXor:()=>IP,losses:()=>LV,matMul:()=>yt,math:()=>ck,max:()=>$s,maxPool:()=>s6,maxPool3d:()=>TP,maxPoolWithArgmax:()=>CP,maximum:()=>i6,mean:()=>Nc,memory:()=>wD,meshgrid:()=>RP,metrics:()=>DS,min:()=>r1,minimum:()=>o6,mirrorPad:()=>_P,mod:()=>PP,model:()=>Bte,models:()=>_S,moments:()=>BP,movingAverage:()=>BW,mul:()=>fe,multiRNNCell:()=>UP,multinomial:()=>HP,neg:()=>Ms,nextFrame:()=>jV,norm:()=>u1,notEqual:()=>l6,oneHot:()=>Wy,ones:()=>wi,onesLike:()=>KP,op:()=>U,outerProduct:()=>ZP,pad:()=>hd,pad1d:()=>QP,pad2d:()=>tL,pad3d:()=>aL,pad4d:()=>sL,pool:()=>dL,pow:()=>pd,prelu:()=>d6,print:()=>ik,prod:()=>fL,profile:()=>kD,rand:()=>gL,randomGamma:()=>bL,randomNormal:()=>wL,randomUniform:()=>h6,range:()=>cd,ready:()=>ND,real:()=>Tc,reciprocal:()=>NL,registerBackend:()=>Ky,registerCallbackConstructor:()=>jte,registerGradient:()=>xF,registerKernel:()=>rc,registerOp:()=>Fae,regularizers:()=>zS,relu:()=>Ec,relu6:()=>p6,removeBackend:()=>ED,reshape:()=>le,reverse:()=>ki,reverse1d:()=>$L,reverse2d:()=>FL,reverse3d:()=>DL,reverse4d:()=>zL,rfft:()=>l1,round:()=>c6,rsqrt:()=>WL,scalar:()=>dt,scatterND:()=>UW,scatter_util:()=>yk,selu:()=>VL,separableConv2d:()=>jL,sequential:()=>Vte,serialization:()=>Ck,setBackend:()=>SD,setPlatform:()=>$D,setWasmPath:()=>Eve,setWasmPaths:()=>Cve,setWebGLContext:()=>F0,setdiff1dAsync:()=>GL,shared:()=>U9,sigmoid:()=>Sr,sign:()=>KL,signal:()=>zV,sin:()=>ZL,sinh:()=>JL,slice:()=>Ze,slice1d:()=>eW,slice2d:()=>nW,slice3d:()=>rW,slice4d:()=>iW,slice_util:()=>Uy,softmax:()=>lW,softplus:()=>e6,spaceToBatchND:()=>u6,sparse:()=>WV,sparseToDense:()=>GW,spectral:()=>_V,split:()=>es,sqrt:()=>ts,square:()=>tr,squaredDifference:()=>m6,squeeze:()=>Yn,stack:()=>Ii,step:()=>g6,stridedSlice:()=>bW,string:()=>BV,sub:()=>je,sum:()=>$t,sumOutType:()=>jF,tan:()=>wW,tanh:()=>Qy,tensor:()=>er,tensor1d:()=>oa,tensor2d:()=>ns,tensor3d:()=>mc,tensor4d:()=>kW,tensor5d:()=>IW,tensor6d:()=>SW,tensor_util:()=>B7,test_util:()=>$k,tidy:()=>Ue,tile:()=>vc,time:()=>ID,topk:()=>TW,train:()=>VV,transpose:()=>fc,truncatedNormal:()=>CW,unique:()=>$W,unregisterGradient:()=>vF,unregisterKernel:()=>bF,unsortedSegmentSum:()=>FW,unstack:()=>fd,upcastType:()=>dc,util:()=>O7,valueAndGrad:()=>aP,valueAndGrads:()=>rP,variable:()=>DW,variableGrads:()=>Qk,version:()=>Rve,version_converter:()=>zre,version_core:()=>gD,version_cpu:()=>Aie,version_layers:()=>ex,version_wasm:()=>Mve,version_webgl:()=>ffe,webgl:()=>mfe,webgl_util:()=>XN,where:()=>Ho,whereAsync:()=>A6,zeros:()=>Go,zerosLike:()=>Na});var tR=Object.create,Qp=Object.defineProperty,nR=Object.getOwnPropertyDescriptor,aR=Object.getOwnPropertyNames,rR=Object.getPrototypeOf,sR=Object.prototype.hasOwnProperty,iR=e=>Qp(e,"__esModule",{value:!0}),di=e=>{if(typeof Jg!="undefined")return Jg(e);throw new Error('Dynamic require of "'+e+'" is not supported')},_t=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),$e=(e,t)=>{for(var n in t)Qp(e,n,{get:t[n],enumerable:!0})},oR=(e,t,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let a of aR(t))!sR.call(e,a)&&a!=="default"&&Qp(e,a,{get:()=>t[a],enumerable:!(n=nR(t,a))||n.enumerable});return e},qr=e=>oR(iR(Qp(e!=null?tR(rR(e)):{},"default",e&&e.__esModule&&"default"in e?{get:()=>e.default,enumerable:!0}:{value:e,enumerable:!0})),e),D3=_t((e,t)=>{t.exports=a;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(S){}function a(S,D,_){this.low=S|0,this.high=D|0,this.unsigned=!!_}a.prototype.__isLong__,Object.defineProperty(a.prototype,"__isLong__",{value:!0});function r(S){return(S&&S.__isLong__)===!0}a.isLong=r;var s={},i={};function o(S,D){var _,W,X;return D?(S>>>=0,(X=0<=S&&S<256)&&(W=i[S],W)?W:(_=u(S,(S|0)<0?-1:0,!0),X&&(i[S]=_),_)):(S|=0,(X=-128<=S&&S<128)&&(W=s[S],W)?W:(_=u(S,S<0?-1:0,!1),X&&(s[S]=_),_))}a.fromInt=o;function l(S,D){if(isNaN(S))return D?v:x;if(D){if(S<0)return v;if(S>=g)return C}else{if(S<=-y)return z;if(S+1>=y)return T}return S<0?l(-S,D).neg():u(S%f|0,S/f|0,D)}a.fromNumber=l;function u(S,D,_){return new a(S,D,_)}a.fromBits=u;var d=Math.pow;function h(S,D,_){if(S.length===0)throw Error("empty string");if(S==="NaN"||S==="Infinity"||S==="+Infinity"||S==="-Infinity")return x;if(typeof D=="number"?(_=D,D=!1):D=!!D,_=_||10,_<2||36<_)throw RangeError("radix");var W;if((W=S.indexOf("-"))>0)throw Error("interior hyphen");if(W===0)return h(S.substring(1),D,_).neg();for(var X=l(d(_,8)),q=x,Q=0;Q>>0:this.low},$.toNumber=function(){return this.unsigned?(this.high>>>0)*f+(this.low>>>0):this.high*f+(this.low>>>0)},$.toString=function(S){if(S=S||10,S<2||36>>0,ae=ie.toString(S);if(q=ee,q.isZero())return ae+Q;for(;ae.length<6;)ae="0"+ae;Q=""+ae+Q}},$.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(z)?64:this.neg().getNumBitsAbs();for(var S=this.high!=0?this.high:this.low,D=31;D>0&&(S&1<=0},$.isOdd=function(){return(this.low&1)==1},$.isEven=function(){return(this.low&1)==0},$.equals=function(S){return r(S)||(S=p(S)),this.unsigned!==S.unsigned&&this.high>>>31==1&&S.high>>>31==1?!1:this.high===S.high&&this.low===S.low},$.eq=$.equals,$.notEquals=function(S){return!this.eq(S)},$.neq=$.notEquals,$.ne=$.notEquals,$.lessThan=function(S){return this.comp(S)<0},$.lt=$.lessThan,$.lessThanOrEqual=function(S){return this.comp(S)<=0},$.lte=$.lessThanOrEqual,$.le=$.lessThanOrEqual,$.greaterThan=function(S){return this.comp(S)>0},$.gt=$.greaterThan,$.greaterThanOrEqual=function(S){return this.comp(S)>=0},$.gte=$.greaterThanOrEqual,$.ge=$.greaterThanOrEqual,$.compare=function(S){if(r(S)||(S=p(S)),this.eq(S))return 0;var D=this.isNegative(),_=S.isNegative();return D&&!_?-1:!D&&_?1:this.unsigned?S.high>>>0>this.high>>>0||S.high===this.high&&S.low>>>0>this.low>>>0?-1:1:this.sub(S).isNegative()?-1:1},$.comp=$.compare,$.negate=function(){return!this.unsigned&&this.eq(z)?z:this.not().add(b)},$.neg=$.negate,$.add=function(S){r(S)||(S=p(S));var D=this.high>>>16,_=this.high&65535,W=this.low>>>16,X=this.low&65535,q=S.high>>>16,Q=S.high&65535,ee=S.low>>>16,ie=S.low&65535,ae=0,de=0,te=0,ce=0;return ce+=X+ie,te+=ce>>>16,ce&=65535,te+=W+ee,de+=te>>>16,te&=65535,de+=_+Q,ae+=de>>>16,de&=65535,ae+=D+q,ae&=65535,u(te<<16|ce,ae<<16|de,this.unsigned)},$.subtract=function(S){return r(S)||(S=p(S)),this.add(S.neg())},$.sub=$.subtract,$.multiply=function(S){if(this.isZero())return x;if(r(S)||(S=p(S)),n){var D=n.mul(this.low,this.high,S.low,S.high);return u(D,n.get_high(),this.unsigned)}if(S.isZero())return x;if(this.eq(z))return S.isOdd()?z:x;if(S.eq(z))return this.isOdd()?z:x;if(this.isNegative())return S.isNegative()?this.neg().mul(S.neg()):this.neg().mul(S).neg();if(S.isNegative())return this.mul(S.neg()).neg();if(this.lt(A)&&S.lt(A))return l(this.toNumber()*S.toNumber(),this.unsigned);var _=this.high>>>16,W=this.high&65535,X=this.low>>>16,q=this.low&65535,Q=S.high>>>16,ee=S.high&65535,ie=S.low>>>16,ae=S.low&65535,de=0,te=0,ce=0,he=0;return he+=q*ae,ce+=he>>>16,he&=65535,ce+=X*ae,te+=ce>>>16,ce&=65535,ce+=q*ie,te+=ce>>>16,ce&=65535,te+=W*ae,de+=te>>>16,te&=65535,te+=X*ie,de+=te>>>16,te&=65535,te+=q*ee,de+=te>>>16,te&=65535,de+=_*ae+W*ie+X*ee+q*Q,de&=65535,u(ce<<16|he,de<<16|te,this.unsigned)},$.mul=$.multiply,$.divide=function(S){if(r(S)||(S=p(S)),S.isZero())throw Error("division by zero");if(n){if(!this.unsigned&&this.high===-2147483648&&S.low===-1&&S.high===-1)return this;var D=(this.unsigned?n.div_u:n.div_s)(this.low,this.high,S.low,S.high);return u(D,n.get_high(),this.unsigned)}if(this.isZero())return this.unsigned?v:x;var _,W,X;if(this.unsigned){if(S.unsigned||(S=S.toUnsigned()),S.gt(this))return v;if(S.gt(this.shru(1)))return w;X=v}else{if(this.eq(z)){if(S.eq(b)||S.eq(I))return z;if(S.eq(z))return b;var q=this.shr(1);return _=q.div(S).shl(1),_.eq(x)?S.isNegative()?b:I:(W=this.sub(S.mul(_)),X=_.add(W.div(S)),X)}else if(S.eq(z))return this.unsigned?v:x;if(this.isNegative())return S.isNegative()?this.neg().div(S.neg()):this.neg().div(S).neg();if(S.isNegative())return this.div(S.neg()).neg();X=x}for(W=this;W.gte(S);){_=Math.max(1,Math.floor(W.toNumber()/S.toNumber()));for(var Q=Math.ceil(Math.log(_)/Math.LN2),ee=Q<=48?1:d(2,Q-48),ie=l(_),ae=ie.mul(S);ae.isNegative()||ae.gt(W);)_-=ee,ie=l(_,this.unsigned),ae=ie.mul(S);ie.isZero()&&(ie=b),X=X.add(ie),W=W.sub(ae)}return X},$.div=$.divide,$.modulo=function(S){if(r(S)||(S=p(S)),n){var D=(this.unsigned?n.rem_u:n.rem_s)(this.low,this.high,S.low,S.high);return u(D,n.get_high(),this.unsigned)}return this.sub(this.div(S).mul(S))},$.mod=$.modulo,$.rem=$.modulo,$.not=function(){return u(~this.low,~this.high,this.unsigned)},$.and=function(S){return r(S)||(S=p(S)),u(this.low&S.low,this.high&S.high,this.unsigned)},$.or=function(S){return r(S)||(S=p(S)),u(this.low|S.low,this.high|S.high,this.unsigned)},$.xor=function(S){return r(S)||(S=p(S)),u(this.low^S.low,this.high^S.high,this.unsigned)},$.shiftLeft=function(S){return r(S)&&(S=S.toInt()),(S&=63)===0?this:S<32?u(this.low<>>32-S,this.unsigned):u(0,this.low<>>S|this.high<<32-S,this.high>>S,this.unsigned):u(this.high>>S-32,this.high>=0?0:-1,this.unsigned)},$.shr=$.shiftRight,$.shiftRightUnsigned=function(S){if(r(S)&&(S=S.toInt()),S&=63,S===0)return this;var D=this.high;if(S<32){var _=this.low;return u(_>>>S|D<<32-S,D>>>S,this.unsigned)}else return S===32?u(D,0,this.unsigned):u(D>>>S-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(S){return S?this.toBytesLE():this.toBytesBE()},$.toBytesLE=function(){var S=this.high,D=this.low;return[D&255,D>>>8&255,D>>>16&255,D>>>24,S&255,S>>>8&255,S>>>16&255,S>>>24]},$.toBytesBE=function(){var S=this.high,D=this.low;return[S>>>24,S>>>16&255,S>>>8&255,S&255,D>>>24,D>>>16&255,D>>>8&255,D&255]},a.fromBytes=function(S,D,_){return _?a.fromBytesLE(S,D):a.fromBytesBE(S,D)},a.fromBytesLE=function(S,D){return new a(S[0]|S[1]<<8|S[2]<<16|S[3]<<24,S[4]|S[5]<<8|S[6]<<16|S[7]<<24,D)},a.fromBytesBE=function(S,D){return new a(S[4]<<24|S[5]<<16|S[6]<<8|S[7],S[0]<<24|S[1]<<16|S[2]<<8|S[3],D)}}),_3=_t(()=>{}),lR=_t((e,t)=>{(function(n,a,r){function s(u){var d=this,h=l();d.next=function(){var p=2091639*d.s0+d.c*23283064365386963e-26;return d.s0=d.s1,d.s1=d.s2,d.s2=p-(d.c=p|0)},d.c=1,d.s0=h(" "),d.s1=h(" "),d.s2=h(" "),d.s0-=h(u),d.s0<0&&(d.s0+=1),d.s1-=h(u),d.s1<0&&(d.s1+=1),d.s2-=h(u),d.s2<0&&(d.s2+=1),h=null}function i(u,d){return d.c=u.c,d.s0=u.s0,d.s1=u.s1,d.s2=u.s2,d}function o(u,d){var h=new s(u),p=d&&d.state,c=h.next;return c.int32=function(){return h.next()*4294967296|0},c.double=function(){return c()+(c()*2097152|0)*11102230246251565e-32},c.quick=c,p&&(typeof p=="object"&&i(p,h),c.state=function(){return i(h,{})}),c}function l(){var u=4022871197,d=function(h){h=h.toString();for(var p=0;p>>0,c-=u,c*=u,u=c>>>0,c-=u,u+=c*4294967296}return(u>>>0)*23283064365386963e-26};return d}a&&a.exports?a.exports=o:r&&r.amd?r(function(){return o}):this.alea=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),uR=_t((e,t)=>{(function(n,a,r){function s(l){var u=this,d="";u.x=0,u.y=0,u.z=0,u.w=0,u.next=function(){var p=u.x^u.x<<11;return u.x=u.y,u.y=u.z,u.z=u.w,u.w^=u.w>>>19^p^p>>>8},l===(l|0)?u.x=l:d+=l;for(var h=0;h>>0)/4294967296};return p.double=function(){do var c=d.next()>>>11,m=(d.next()>>>0)/4294967296,f=(c+m)/(1<<21);while(f===0);return f},p.int32=d.next,p.quick=p,h&&(typeof h=="object"&&i(h,d),p.state=function(){return i(d,{})}),p}a&&a.exports?a.exports=o:r&&r.amd?r(function(){return o}):this.xor128=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),dR=_t((e,t)=>{(function(n,a,r){function s(l){var u=this,d="";u.next=function(){var p=u.x^u.x>>>2;return u.x=u.y,u.y=u.z,u.z=u.w,u.w=u.v,(u.d=u.d+362437|0)+(u.v=u.v^u.v<<4^(p^p<<1))|0},u.x=0,u.y=0,u.z=0,u.w=0,u.v=0,l===(l|0)?u.x=l:d+=l;for(var h=0;h>>4),u.next()}function i(l,u){return u.x=l.x,u.y=l.y,u.z=l.z,u.w=l.w,u.v=l.v,u.d=l.d,u}function o(l,u){var d=new s(l),h=u&&u.state,p=function(){return(d.next()>>>0)/4294967296};return p.double=function(){do var c=d.next()>>>11,m=(d.next()>>>0)/4294967296,f=(c+m)/(1<<21);while(f===0);return f},p.int32=d.next,p.quick=p,h&&(typeof h=="object"&&i(h,d),p.state=function(){return i(d,{})}),p}a&&a.exports?a.exports=o:r&&r.amd?r(function(){return o}):this.xorwow=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),hR=_t((e,t)=>{(function(n,a,r){function s(l){var u=this;u.next=function(){var h=u.x,p=u.i,c,m,f;return c=h[p],c^=c>>>7,m=c^c<<24,c=h[p+1&7],m^=c^c>>>10,c=h[p+3&7],m^=c^c>>>3,c=h[p+4&7],m^=c^c<<7,c=h[p+7&7],c=c^c<<13,m^=c^c<<9,h[p]=m,u.i=p+1&7,m};function d(h,p){var c,m,f=[];if(p===(p|0))m=f[0]=p;else for(p=""+p,c=0;c0;--c)h.next()}d(u,l)}function i(l,u){return u.x=l.x.slice(),u.i=l.i,u}function o(l,u){l==null&&(l=+new Date);var d=new s(l),h=u&&u.state,p=function(){return(d.next()>>>0)/4294967296};return p.double=function(){do var c=d.next()>>>11,m=(d.next()>>>0)/4294967296,f=(c+m)/(1<<21);while(f===0);return f},p.int32=d.next,p.quick=p,h&&(h.x&&i(h,d),p.state=function(){return i(d,{})}),p}a&&a.exports?a.exports=o:r&&r.amd?r(function(){return o}):this.xorshift7=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),pR=_t((e,t)=>{(function(n,a,r){function s(l){var u=this;u.next=function(){var h=u.w,p=u.X,c=u.i,m,f;return u.w=h=h+1640531527|0,f=p[c+34&127],m=p[c=c+1&127],f^=f<<13,m^=m<<17,f^=f>>>15,m^=m>>>12,f=p[c]=f^m,u.i=c,f+(h^h>>>16)|0};function d(h,p){var c,m,f,g,y,A=[],x=128;for(p===(p|0)?(m=p,p=null):(p=p+"\0",m=0,x=Math.max(x,p.length)),f=0,g=-32;g>>15,m^=m<<4,m^=m>>>13,g>=0&&(y=y+1640531527|0,c=A[g&127]^=m+y,f=c==0?f+1:0);for(f>=128&&(A[(p&&p.length||0)&127]=-1),f=127,g=4*128;g>0;--g)m=A[f+34&127],c=A[f=f+1&127],m^=m<<13,c^=c<<17,m^=m>>>15,c^=c>>>12,A[f]=m^c;h.w=y,h.X=A,h.i=f}d(u,l)}function i(l,u){return u.i=l.i,u.w=l.w,u.X=l.X.slice(),u}function o(l,u){l==null&&(l=+new Date);var d=new s(l),h=u&&u.state,p=function(){return(d.next()>>>0)/4294967296};return p.double=function(){do var c=d.next()>>>11,m=(d.next()>>>0)/4294967296,f=(c+m)/(1<<21);while(f===0);return f},p.int32=d.next,p.quick=p,h&&(h.X&&i(h,d),p.state=function(){return i(d,{})}),p}a&&a.exports?a.exports=o:r&&r.amd?r(function(){return o}):this.xor4096=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),cR=_t((e,t)=>{(function(n,a,r){function s(l){var u=this,d="";u.next=function(){var p=u.b,c=u.c,m=u.d,f=u.a;return p=p<<25^p>>>7^c,c=c-m|0,m=m<<24^m>>>8^f,f=f-p|0,u.b=p=p<<20^p>>>12^c,u.c=c=c-m|0,u.d=m<<16^c>>>16^f,u.a=f-p|0},u.a=0,u.b=0,u.c=2654435769|0,u.d=1367130551,l===Math.floor(l)?(u.a=l/4294967296|0,u.b=l|0):d+=l;for(var h=0;h>>0)/4294967296};return p.double=function(){do var c=d.next()>>>11,m=(d.next()>>>0)/4294967296,f=(c+m)/(1<<21);while(f===0);return f},p.int32=d.next,p.quick=p,h&&(typeof h=="object"&&i(h,d),p.state=function(){return i(d,{})}),p}a&&a.exports?a.exports=o:r&&r.amd?r(function(){return o}):this.tychei=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),z3=_t(()=>{}),fR=_t((e,t)=>{(function(n,a){var r=this,s=256,i=6,o=52,l="random",u=a.pow(s,i),d=a.pow(2,o),h=d*2,p=s-1,c;function m(b,w,I){var T=[];w=w==!0?{entropy:!0}:w||{};var C=A(y(w.entropy?[b,v(n)]:b==null?x():b,3),T),z=new f(T),$=function(){for(var S=z.g(i),D=u,_=0;S=h;)S/=2,D/=2,_>>>=1;return(S+_)/D};return $.int32=function(){return z.g(4)|0},$.quick=function(){return z.g(4)/4294967296},$.double=$,A(v(z.S),n),(w.pass||I||function(S,D,_,W){return W&&(W.S&&g(W,z),S.state=function(){return g(z,{})}),_?(a[l]=S,D):S})($,C,"global"in w?w.global:this==a,w.state)}a["seed"+l]=m;function f(b){var w,I=b.length,T=this,C=0,z=T.i=T.j=0,$=T.S=[];for(I||(b=[I++]);C{var n=lR(),a=uR(),r=dR(),s=hR(),i=pR(),o=cR(),l=fR();l.alea=n,l.xor128=a,l.xorwow=r,l.xorshift7=s,l.xor4096=i,l.tychei=o,t.exports=l}),mR=_t((e,t)=>{(function(n,a,r){function s(u){var d=this,h=l();d.next=function(){var p=2091639*d.s0+d.c*23283064365386963e-26;return d.s0=d.s1,d.s1=d.s2,d.s2=p-(d.c=p|0)},d.c=1,d.s0=h(" "),d.s1=h(" "),d.s2=h(" "),d.s0-=h(u),d.s0<0&&(d.s0+=1),d.s1-=h(u),d.s1<0&&(d.s1+=1),d.s2-=h(u),d.s2<0&&(d.s2+=1),h=null}function i(u,d){return d.c=u.c,d.s0=u.s0,d.s1=u.s1,d.s2=u.s2,d}function o(u,d){var h=new s(u),p=d&&d.state,c=h.next;return c.int32=function(){return h.next()*4294967296|0},c.double=function(){return c()+(c()*2097152|0)*11102230246251565e-32},c.quick=c,p&&(typeof p=="object"&&i(p,h),c.state=function(){return i(h,{})}),c}function l(){var u=4022871197,d=function(h){h=String(h);for(var p=0;p>>0,c-=u,c*=u,u=c>>>0,c-=u,u+=c*4294967296}return(u>>>0)*23283064365386963e-26};return d}a&&a.exports?a.exports=o:r&&r.amd?r(function(){return o}):this.alea=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),gR=_t((e,t)=>{(function(n,a,r){function s(l){var u=this,d="";u.x=0,u.y=0,u.z=0,u.w=0,u.next=function(){var p=u.x^u.x<<11;return u.x=u.y,u.y=u.z,u.z=u.w,u.w^=u.w>>>19^p^p>>>8},l===(l|0)?u.x=l:d+=l;for(var h=0;h>>0)/4294967296};return p.double=function(){do var c=d.next()>>>11,m=(d.next()>>>0)/4294967296,f=(c+m)/(1<<21);while(f===0);return f},p.int32=d.next,p.quick=p,h&&(typeof h=="object"&&i(h,d),p.state=function(){return i(d,{})}),p}a&&a.exports?a.exports=o:r&&r.amd?r(function(){return o}):this.xor128=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),yR=_t((e,t)=>{(function(n,a,r){function s(l){var u=this,d="";u.next=function(){var p=u.x^u.x>>>2;return u.x=u.y,u.y=u.z,u.z=u.w,u.w=u.v,(u.d=u.d+362437|0)+(u.v=u.v^u.v<<4^(p^p<<1))|0},u.x=0,u.y=0,u.z=0,u.w=0,u.v=0,l===(l|0)?u.x=l:d+=l;for(var h=0;h>>4),u.next()}function i(l,u){return u.x=l.x,u.y=l.y,u.z=l.z,u.w=l.w,u.v=l.v,u.d=l.d,u}function o(l,u){var d=new s(l),h=u&&u.state,p=function(){return(d.next()>>>0)/4294967296};return p.double=function(){do var c=d.next()>>>11,m=(d.next()>>>0)/4294967296,f=(c+m)/(1<<21);while(f===0);return f},p.int32=d.next,p.quick=p,h&&(typeof h=="object"&&i(h,d),p.state=function(){return i(d,{})}),p}a&&a.exports?a.exports=o:r&&r.amd?r(function(){return o}):this.xorwow=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),AR=_t((e,t)=>{(function(n,a,r){function s(l){var u=this;u.next=function(){var h=u.x,p=u.i,c,m,f;return c=h[p],c^=c>>>7,m=c^c<<24,c=h[p+1&7],m^=c^c>>>10,c=h[p+3&7],m^=c^c>>>3,c=h[p+4&7],m^=c^c<<7,c=h[p+7&7],c=c^c<<13,m^=c^c<<9,h[p]=m,u.i=p+1&7,m};function d(h,p){var c,m,f=[];if(p===(p|0))m=f[0]=p;else for(p=""+p,c=0;c0;--c)h.next()}d(u,l)}function i(l,u){return u.x=l.x.slice(),u.i=l.i,u}function o(l,u){l==null&&(l=+new Date);var d=new s(l),h=u&&u.state,p=function(){return(d.next()>>>0)/4294967296};return p.double=function(){do var c=d.next()>>>11,m=(d.next()>>>0)/4294967296,f=(c+m)/(1<<21);while(f===0);return f},p.int32=d.next,p.quick=p,h&&(h.x&&i(h,d),p.state=function(){return i(d,{})}),p}a&&a.exports?a.exports=o:r&&r.amd?r(function(){return o}):this.xorshift7=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),xR=_t((e,t)=>{(function(n,a,r){function s(l){var u=this;u.next=function(){var h=u.w,p=u.X,c=u.i,m,f;return u.w=h=h+1640531527|0,f=p[c+34&127],m=p[c=c+1&127],f^=f<<13,m^=m<<17,f^=f>>>15,m^=m>>>12,f=p[c]=f^m,u.i=c,f+(h^h>>>16)|0};function d(h,p){var c,m,f,g,y,A=[],x=128;for(p===(p|0)?(m=p,p=null):(p=p+"\0",m=0,x=Math.max(x,p.length)),f=0,g=-32;g>>15,m^=m<<4,m^=m>>>13,g>=0&&(y=y+1640531527|0,c=A[g&127]^=m+y,f=c==0?f+1:0);for(f>=128&&(A[(p&&p.length||0)&127]=-1),f=127,g=4*128;g>0;--g)m=A[f+34&127],c=A[f=f+1&127],m^=m<<13,c^=c<<17,m^=m>>>15,c^=c>>>12,A[f]=m^c;h.w=y,h.X=A,h.i=f}d(u,l)}function i(l,u){return u.i=l.i,u.w=l.w,u.X=l.X.slice(),u}function o(l,u){l==null&&(l=+new Date);var d=new s(l),h=u&&u.state,p=function(){return(d.next()>>>0)/4294967296};return p.double=function(){do var c=d.next()>>>11,m=(d.next()>>>0)/4294967296,f=(c+m)/(1<<21);while(f===0);return f},p.int32=d.next,p.quick=p,h&&(h.X&&i(h,d),p.state=function(){return i(d,{})}),p}a&&a.exports?a.exports=o:r&&r.amd?r(function(){return o}):this.xor4096=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),bR=_t((e,t)=>{(function(n,a,r){function s(l){var u=this,d="";u.next=function(){var p=u.b,c=u.c,m=u.d,f=u.a;return p=p<<25^p>>>7^c,c=c-m|0,m=m<<24^m>>>8^f,f=f-p|0,u.b=p=p<<20^p>>>12^c,u.c=c=c-m|0,u.d=m<<16^c>>>16^f,u.a=f-p|0},u.a=0,u.b=0,u.c=2654435769|0,u.d=1367130551,l===Math.floor(l)?(u.a=l/4294967296|0,u.b=l|0):d+=l;for(var h=0;h>>0)/4294967296};return p.double=function(){do var c=d.next()>>>11,m=(d.next()>>>0)/4294967296,f=(c+m)/(1<<21);while(f===0);return f},p.int32=d.next,p.quick=p,h&&(typeof h=="object"&&i(h,d),p.state=function(){return i(d,{})}),p}a&&a.exports?a.exports=o:r&&r.amd?r(function(){return o}):this.tychei=o})(e,typeof t=="object"&&t,typeof define=="function"&&define)}),vR=_t((e,t)=>{(function(n,a,r){var s=256,i=6,o=52,l="random",u=r.pow(s,i),d=r.pow(2,o),h=d*2,p=s-1,c;function m(b,w,I){var T=[];w=w==!0?{entropy:!0}:w||{};var C=A(y(w.entropy?[b,v(a)]:b==null?x():b,3),T),z=new f(T),$=function(){for(var S=z.g(i),D=u,_=0;S=h;)S/=2,D/=2,_>>>=1;return(S+_)/D};return $.int32=function(){return z.g(4)|0},$.quick=function(){return z.g(4)/4294967296},$.double=$,A(v(z.S),a),(w.pass||I||function(S,D,_,W){return W&&(W.S&&g(W,z),S.state=function(){return g(z,{})}),_?(r[l]=S,D):S})($,C,"global"in w?w.global:this==r,w.state)}function f(b){var w,I=b.length,T=this,C=0,z=T.i=T.j=0,$=T.S=[];for(I||(b=[I++]);C{var n=mR(),a=gR(),r=yR(),s=AR(),i=xR(),o=bR(),l=vR();l.alea=n,l.xor128=a,l.xorwow=r,l.xorshift7=s,l.xor4096=i,l.tychei=o,t.exports=l}),wR=_t(()=>{}),Gu=_t(()=>{}),kR=_t(()=>{}),IR=_t(()=>{}),SR=_t((e,t)=>{var n=function(){var a=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(a=a||__filename),function(r){r=r||{};function s(){return te.buffer!=Je&&wn(te.buffer),Hn}function i(){return te.buffer!=Je&&wn(te.buffer),Bt}function o(){return te.buffer!=Je&&wn(te.buffer),Gn}function l(){return te.buffer!=Je&&wn(te.buffer),ba}function u(){return te.buffer!=Je&&wn(te.buffer),Rn}var d=typeof r!="undefined"?r:{},h,p;d.ready=new Promise(function(E,R){h=E,p=R});var c={},m;for(m in d)d.hasOwnProperty(m)&&(c[m]=d[m]);var f=[],g="./this.program",y=function(E,R){throw R},A=!1,x=!1,v=!1,b=!1;A=typeof window=="object",x=typeof importScripts=="function",v=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",b=!A&&!v&&!x;var w=d.ENVIRONMENT_IS_PTHREAD||!1;w&&(Je=d.buffer);var I="";function T(E){return d.locateFile?d.locateFile(E,I):I+E}var C,z,$,S,D,_;if(v){x?I=Gu().dirname(I)+"/":I=__dirname+"/",C=function(E,R){return D||(D=di("fs")),_||(_=Gu()),E=_.normalize(E),D.readFileSync(E,R?null:"utf8")},$=function(E){var R=C(E,!0);return R.buffer||(R=new Uint8Array(R)),xe(R.buffer),R},process.argv.length>1&&(g=process.argv[1].replace(/\\/g,"/")),f=process.argv.slice(2),process.on("uncaughtException",function(E){if(!(E instanceof Hu))throw E}),process.on("unhandledRejection",jr),y=function(E){process.exit(E)},d.inspect=function(){return"[Emscripten Module object]"};var W;try{W=kR()}catch(E){throw console.error('The "worker_threads" module is not supported in this node.js build - perhaps a newer version is needed?'),E}global.Worker=W.Worker}else b?(typeof read!="undefined"&&(C=function(E){return read(E)}),$=function(E){var R;return typeof readbuffer=="function"?new Uint8Array(readbuffer(E)):(R=read(E,"binary"),xe(typeof R=="object"),R)},typeof scriptArgs!="undefined"?f=scriptArgs:typeof arguments!="undefined"&&(f=arguments),typeof quit=="function"&&(y=function(E){quit(E)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(A||x)&&(x?I=self.location.href:typeof document!="undefined"&&document.currentScript&&(I=document.currentScript.src),typeof a!="undefined"&&a&&(I=a),I.indexOf("blob:")!==0?I=I.substr(0,I.lastIndexOf("/")+1):I="",v?(C=function(E,R){return D||(D=di("fs")),_||(_=Gu()),E=_.normalize(E),D.readFileSync(E,R?null:"utf8")},$=function(E){var R=C(E,!0);return R.buffer||(R=new Uint8Array(R)),xe(R.buffer),R}):(C=function(E){var R=new XMLHttpRequest;return R.open("GET",E,!1),R.send(null),R.responseText},x&&($=function(E){var R=new XMLHttpRequest;return R.open("GET",E,!1),R.responseType="arraybuffer",R.send(null),new Uint8Array(R.response)}),z=function(E,R,H){var J=new XMLHttpRequest;J.open("GET",E,!0),J.responseType="arraybuffer",J.onload=function(){if(J.status==200||J.status==0&&J.response){R(J.response);return}H()},J.onerror=H,J.send(null)}),S=function(E){document.title=E});v&&typeof performance=="undefined"&&(global.performance=IR().performance);var X=d.print||console.log.bind(console),q=d.printErr||console.warn.bind(console);for(m in c)c.hasOwnProperty(m)&&(d[m]=c[m]);c=null,d.arguments&&(f=d.arguments),d.thisProgram&&(g=d.thisProgram),d.quit&&(y=d.quit);var Q=Atomics.load,ee=Atomics.store,ie=Atomics.compareExchange,ae;d.wasmBinary&&(ae=d.wasmBinary);var de=d.noExitRuntime||!0;typeof WebAssembly!="object"&&jr("no native wasm support detected");var te,ce,he=!1,ve;function xe(E,R){E||jr("Assertion failed: "+R)}function Ee(E){var R=d["_"+E];return xe(R,"Cannot call unknown function "+E+", make sure it is exported"),R}function Fe(E,R,H,J,Ae){var me={string:function(Xn){var Do=0;if(Xn!=null&&Xn!==0){var $3=(Xn.length<<2)+1;Do=Ro($3),mt(Xn,Do,$3)}return Do},array:function(Xn){var Do=Ro(Xn.length);return lt(Xn,Do),Do}};function ye(Xn){return R==="string"?Be(Xn):R==="boolean"?Boolean(Xn):Xn}var Ie=Ee(E),gt=[],cn=0;if(J)for(var rn=0;rn=J);){var me=E[R++];if(!me)return Ae;if(!(me&128)){Ae+=String.fromCharCode(me);continue}var ye=E[R++]&63;if((me&224)==192){Ae+=String.fromCharCode((me&31)<<6|ye);continue}var Ie=E[R++]&63;if((me&240)==224?me=(me&15)<<12|ye<<6|Ie:me=(me&7)<<18|ye<<12|Ie<<6|E[R++]&63,me<65536)Ae+=String.fromCharCode(me);else{var gt=me-65536;Ae+=String.fromCharCode(55296|gt>>10,56320|gt&1023)}}return Ae}function Be(E,R){return E?qe(i(),E,R):""}function ft(E,R,H,J){if(!(J>0))return 0;for(var Ae=H,me=H+J-1,ye=0;ye=55296&&Ie<=57343){var gt=E.charCodeAt(++ye);Ie=65536+((Ie&1023)<<10)|gt&1023}if(Ie<=127){if(H>=me)break;R[H++]=Ie}else if(Ie<=2047){if(H+1>=me)break;R[H++]=192|Ie>>6,R[H++]=128|Ie&63}else if(Ie<=65535){if(H+2>=me)break;R[H++]=224|Ie>>12,R[H++]=128|Ie>>6&63,R[H++]=128|Ie&63}else{if(H+3>=me)break;R[H++]=240|Ie>>18,R[H++]=128|Ie>>12&63,R[H++]=128|Ie>>6&63,R[H++]=128|Ie&63}}return R[H]=0,H-Ae}function mt(E,R,H){return ft(E,i(),R,H)}function bt(E){for(var R=0,H=0;H=55296&&J<=57343&&(J=65536+((J&1023)<<10)|E.charCodeAt(++H)&1023),J<=127?++R:J<=2047?R+=2:J<=65535?R+=3:R+=4}return R}function lt(E,R){s().set(E,R)}function Ct(E,R){return E%R>0&&(E+=R-E%R),E}var Je,Hn,Bt,xa,vn,Gn,ba,sa,Rn;function wn(E){Je=E,d.HEAP8=Hn=new Int8Array(E),d.HEAP16=xa=new Int16Array(E),d.HEAP32=Gn=new Int32Array(E),d.HEAPU8=Bt=new Uint8Array(E),d.HEAPU16=vn=new Uint16Array(E),d.HEAPU32=ba=new Uint32Array(E),d.HEAPF32=sa=new Float32Array(E),d.HEAPF64=Rn=new Float64Array(E)}var vr=d.INITIAL_MEMORY||16777216;if(w)te=d.wasmMemory,Je=d.buffer;else if(d.wasmMemory)te=d.wasmMemory;else if(te=new WebAssembly.Memory({initial:vr/65536,maximum:2147483648/65536,shared:!0}),!(te.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"),v&&console.log("(on node you may need: --experimental-wasm-threads --experimental-wasm-bulk-memory and also use a recent version)"),Error("bad memory");te&&(Je=te.buffer),vr=Je.byteLength,wn(Je);var Wa,Ba=[],ys=[],Vr=[],As=[],So=[],wr=!1,$p=!1;w||ys.push({func:function(){Gp()}});function Em(){if(!w){if(d.preRun)for(typeof d.preRun=="function"&&(d.preRun=[d.preRun]);d.preRun.length;)Fp(d.preRun.shift());To(Ba)}}function Du(){wr=!0,!w&&To(ys)}function Cm(){w||To(Vr)}function Rp(){w||($p=!0)}function qn(){if(!w){if(d.postRun)for(typeof d.postRun=="function"&&(d.postRun=[d.postRun]);d.postRun.length;)Mm(d.postRun.shift());To(So)}}function Fp(E){Ba.unshift(E)}function Mm(E){So.unshift(E)}var Ur=0,xs=null,oi=null;function $m(E){xe(!w,"addRunDependency cannot be used in a pthread worker"),Ur++,d.monitorRunDependencies&&d.monitorRunDependencies(Ur)}function Rm(E){if(Ur--,d.monitorRunDependencies&&d.monitorRunDependencies(Ur),Ur==0&&(xs!==null&&(clearInterval(xs),xs=null),oi)){var R=oi;oi=null,R()}}d.preloadedImages={},d.preloadedAudios={};function jr(E){d.onAbort&&d.onAbort(E),w&&console.error("Pthread aborting at "+new Error().stack),E+="",q(E),he=!0,ve=1,E="abort("+E+"). Build with -s ASSERTIONS=1 for more info.";var R=new WebAssembly.RuntimeError(E);throw p(R),R}function Op(E,R){return String.prototype.startsWith?E.startsWith(R):E.indexOf(R)===0}var No="data:application/octet-stream;base64,";function Dp(E){return Op(E,No)}var Fm="file://";function _p(E){return Op(E,Fm)}var Kn="tfjs-backend-wasm-threaded-simd.wasm";Dp(Kn)||(Kn=T(Kn));function zp(E){try{if(E==Kn&&ae)return new Uint8Array(ae);if($)return $(E);throw"both async and sync fetching of the wasm failed"}catch(R){jr(R)}}function Om(){if(!ae&&(A||x)){if(typeof fetch=="function"&&!_p(Kn))return fetch(Kn,{credentials:"same-origin"}).then(function(E){if(!E.ok)throw"failed to load wasm binary file at '"+Kn+"'";return E.arrayBuffer()}).catch(function(){return zp(Kn)});if(z)return new Promise(function(E,R){z(Kn,function(H){E(new Uint8Array(H))},R)})}return Promise.resolve().then(function(){return zp(Kn)})}function Dm(){var E={a:Sg};function R(ye,Ie){var gt=ye.exports;if(d.asm=gt,Wa=d.asm.F,ce=Ie,!w){var cn=Te.unusedWorkers.length;Te.unusedWorkers.forEach(function(rn){Te.loadWasmModuleToWorker(rn,function(){--cn||Rm("wasm-instantiate")})})}}w||$m("wasm-instantiate");function H(ye){R(ye.instance,ye.module)}function J(ye){return Om().then(function(Ie){return WebAssembly.instantiate(Ie,E)}).then(ye,function(Ie){q("failed to asynchronously prepare wasm: "+Ie),jr(Ie)})}function Ae(){return!ae&&typeof WebAssembly.instantiateStreaming=="function"&&!Dp(Kn)&&!_p(Kn)&&typeof fetch=="function"?fetch(Kn,{credentials:"same-origin"}).then(function(ye){var Ie=WebAssembly.instantiateStreaming(ye,E);return Ie.then(H,function(gt){return q("wasm streaming compile failed: "+gt),q("falling back to ArrayBuffer instantiation"),J(H)})}):J(H)}if(d.instantiateWasm)try{var me=d.instantiateWasm(E,R);return me}catch(ye){return q("Module.instantiateWasm callback failed with error: "+ye),!1}return Ae().catch(p),{}}var _m={9816:function(){throw"Canceled!"},9834:function(E,R){setTimeout(function(){S3(E,R)},0)}};function Pp(){Te.initRuntime()}function To(E){for(;E.length>0;){var R=E.shift();if(typeof R=="function"){R(d);continue}var H=R.func;typeof H=="number"?R.arg===void 0?Wa.get(H)():Wa.get(H)(R.arg):H(R.arg===void 0?null:R.arg)}}function _u(E,R){if(E<=0||E>s().length||E&!0||R<0)return-28;if(R==0)return 0;R>=2147483647&&(R=Infinity);var H=Atomics.load(o(),Fo>>2),J=0;if(H==E){var Ae=Atomics.compareExchange(o(),Fo>>2,H,0);if(Ae==H&&(--R,J=1,R<=0))return 1}var me=Atomics.notify(o(),E>>2,R);if(me>=0)return me+J;throw"Atomics.notify returned an unexpected value "+me}d._emscripten_futex_wake=_u;function zm(E){if(w)throw"Internal Error! killThread() can only ever be called from main application thread!";if(!E)throw"Internal Error! Null pthread_ptr in killThread!";o()[E+12>>2]=0;var R=Te.pthreads[E];R.worker.terminate(),Te.freeThreadData(R),Te.runningWorkers.splice(Te.runningWorkers.indexOf(R.worker),1),R.worker.pthread=void 0}function Pm(E){if(w)throw"Internal Error! cancelThread() can only ever be called from main application thread!";if(!E)throw"Internal Error! Null pthread_ptr in cancelThread!";var R=Te.pthreads[E];R.worker.postMessage({cmd:"cancel"})}function Lm(E){if(w)throw"Internal Error! cleanupThread() can only ever be called from main application thread!";if(!E)throw"Internal Error! Null pthread_ptr in cleanupThread!";var R=Te.pthreads[E];if(R){o()[E+12>>2]=0;var H=R.worker;Te.returnWorkerToPool(H)}}var Te={unusedWorkers:[],runningWorkers:[],initMainThreadBlock:function(){for(var E=Math.min(4,Math.max(1,(navigator.hardwareConcurrency||1)/2)),R=0;R>2]=E;var H=E+152;o()[H>>2]=H;for(var J=ui(512),R=0;R<128;++R)l()[J/4+R]=0;Atomics.store(l(),E+100>>2,J),Atomics.store(l(),E+40>>2,E),Zg(E,!x,1),I3(E)},initWorker:function(){},pthreads:{},threadExitHandlers:[],setThreadStatus:function(){},runExitHandlers:function(){for(;Te.threadExitHandlers.length>0;)Te.threadExitHandlers.pop()();w&&Mo()&&k3()},runExitHandlersAndDeinitThread:function(E,R){Atomics.store(l(),E+56>>2,1),Atomics.store(l(),E+60>>2,0),Te.runExitHandlers(),Atomics.store(l(),E+4>>2,R),Atomics.store(l(),E+0>>2,1),_u(E+0,2147483647),Zg(0,0,0)},threadExit:function(E){var R=Mo();R&&(Te.runExitHandlersAndDeinitThread(R,E),w&&postMessage({cmd:"exit"}))},threadCancel:function(){Te.runExitHandlersAndDeinitThread(Mo(),-1),postMessage({cmd:"cancelDone"})},terminateAllThreads:function(){for(var E in Te.pthreads){var R=Te.pthreads[E];R&&R.worker&&Te.returnWorkerToPool(R.worker)}Te.pthreads={};for(var H=0;H>2];o()[E.threadInfoStruct+100>>2]=0,Uu(R),Uu(E.threadInfoStruct)}E.threadInfoStruct=0,E.allocatedOwnStack&&E.stackBase&&Uu(E.stackBase),E.stackBase=0,E.worker&&(E.worker.pthread=null)}},returnWorkerToPool:function(E){Te.runWithoutMainThreadQueuedCalls(function(){delete Te.pthreads[E.pthread.threadInfoStruct],Te.unusedWorkers.push(E),Te.runningWorkers.splice(Te.runningWorkers.indexOf(E),1),Te.freeThreadData(E.pthread),E.pthread=void 0})},runWithoutMainThreadQueuedCalls:function(E){o()[M3>>2]=0;try{E()}finally{o()[M3>>2]=1}},receiveObjectTransfer:function(E){},loadWasmModuleToWorker:function(E,R){E.onmessage=function(H){var J=H.data,Ae=J.cmd;if(E.pthread&&(Te.currentProxiedOperationCallerThread=E.pthread.threadInfoStruct),J.targetThread&&J.targetThread!=Mo()){var me=Te.pthreads[J.targetThread];me?me.worker.postMessage(H.data,J.transferList):console.error('Internal error! Worker sent a message "'+Ae+'" to target pthread '+J.targetThread+", but that thread no longer exists!"),Te.currentProxiedOperationCallerThread=void 0;return}if(Ae==="processQueuedMainThreadWork")Kg();else if(Ae==="spawnThread")jp(H.data);else if(Ae==="cleanupThread")Lm(J.thread);else if(Ae==="killThread")zm(J.thread);else if(Ae==="cancelThread")Pm(J.thread);else if(Ae==="loaded")E.loaded=!0,R&&R(E),E.runPthread&&(E.runPthread(),delete E.runPthread);else if(Ae==="print")X("Thread "+J.threadId+": "+J.text);else if(Ae==="printErr")q("Thread "+J.threadId+": "+J.text);else if(Ae==="alert")alert("Thread "+J.threadId+": "+J.text);else if(Ae==="exit"){var ye=E.pthread&&Atomics.load(l(),E.pthread.threadInfoStruct+64>>2);ye&&Te.returnWorkerToPool(E)}else if(Ae==="exitProcess")try{Q$(J.returnCode)}catch(Ie){if(Ie instanceof Hu)return;throw Ie}else Ae==="cancelDone"?Te.returnWorkerToPool(E):Ae==="objectTransfer"?Te.receiveObjectTransfer(H.data):H.data.target==="setimmediate"?E.postMessage(H.data):q("worker sent an unknown command "+Ae);Te.currentProxiedOperationCallerThread=void 0},E.onerror=function(H){q("pthread sent an error! "+H.filename+":"+H.lineno+": "+H.message)},v&&(E.on("message",function(H){E.onmessage({data:H})}),E.on("error",function(H){E.onerror(H)}),E.on("exit",function(H){})),E.postMessage({cmd:"load",urlOrBlob:d.mainScriptUrlOrBlob||a,wasmMemory:te,wasmModule:ce})},allocateUnusedWorker:function(){var E=T("tfjs-backend-wasm-threaded-simd.worker.js");Te.unusedWorkers.push(new Worker(E))},getNewWorker:function(){return Te.unusedWorkers.length==0&&(Te.allocateUnusedWorker(),Te.loadWasmModuleToWorker(Te.unusedWorkers[0])),Te.unusedWorkers.length>0?Te.unusedWorkers.pop():null},busySpinWait:function(E){for(var R=performance.now()+E;performance.now()>2]=E,E}function Gm(E,R){if(w)return bs(1,1,E,R)}function qm(E,R){if(E==R)postMessage({cmd:"processQueuedMainThreadWork"});else if(w)postMessage({targetThread:E,cmd:"processThreadQueue"});else{var H=Te.pthreads[E],J=H&&H.worker;if(!J)return;J.postMessage({cmd:"processThreadQueue"})}return 1}function Km(){jr()}function Xm(E,R,H){var J=eg(R,H);return _m[E].apply(null,J)}function Zm(E,R){}function Ym(E,R,H){if(E<=0||E>s().length||E&!0)return-28;if(A){if(Atomics.load(o(),E>>2)!=R)return-6;for(var J=performance.now(),Ae=J+H,me=Atomics.exchange(o(),Fo>>2,E);;){if(J=performance.now(),J>Ae)return me=Atomics.exchange(o(),Fo>>2,0),-73;if(me=Atomics.exchange(o(),Fo>>2,0),me==0)break;if(Kg(),Atomics.load(o(),E>>2)!=R)return-6;me=Atomics.exchange(o(),Fo>>2,E)}return 0}else{var ye=Atomics.wait(o(),E>>2,R,H);if(ye==="timed-out")return-73;if(ye==="not-equal")return-6;if(ye==="ok")return 0;throw"Atomics.wait returned an unexpected value "+ye}}function Jm(E,R,H){i().copyWithin(E,R,R+H)}function Qm(){return v?di("os").cpus().length:navigator.hardwareConcurrency}function bs(E,R){for(var H=arguments.length-2,J=ju(),Ae=H,me=Ro(Ae*8),ye=me>>3,Ie=0;Ie>=2;H=i()[E++];){var J=H<105;J&&R&1&&R++,Pu.push(J?u()[R++>>1]:o()[R]),++R}return Pu}function tg(E,R,H){zu.length=R;for(var J=H>>3,Ae=0;Ae>>16),wn(te.buffer),1}catch(R){}}function rg(E){var R=ng();if(E<=R)return!1;var H=2147483648;if(E>H)return!1;for(var J=1;J<=4;J*=2){var Ae=R*(1+.2/J);Ae=Math.min(Ae,E+100663296);var me=Math.min(H,Ct(Math.max(E,Ae),65536)),ye=ag(me);if(ye)return!0}return!1}var Xe={inEventHandler:0,removeAllEventListeners:function(){for(var E=Xe.eventHandlers.length-1;E>=0;--E)Xe._removeHandler(E);Xe.eventHandlers=[],Xe.deferredCalls=[]},registerRemoveEventListeners:function(){Xe.removeEventListenersRegistered||(As.push(Xe.removeAllEventListeners),Xe.removeEventListenersRegistered=!0)},deferredCalls:[],deferCall:function(E,R,H){function J(ye,Ie){if(ye.length!=Ie.length)return!1;for(var gt in ye)if(ye[gt]!=Ie[gt])return!1;return!0}for(var Ae in Xe.deferredCalls){var me=Xe.deferredCalls[Ae];if(me.targetFunction==E&&J(me.argsList,H))return}Xe.deferredCalls.push({targetFunction:E,precedence:R,argsList:H}),Xe.deferredCalls.sort(function(ye,Ie){return ye.precedence>2]=H,o()[ye+4>>2]=J,o()[ye+8>>2]=Ae,Xg(0,E,637534208,R,J,ye),$o(me)},getTargetThreadForEventCallback:function(E){switch(E){case 1:return 0;case 2:return Te.currentProxiedOperationCallerThread;default:return E}},getNodeNameForTarget:function(E){return E?E==window?"#window":E==screen?"#screen":E&&E.nodeName?E.nodeName:"":""},fullscreenEnabled:function(){return document.fullscreenEnabled||document.webkitFullscreenEnabled}};function sg(E){var R=bt(E)+1,H=ui(R);return mt(E,H,R),H}function ig(E,R,H,J){var Ae=ju(),me=Ro(12),ye=0;R&&(ye=sg(R)),o()[me>>2]=ye,o()[me+4>>2]=H,o()[me+8>>2]=J,Xg(0,E,657457152,0,ye,me),$o(Ae)}function og(E,R,H,J){R=R?Be(R):"",ig(E,R,H,J)}function lg(E){return E>2?Be(E):E}var ug=[0,typeof document!="undefined"?document:0,typeof window!="undefined"?window:0];function dg(E){E=lg(E);var R=ug[E]||(typeof document!="undefined"?document.querySelector(E):void 0);return R}function Lu(E){return dg(E)}function Lp(E,R,H){var J=Lu(E);if(!J)return-4;if(J.canvasSharedPtr&&(o()[J.canvasSharedPtr>>2]=R,o()[J.canvasSharedPtr+4>>2]=H),J.offscreenCanvas||!J.controlTransferredOffscreen){J.offscreenCanvas&&(J=J.offscreenCanvas);var Ae=!1;if(J.GLctxObject&&J.GLctxObject.GLctx){var me=J.GLctxObject.GLctx.getParameter(2978);Ae=me[0]===0&&me[1]===0&&me[2]===J.width&&me[3]===J.height}J.width=R,J.height=H,Ae&&J.GLctxObject.GLctx.viewport(0,0,R,H)}else if(J.canvasSharedPtr){var ye=o()[J.canvasSharedPtr+8>>2];return og(ye,E,R,H),1}else return-4;return 0}function Wp(E,R,H){return w?bs(2,1,E,R,H):Lp(E,R,H)}function hg(E,R,H){var J=Lu(E);return J?Lp(E,R,H):Wp(E,R,H)}function pg(E){}function cg(E,R){}function fg(E){var R=E.getExtension("ANGLE_instanced_arrays");if(R)return E.vertexAttribDivisor=function(H,J){R.vertexAttribDivisorANGLE(H,J)},E.drawArraysInstanced=function(H,J,Ae,me){R.drawArraysInstancedANGLE(H,J,Ae,me)},E.drawElementsInstanced=function(H,J,Ae,me,ye){R.drawElementsInstancedANGLE(H,J,Ae,me,ye)},1}function mg(E){var R=E.getExtension("OES_vertex_array_object");if(R)return E.createVertexArray=function(){return R.createVertexArrayOES()},E.deleteVertexArray=function(H){R.deleteVertexArrayOES(H)},E.bindVertexArray=function(H){R.bindVertexArrayOES(H)},E.isVertexArray=function(H){return R.isVertexArrayOES(H)},1}function gg(E){var R=E.getExtension("WEBGL_draw_buffers");if(R)return E.drawBuffers=function(H,J){R.drawBuffersWEBGL(H,J)},1}function yg(E){return!!(E.multiDrawWebgl=E.getExtension("WEBGL_multi_draw"))}var pt={counter:1,buffers:[],programs:[],framebuffers:[],renderbuffers:[],textures:[],uniforms:[],shaders:[],vaos:[],contexts:{},offscreenCanvases:{},timerQueriesEXT:[],programInfos:{},stringCache:{},unpackAlignment:4,recordError:function(E){pt.lastError||(pt.lastError=E)},getNewId:function(E){for(var R=pt.counter++,H=E.length;H>2]:-1;Ae+=Be(o()[H+me*4>>2],ye<0?void 0:ye)}return Ae},createContext:function(E,R){var H=E.getContext("webgl",R);if(!H)return 0;var J=pt.registerContext(H,R);return J},registerContext:function(E,R){var H=ui(8);o()[H+4>>2]=Mo();var J={handle:H,attributes:R,version:R.majorVersion,GLctx:E};return E.canvas&&(E.canvas.GLctxObject=J),pt.contexts[H]=J,(typeof R.enableExtensionsByDefault=="undefined"||R.enableExtensionsByDefault)&&pt.initExtensions(J),H},makeContextCurrent:function(E){return pt.currentContext=pt.contexts[E],d.ctx=vs=pt.currentContext&&pt.currentContext.GLctx,!(E&&!vs)},getContext:function(E){return pt.contexts[E]},deleteContext:function(E){pt.currentContext===pt.contexts[E]&&(pt.currentContext=null),typeof Xe=="object"&&Xe.removeAllHandlersOnTarget(pt.contexts[E].GLctx.canvas),pt.contexts[E]&&pt.contexts[E].GLctx.canvas&&(pt.contexts[E].GLctx.canvas.GLctxObject=void 0),Uu(pt.contexts[E].handle),pt.contexts[E]=null},initExtensions:function(E){if(E||(E=pt.currentContext),!E.initExtensionsDone){E.initExtensionsDone=!0;var R=E.GLctx;fg(R),mg(R),gg(R),R.disjointTimerQueryExt=R.getExtension("EXT_disjoint_timer_query"),yg(R);var H=R.getSupportedExtensions()||[];H.forEach(function(J){J.indexOf("lose_context")<0&&J.indexOf("debug")<0&&R.getExtension(J)})}},populateUniformTable:function(E){for(var R=pt.programs[E],H=pt.programInfos[E]={uniforms:{},maxUniformLength:0,maxAttributeLength:-1,maxUniformBlockNameLength:-1},J=H.uniforms,Ae=vs.getProgramParameter(R,35718),me=0;me>2,J=o()[H+(24>>2)],Ae={alpha:!!o()[H+(0>>2)],depth:!!o()[H+(4>>2)],stencil:!!o()[H+(8>>2)],antialias:!!o()[H+(12>>2)],premultipliedAlpha:!!o()[H+(16>>2)],preserveDrawingBuffer:!!o()[H+(20>>2)],powerPreference:Ag[J],failIfMajorPerformanceCaveat:!!o()[H+(28>>2)],majorVersion:o()[H+(32>>2)],minorVersion:o()[H+(36>>2)],enableExtensionsByDefault:o()[H+(40>>2)],explicitSwapControl:o()[H+(44>>2)],proxyContextToMainThread:o()[H+(48>>2)],renderViaOffscreenBackBuffer:o()[H+(52>>2)]},me=Lu(E);if(!me||Ae.explicitSwapControl)return 0;var ye=pt.createContext(me,Ae);return ye}function bg(E,R){return xg(E,R)}var Eo={mappings:{},buffers:[null,[],[]],printChar:function(E,R){var H=Eo.buffers[E];R===0||R===10?((E===1?X:q)(qe(H,0)),H.length=0):H.push(R)},varargs:void 0,get:function(){Eo.varargs+=4;var E=o()[Eo.varargs-4>>2];return E},getStr:function(E){var R=Be(E);return R},get64:function(E,R){return E}};function Bp(E){return w?bs(3,1,E):0}function Vp(E,R,H,J,Ae){if(w)return bs(4,1,E,R,H,J,Ae)}function Up(E,R,H,J){if(w)return bs(5,1,E,R,H,J);for(var Ae=0,me=0;me>2],Ie=o()[R+(me*8+4)>>2],gt=0;gt>2]=Ae,0}function vg(E){var R=Te.threadExitHandlers.pop();E&&R()}function wg(E,R){Te.threadExitHandlers.push(function(){Wa.get(E)(R)})}function jp(E){if(w)throw"Internal Error! spawnThread() can only ever be called from main application thread!";var R=Te.getNewWorker();if(R.pthread!==void 0)throw"Internal error!";if(!E.pthread_ptr)throw"Internal error, no pthread ptr!";Te.runningWorkers.push(R);for(var H=ui(128*4),J=0;J<128;++J)o()[H+J*4>>2]=0;var Ae=E.stackBase+E.stackSize,me=Te.pthreads[E.pthread_ptr]={worker:R,stackBase:E.stackBase,stackSize:E.stackSize,allocatedOwnStack:E.allocatedOwnStack,threadInfoStruct:E.pthread_ptr},ye=me.threadInfoStruct>>2;Atomics.store(l(),ye+(64>>2),E.detached),Atomics.store(l(),ye+(100>>2),H),Atomics.store(l(),ye+(40>>2),me.threadInfoStruct),Atomics.store(l(),ye+(80>>2),E.stackSize),Atomics.store(l(),ye+(76>>2),Ae),Atomics.store(l(),ye+(104>>2),E.stackSize),Atomics.store(l(),ye+(104+8>>2),Ae),Atomics.store(l(),ye+(104+12>>2),E.detached);var Ie=w3(),gt=Ie+40;Atomics.store(l(),ye+(172>>2),gt),R.pthread=me;var cn={cmd:"run",start_routine:E.startRoutine,arg:E.arg,threadInfoStruct:E.pthread_ptr,stackBase:E.stackBase,stackSize:E.stackSize};R.runPthread=function(){cn.time=performance.now(),R.postMessage(cn,E.transferList)},R.loaded&&(R.runPthread(),delete R.runPthread)}function kg(E,R,H,J){if(typeof SharedArrayBuffer=="undefined")return q("Current environment does not support SharedArrayBuffer, pthreads are not available!"),6;if(!E)return q("pthread_create called with a null thread pointer!"),28;var Ae=[],me=0;if(w&&(Ae.length===0||me))return N3(687865856,E,R,H,J);if(me)return me;var ye=0,Ie=0,gt=0;R&&R!=-1?(ye=o()[R>>2],ye+=81920,Ie=o()[R+8>>2],gt=o()[R+12>>2]!==0):ye=2097152;var cn=Ie==0;cn?Ie=C3(16,ye):(Ie-=ye,xe(Ie>0));for(var rn=ui(228),ks=0;ks<228>>2;++ks)l()[(rn>>2)+ks]=0;o()[E>>2]=rn,o()[rn+12>>2]=rn;var Oo=rn+152;o()[Oo>>2]=Oo;var Xn={stackBase:Ie,stackSize:ye,allocatedOwnStack:cn,detached:gt,startRoutine:H,pthread_ptr:rn,arg:J,transferList:Ae};return w?(Xn.cmd="spawnThread",postMessage(Xn,Ae)):jp(Xn),0}function Hp(E){if(w)return bs(6,1,E);switch(E){case 30:return 16384;case 85:var R=2147483648;return R/16384;case 132:case 133:case 12:case 137:case 138:case 15:case 235:case 16:case 17:case 18:case 19:case 20:case 149:case 13:case 10:case 236:case 153:case 9:case 21:case 22:case 159:case 154:case 14:case 77:case 78:case 139:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:return 200809;case 27:case 246:case 127:case 128:case 23:case 24:case 160:case 161:case 181:case 182:case 242:case 183:case 184:case 243:case 244:case 245:case 165:case 178:case 179:case 49:case 50:case 168:case 169:case 175:case 170:case 171:case 172:case 97:case 76:case 32:case 173:case 35:case 80:case 81:case 79:return-1;case 176:case 177:case 7:case 155:case 8:case 157:case 125:case 126:case 92:case 93:case 129:case 130:case 131:case 94:case 91:return 1;case 74:case 60:case 69:case 70:case 4:return 1024;case 31:case 42:case 72:return 32;case 87:case 26:case 33:return 2147483647;case 34:case 1:return 47839;case 38:case 36:return 99;case 43:case 37:return 2048;case 0:return 2097152;case 3:return 65536;case 28:return 32768;case 44:return 32767;case 75:return 16384;case 39:return 1e3;case 89:return 700;case 71:return 256;case 40:return 255;case 2:return 100;case 180:return 64;case 25:return 20;case 5:return 16;case 6:return 6;case 73:return 4;case 84:return typeof navigator=="object"&&navigator.hardwareConcurrency||1}return Hm(28),-1}w||Te.initMainThreadBlock();var vs,Ig=[null,Gm,Wp,Bp,Vp,Up,Hp],Sg={e:Um,r:jm,x:qm,b:Km,y:Xm,j:Zm,c:Ym,d:_u,f:li,p:Jm,z:Qm,u:tg,q:rg,v:hg,i:pg,t:cg,w:bg,m:Bp,n:Vp,g:Up,o:Pp,a:te||d.wasmMemory,k:vg,l:wg,h:kg,s:Hp},b3=Dm(),Gp=d.___wasm_call_ctors=function(){return(Gp=d.___wasm_call_ctors=d.asm.A).apply(null,arguments)},Ng=d._init=function(){return(Ng=d._init=d.asm.B).apply(null,arguments)},Tg=d._register_tensor=function(){return(Tg=d._register_tensor=d.asm.C).apply(null,arguments)},Eg=d._dispose_data=function(){return(Eg=d._dispose_data=d.asm.D).apply(null,arguments)},Cg=d._dispose=function(){return(Cg=d._dispose=d.asm.E).apply(null,arguments)},Mg=d._Abs=function(){return(Mg=d._Abs=d.asm.G).apply(null,arguments)},$g=d._Add=function(){return($g=d._Add=d.asm.H).apply(null,arguments)},Rg=d._AddN=function(){return(Rg=d._AddN=d.asm.I).apply(null,arguments)},Fg=d._All=function(){return(Fg=d._All=d.asm.J).apply(null,arguments)},Og=d._Any=function(){return(Og=d._Any=d.asm.K).apply(null,arguments)},Dg=d._ArgMax=function(){return(Dg=d._ArgMax=d.asm.L).apply(null,arguments)},_g=d._AvgPool=function(){return(_g=d._AvgPool=d.asm.M).apply(null,arguments)},zg=d._BatchMatMul=function(){return(zg=d._BatchMatMul=d.asm.N).apply(null,arguments)},Pg=d._Ceil=function(){return(Pg=d._Ceil=d.asm.O).apply(null,arguments)},Lg=d._ClipByValue=function(){return(Lg=d._ClipByValue=d.asm.P).apply(null,arguments)},Wg=d._Conv2D=function(){return(Wg=d._Conv2D=d.asm.Q).apply(null,arguments)},Bg=d._Conv2DBackpropInput=function(){return(Bg=d._Conv2DBackpropInput=d.asm.R).apply(null,arguments)},Vg=d._Cos=function(){return(Vg=d._Cos=d.asm.S).apply(null,arguments)},Ug=d._CropAndResize=function(){return(Ug=d._CropAndResize=d.asm.T).apply(null,arguments)},jg=d._Cumsum=function(){return(jg=d._Cumsum=d.asm.U).apply(null,arguments)},Hg=d._DepthToSpace=function(){return(Hg=d._DepthToSpace=d.asm.V).apply(null,arguments)},Gg=d._DepthwiseConv2dNative=function(){return(Gg=d._DepthwiseConv2dNative=d.asm.W).apply(null,arguments)},qp=d._Equal=function(){return(qp=d._Equal=d.asm.X).apply(null,arguments)},Kp=d._Exp=function(){return(Kp=d._Exp=d.asm.Y).apply(null,arguments)},Xp=d._FlipLeftRight=function(){return(Xp=d._FlipLeftRight=d.asm.Z).apply(null,arguments)},Wu=d._Floor=function(){return(Wu=d._Floor=d.asm._).apply(null,arguments)},Co=d._FloorDiv=function(){return(Co=d._FloorDiv=d.asm.$).apply(null,arguments)},qg=d._FusedBatchNorm=function(){return(qg=d._FusedBatchNorm=d.asm.aa).apply(null,arguments)},Bu=d._FusedConv2D=function(){return(Bu=d._FusedConv2D=d.asm.ba).apply(null,arguments)},ne=d._FusedDepthwiseConv2D=function(){return(ne=d._FusedDepthwiseConv2D=d.asm.ca).apply(null,arguments)},oe=d._Gather=function(){return(oe=d._Gather=d.asm.da).apply(null,arguments)},Oe=d._GatherNd=function(){return(Oe=d._GatherNd=d.asm.ea).apply(null,arguments)},ut=d._Greater=function(){return(ut=d._Greater=d.asm.fa).apply(null,arguments)},Ht=d._GreaterEqual=function(){return(Ht=d._GreaterEqual=d.asm.ga).apply(null,arguments)},Dt=d._LeakyRelu=function(){return(Dt=d._LeakyRelu=d.asm.ha).apply(null,arguments)},et=d._Less=function(){return(et=d._Less=d.asm.ia).apply(null,arguments)},tt=d._LessEqual=function(){return(tt=d._LessEqual=d.asm.ja).apply(null,arguments)},kn=d._Log=function(){return(kn=d._Log=d.asm.ka).apply(null,arguments)},Hr=d._LogicalAnd=function(){return(Hr=d._LogicalAnd=d.asm.la).apply(null,arguments)},Gr=d._Max=function(){return(Gr=d._Max=d.asm.ma).apply(null,arguments)},Zp=d._MaxPool=function(){return(Zp=d._MaxPool=d.asm.na).apply(null,arguments)},Vu=d._Maximum=function(){return(Vu=d._Maximum=d.asm.oa).apply(null,arguments)},va=d._Mean=function(){return(va=d._Mean=d.asm.pa).apply(null,arguments)},ws=d._Min=function(){return(ws=d._Min=d.asm.qa).apply(null,arguments)},Yp=d._Minimum=function(){return(Yp=d._Minimum=d.asm.ra).apply(null,arguments)},p$=d._MirrorPad=function(){return(p$=d._MirrorPad=d.asm.sa).apply(null,arguments)},c$=d._Multiply=function(){return(c$=d._Multiply=d.asm.ta).apply(null,arguments)},f$=d._Neg=function(){return(f$=d._Neg=d.asm.ua).apply(null,arguments)},m$=d._NonMaxSuppressionV3=function(){return(m$=d._NonMaxSuppressionV3=d.asm.va).apply(null,arguments)},g$=d._NonMaxSuppressionV4=function(){return(g$=d._NonMaxSuppressionV4=d.asm.wa).apply(null,arguments)},y$=d._NonMaxSuppressionV5=function(){return(y$=d._NonMaxSuppressionV5=d.asm.xa).apply(null,arguments)},A$=d._NotEqual=function(){return(A$=d._NotEqual=d.asm.ya).apply(null,arguments)},x$=d._OneHot=function(){return(x$=d._OneHot=d.asm.za).apply(null,arguments)},b$=d._PadV2=function(){return(b$=d._PadV2=d.asm.Aa).apply(null,arguments)},v$=d._Pow=function(){return(v$=d._Pow=d.asm.Ba).apply(null,arguments)},w$=d._Prelu=function(){return(w$=d._Prelu=d.asm.Ca).apply(null,arguments)},k$=d._Prod=function(){return(k$=d._Prod=d.asm.Da).apply(null,arguments)},I$=d._RealDiv=function(){return(I$=d._RealDiv=d.asm.Ea).apply(null,arguments)},S$=d._Relu=function(){return(S$=d._Relu=d.asm.Fa).apply(null,arguments)},N$=d._Relu6=function(){return(N$=d._Relu6=d.asm.Ga).apply(null,arguments)},T$=d._ResizeBilinear=function(){return(T$=d._ResizeBilinear=d.asm.Ha).apply(null,arguments)},E$=d._Reverse=function(){return(E$=d._Reverse=d.asm.Ia).apply(null,arguments)},C$=d._RotateWithOffset=function(){return(C$=d._RotateWithOffset=d.asm.Ja).apply(null,arguments)},M$=d._Round=function(){return(M$=d._Round=d.asm.Ka).apply(null,arguments)},$$=d._Rsqrt=function(){return($$=d._Rsqrt=d.asm.La).apply(null,arguments)},R$=d._ScatterNd=function(){return(R$=d._ScatterNd=d.asm.Ma).apply(null,arguments)},F$=d._SelectV2=function(){return(F$=d._SelectV2=d.asm.Na).apply(null,arguments)},O$=d._Sigmoid=function(){return(O$=d._Sigmoid=d.asm.Oa).apply(null,arguments)},D$=d._Sin=function(){return(D$=d._Sin=d.asm.Pa).apply(null,arguments)},_$=d._Softmax=function(){return(_$=d._Softmax=d.asm.Qa).apply(null,arguments)},z$=d._Sqrt=function(){return(z$=d._Sqrt=d.asm.Ra).apply(null,arguments)},P$=d._Square=function(){return(P$=d._Square=d.asm.Sa).apply(null,arguments)},L$=d._SquaredDifference=function(){return(L$=d._SquaredDifference=d.asm.Ta).apply(null,arguments)},W$=d._Step=function(){return(W$=d._Step=d.asm.Ua).apply(null,arguments)},B$=d._StridedSlice=function(){return(B$=d._StridedSlice=d.asm.Va).apply(null,arguments)},V$=d._Sub=function(){return(V$=d._Sub=d.asm.Wa).apply(null,arguments)},U$=d._Sum=function(){return(U$=d._Sum=d.asm.Xa).apply(null,arguments)},j$=d._Tan=function(){return(j$=d._Tan=d.asm.Ya).apply(null,arguments)},H$=d._Tanh=function(){return(H$=d._Tanh=d.asm.Za).apply(null,arguments)},G$=d._Tile=function(){return(G$=d._Tile=d.asm._a).apply(null,arguments)},q$=d._TopK=function(){return(q$=d._TopK=d.asm.$a).apply(null,arguments)},K$=d._Transform=function(){return(K$=d._Transform=d.asm.ab).apply(null,arguments)},X$=d._Transpose=function(){return(X$=d._Transpose=d.asm.bb).apply(null,arguments)},Z$=d.__FusedMatMul=function(){return(Z$=d.__FusedMatMul=d.asm.cb).apply(null,arguments)},ui=d._malloc=function(){return(ui=d._malloc=d.asm.db).apply(null,arguments)},Uu=d._free=function(){return(Uu=d._free=d.asm.eb).apply(null,arguments)},v3=d.___errno_location=function(){return(v3=d.___errno_location=d.asm.fb).apply(null,arguments)},w3=d._emscripten_get_global_libc=function(){return(w3=d._emscripten_get_global_libc=d.asm.gb).apply(null,arguments)},Mo=d._pthread_self=function(){return(Mo=d._pthread_self=d.asm.hb).apply(null,arguments)},k3=d.___pthread_tsd_run_dtors=function(){return(k3=d.___pthread_tsd_run_dtors=d.asm.ib).apply(null,arguments)},Kg=d._emscripten_main_thread_process_queued_calls=function(){return(Kg=d._emscripten_main_thread_process_queued_calls=d.asm.jb).apply(null,arguments)},Y$=d._emscripten_current_thread_process_queued_calls=function(){return(Y$=d._emscripten_current_thread_process_queued_calls=d.asm.kb).apply(null,arguments)},I3=d._emscripten_register_main_browser_thread_id=function(){return(I3=d._emscripten_register_main_browser_thread_id=d.asm.lb).apply(null,arguments)},S3=d.__emscripten_do_dispatch_to_thread=function(){return(S3=d.__emscripten_do_dispatch_to_thread=d.asm.mb).apply(null,arguments)},N3=d._emscripten_sync_run_in_main_thread_4=function(){return(N3=d._emscripten_sync_run_in_main_thread_4=d.asm.nb).apply(null,arguments)},T3=d._emscripten_run_in_main_runtime_thread_js=function(){return(T3=d._emscripten_run_in_main_runtime_thread_js=d.asm.ob).apply(null,arguments)},Xg=d.__emscripten_call_on_thread=function(){return(Xg=d.__emscripten_call_on_thread=d.asm.pb).apply(null,arguments)},J$=d._emscripten_tls_init=function(){return(J$=d._emscripten_tls_init=d.asm.qb).apply(null,arguments)},Zg=d.__emscripten_thread_init=function(){return(Zg=d.__emscripten_thread_init=d.asm.rb).apply(null,arguments)},ju=d.stackSave=function(){return(ju=d.stackSave=d.asm.sb).apply(null,arguments)},$o=d.stackRestore=function(){return($o=d.stackRestore=d.asm.tb).apply(null,arguments)},Ro=d.stackAlloc=function(){return(Ro=d.stackAlloc=d.asm.ub).apply(null,arguments)},E3=d._emscripten_stack_set_limits=function(){return(E3=d._emscripten_stack_set_limits=d.asm.vb).apply(null,arguments)},C3=d._memalign=function(){return(C3=d._memalign=d.asm.wb).apply(null,arguments)},M3=d.__emscripten_allow_main_runtime_queued_calls=9808,Fo=d.__emscripten_main_thread_futex=11432;d.cwrap=We,d.PThread=Te,d.PThread=Te,d.wasmMemory=te,d.ExitStatus=Hu;var Jp;function Hu(E){this.name="ExitStatus",this.message="Program terminated with exit("+E+")",this.status=E}oi=function E(){Jp||Yg(),Jp||(oi=E)};function Yg(E){if(E=E||f,Ur>0)return;if(w){h(d),Du(),postMessage({cmd:"loaded"});return}if(Em(),Ur>0)return;function R(){Jp||(Jp=!0,d.calledRun=!0,!he&&(Du(),Cm(),h(d),d.onRuntimeInitialized&&d.onRuntimeInitialized(),qn()))}d.setStatus?(d.setStatus("Running..."),setTimeout(function(){setTimeout(function(){d.setStatus("")},1),R()},1)):R()}d.run=Yg;function Q$(E,R){if(!(R&&de&&E===0)){if(!R&&w)throw postMessage({cmd:"exitProcess",returnCode:E}),new Hu(E);de||(Te.terminateAllThreads(),ve=E,Rp(),d.onExit&&d.onExit(E),he=!0),y(E,new Hu(E))}}if(d.preInit)for(typeof d.preInit=="function"&&(d.preInit=[d.preInit]);d.preInit.length>0;)d.preInit.pop()();return w&&(de=!1,Te.initWorker()),Yg(),r.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)}),NR=_t((e,t)=>{var n=function(){var a=typeof document!="undefined"&&document.currentScript?document.currentScript.src:void 0;return typeof __filename!="undefined"&&(a=a||__filename),function(r){r=r||{};var s=typeof r!="undefined"?r:{},i,o;s.ready=new Promise(function(ne,oe){i=ne,o=oe});var l={},u;for(u in s)s.hasOwnProperty(u)&&(l[u]=s[u]);var d=[],h="./this.program",p=function(ne,oe){throw oe},c=!1,m=!1,f=!1,g=!1;c=typeof window=="object",m=typeof importScripts=="function",f=typeof process=="object"&&typeof process.versions=="object"&&typeof process.versions.node=="string",g=!c&&!f&&!m;var y="";function A(ne){return s.locateFile?s.locateFile(ne,y):y+ne}var x,v,b,w,I,T;f?(m?y=Gu().dirname(y)+"/":y=__dirname+"/",x=function(ne,oe){return I||(I=di("fs")),T||(T=Gu()),ne=T.normalize(ne),I.readFileSync(ne,oe?null:"utf8")},b=function(ne){var oe=x(ne,!0);return oe.buffer||(oe=new Uint8Array(oe)),X(oe.buffer),oe},process.argv.length>1&&(h=process.argv[1].replace(/\\/g,"/")),d=process.argv.slice(2),process.on("uncaughtException",function(ne){if(!(ne instanceof qg))throw ne}),process.on("unhandledRejection",wr),p=function(ne){process.exit(ne)},s.inspect=function(){return"[Emscripten Module object]"}):g?(typeof read!="undefined"&&(x=function(ne){return read(ne)}),b=function(ne){var oe;return typeof readbuffer=="function"?new Uint8Array(readbuffer(ne)):(oe=read(ne,"binary"),X(typeof oe=="object"),oe)},typeof scriptArgs!="undefined"?d=scriptArgs:typeof arguments!="undefined"&&(d=arguments),typeof quit=="function"&&(p=function(ne){quit(ne)}),typeof print!="undefined"&&(typeof console=="undefined"&&(console={}),console.log=print,console.warn=console.error=typeof printErr!="undefined"?printErr:print)):(c||m)&&(m?y=self.location.href:typeof document!="undefined"&&document.currentScript&&(y=document.currentScript.src),a&&(y=a),y.indexOf("blob:")!==0?y=y.substr(0,y.lastIndexOf("/")+1):y="",x=function(ne){var oe=new XMLHttpRequest;return oe.open("GET",ne,!1),oe.send(null),oe.responseText},m&&(b=function(ne){var oe=new XMLHttpRequest;return oe.open("GET",ne,!1),oe.responseType="arraybuffer",oe.send(null),new Uint8Array(oe.response)}),v=function(ne,oe,Oe){var ut=new XMLHttpRequest;ut.open("GET",ne,!0),ut.responseType="arraybuffer",ut.onload=function(){if(ut.status==200||ut.status==0&&ut.response){oe(ut.response);return}Oe()},ut.onerror=Oe,ut.send(null)},w=function(ne){document.title=ne});var C=s.print||console.log.bind(console),z=s.printErr||console.warn.bind(console);for(u in l)l.hasOwnProperty(u)&&(s[u]=l[u]);l=null,s.arguments&&(d=s.arguments),s.thisProgram&&(h=s.thisProgram),s.quit&&(p=s.quit);var $;s.wasmBinary&&($=s.wasmBinary);var S=s.noExitRuntime||!0;typeof WebAssembly!="object"&&wr("no native wasm support detected");var D,_=!1,W;function X(ne,oe){ne||wr("Assertion failed: "+oe)}function q(ne){var oe=s["_"+ne];return X(oe,"Cannot call unknown function "+ne+", make sure it is exported"),oe}function Q(ne,oe,Oe,ut,Ht){var Dt={string:function(va){var ws=0;if(va!=null&&va!==0){var Yp=(va.length<<2)+1;ws=Wu(Yp),ce(va,ws,Yp)}return ws},array:function(va){var ws=Wu(va.length);return he(va,ws),ws}};function et(va){return oe==="string"?de(va):oe==="boolean"?Boolean(va):va}var tt=q(ne),kn=[],Hr=0;if(ut)for(var Gr=0;Gr=ut);)++Ht;if(Ht-oe>16&&ne.subarray&&ie)return ie.decode(ne.subarray(oe,Ht));for(var Dt="";oe>10,56320|Hr&1023)}}return Dt}function de(ne,oe){return ne?ae(Fe,ne,oe):""}function te(ne,oe,Oe,ut){if(!(ut>0))return 0;for(var Ht=Oe,Dt=Oe+ut-1,et=0;et=55296&&tt<=57343){var kn=ne.charCodeAt(++et);tt=65536+((tt&1023)<<10)|kn&1023}if(tt<=127){if(Oe>=Dt)break;oe[Oe++]=tt}else if(tt<=2047){if(Oe+1>=Dt)break;oe[Oe++]=192|tt>>6,oe[Oe++]=128|tt&63}else if(tt<=65535){if(Oe+2>=Dt)break;oe[Oe++]=224|tt>>12,oe[Oe++]=128|tt>>6&63,oe[Oe++]=128|tt&63}else{if(Oe+3>=Dt)break;oe[Oe++]=240|tt>>18,oe[Oe++]=128|tt>>12&63,oe[Oe++]=128|tt>>6&63,oe[Oe++]=128|tt&63}}return oe[Oe]=0,Oe-Ht}function ce(ne,oe,Oe){return te(ne,Fe,oe,Oe)}function he(ne,oe){Ee.set(ne,oe)}function ve(ne,oe){return ne%oe>0&&(ne+=oe-ne%oe),ne}var xe,Ee,Fe,We,qe,Be,ft,mt,bt;function lt(ne){xe=ne,s.HEAP8=Ee=new Int8Array(ne),s.HEAP16=We=new Int16Array(ne),s.HEAP32=Be=new Int32Array(ne),s.HEAPU8=Fe=new Uint8Array(ne),s.HEAPU16=qe=new Uint16Array(ne),s.HEAPU32=ft=new Uint32Array(ne),s.HEAPF32=mt=new Float32Array(ne),s.HEAPF64=bt=new Float64Array(ne)}var Ct=s.INITIAL_MEMORY||16777216,Je,Hn=[],Bt=[],xa=[],vn=[],Gn=!1;Bt.push({func:function(){Pp()}});function ba(){if(s.preRun)for(typeof s.preRun=="function"&&(s.preRun=[s.preRun]);s.preRun.length;)vr(s.preRun.shift());xs(Hn)}function sa(){Gn=!0,xs(Bt)}function Rn(){xs(xa)}function wn(){if(s.postRun)for(typeof s.postRun=="function"&&(s.postRun=[s.postRun]);s.postRun.length;)Wa(s.postRun.shift());xs(vn)}function vr(ne){Hn.unshift(ne)}function Wa(ne){vn.unshift(ne)}var Ba=0,ys=null,Vr=null;function As(ne){Ba++,s.monitorRunDependencies&&s.monitorRunDependencies(Ba)}function So(ne){if(Ba--,s.monitorRunDependencies&&s.monitorRunDependencies(Ba),Ba==0&&(ys!==null&&(clearInterval(ys),ys=null),Vr)){var oe=Vr;Vr=null,oe()}}s.preloadedImages={},s.preloadedAudios={};function wr(ne){s.onAbort&&s.onAbort(ne),ne+="",z(ne),_=!0,W=1,ne="abort("+ne+"). Build with -s ASSERTIONS=1 for more info.";var oe=new WebAssembly.RuntimeError(ne);throw o(oe),oe}function $p(ne,oe){return String.prototype.startsWith?ne.startsWith(oe):ne.indexOf(oe)===0}var Em="data:application/octet-stream;base64,";function Du(ne){return $p(ne,Em)}var Cm="file://";function Rp(ne){return $p(ne,Cm)}var qn="tfjs-backend-wasm.wasm";Du(qn)||(qn=A(qn));function Fp(ne){try{if(ne==qn&&$)return new Uint8Array($);if(b)return b(ne);throw"both async and sync fetching of the wasm failed"}catch(oe){wr(oe)}}function Mm(){if(!$&&(c||m)){if(typeof fetch=="function"&&!Rp(qn))return fetch(qn,{credentials:"same-origin"}).then(function(ne){if(!ne.ok)throw"failed to load wasm binary file at '"+qn+"'";return ne.arrayBuffer()}).catch(function(){return Fp(qn)});if(v)return new Promise(function(ne,oe){v(qn,function(Oe){ne(new Uint8Array(Oe))},oe)})}return Promise.resolve().then(function(){return Fp(qn)})}function Ur(){var ne={a:Dm};function oe(et,tt){var kn=et.exports;s.asm=kn,D=s.asm.i,lt(D.buffer),Je=s.asm.o,So("wasm-instantiate")}As("wasm-instantiate");function Oe(et){oe(et.instance)}function ut(et){return Mm().then(function(tt){return WebAssembly.instantiate(tt,ne)}).then(et,function(tt){z("failed to asynchronously prepare wasm: "+tt),wr(tt)})}function Ht(){return!$&&typeof WebAssembly.instantiateStreaming=="function"&&!Du(qn)&&!Rp(qn)&&typeof fetch=="function"?fetch(qn,{credentials:"same-origin"}).then(function(et){var tt=WebAssembly.instantiateStreaming(et,ne);return tt.then(Oe,function(kn){return z("wasm streaming compile failed: "+kn),z("falling back to ArrayBuffer instantiation"),ut(Oe)})}):ut(Oe)}if(s.instantiateWasm)try{var Dt=s.instantiateWasm(ne,oe);return Dt}catch(et){return z("Module.instantiateWasm callback failed with error: "+et),!1}return Ht().catch(o),{}}function xs(ne){for(;ne.length>0;){var oe=ne.shift();if(typeof oe=="function"){oe(s);continue}var Oe=oe.func;typeof Oe=="number"?oe.arg===void 0?Je.get(Oe)():Je.get(Oe)(oe.arg):Oe(oe.arg===void 0?null:oe.arg)}}function oi(){wr()}function $m(ne,oe,Oe){Fe.copyWithin(ne,oe,oe+Oe)}function Rm(){return Fe.length}function jr(ne){try{return D.grow(ne-xe.byteLength+65535>>>16),lt(D.buffer),1}catch(oe){}}function Op(ne){var oe=Rm(),Oe=2147483648;if(ne>Oe)return!1;for(var ut=1;ut<=4;ut*=2){var Ht=oe*(1+.2/ut);Ht=Math.min(Ht,ne+100663296);var Dt=Math.min(Oe,ve(Math.max(ne,Ht),65536)),et=jr(Dt);if(et)return!0}return!1}var No={mappings:{},buffers:[null,[],[]],printChar:function(ne,oe){var Oe=No.buffers[ne];oe===0||oe===10?((ne===1?C:z)(ae(Oe,0)),Oe.length=0):Oe.push(oe)},varargs:void 0,get:function(){No.varargs+=4;var ne=Be[No.varargs-4>>2];return ne},getStr:function(ne){var oe=de(ne);return oe},get64:function(ne,oe){return ne}};function Dp(ne){return 0}function Fm(ne,oe,Oe,ut,Ht){}function _p(ne,oe,Oe,ut){for(var Ht=0,Dt=0;Dt>2],tt=Be[oe+(Dt*8+4)>>2],kn=0;kn>2]=Ht,0}function Kn(){return 6}function zp(ne){return Be[qp()>>2]=ne,ne}function Om(ne){switch(ne){case 30:return 16384;case 85:var oe=2147483648;return oe/16384;case 132:case 133:case 12:case 137:case 138:case 15:case 235:case 16:case 17:case 18:case 19:case 20:case 149:case 13:case 10:case 236:case 153:case 9:case 21:case 22:case 159:case 154:case 14:case 77:case 78:case 139:case 82:case 68:case 67:case 164:case 11:case 29:case 47:case 48:case 95:case 52:case 51:case 46:return 200809;case 27:case 246:case 127:case 128:case 23:case 24:case 160:case 161:case 181:case 182:case 242:case 183:case 184:case 243:case 244:case 245:case 165:case 178:case 179:case 49:case 50:case 168:case 169:case 175:case 170:case 171:case 172:case 97:case 76:case 32:case 173:case 35:case 80:case 81:case 79:return-1;case 176:case 177:case 7:case 155:case 8:case 157:case 125:case 126:case 92:case 93:case 129:case 130:case 131:case 94:case 91:return 1;case 74:case 60:case 69:case 70:case 4:return 1024;case 31:case 42:case 72:return 32;case 87:case 26:case 33:return 2147483647;case 34:case 1:return 47839;case 38:case 36:return 99;case 43:case 37:return 2048;case 0:return 2097152;case 3:return 65536;case 28:return 32768;case 44:return 32767;case 75:return 16384;case 39:return 1e3;case 89:return 700;case 71:return 256;case 40:return 255;case 2:return 100;case 180:return 64;case 25:return 20;case 5:return 16;case 6:return 6;case 73:return 4;case 84:return typeof navigator=="object"&&navigator.hardwareConcurrency||1}return zp(28),-1}var Dm={a:oi,d:$m,e:Op,f:Dp,c:Fm,b:_p,g:Kn,h:Om},_m=Ur(),Pp=s.___wasm_call_ctors=function(){return(Pp=s.___wasm_call_ctors=s.asm.j).apply(null,arguments)},To=s._init=function(){return(To=s._init=s.asm.k).apply(null,arguments)},_u=s._register_tensor=function(){return(_u=s._register_tensor=s.asm.l).apply(null,arguments)},zm=s._dispose_data=function(){return(zm=s._dispose_data=s.asm.m).apply(null,arguments)},Pm=s._dispose=function(){return(Pm=s._dispose=s.asm.n).apply(null,arguments)},Lm=s._Abs=function(){return(Lm=s._Abs=s.asm.p).apply(null,arguments)},Te=s._Add=function(){return(Te=s._Add=s.asm.q).apply(null,arguments)},Wm=s._AddN=function(){return(Wm=s._AddN=s.asm.r).apply(null,arguments)},Bm=s._All=function(){return(Bm=s._All=s.asm.s).apply(null,arguments)},Vm=s._Any=function(){return(Vm=s._Any=s.asm.t).apply(null,arguments)},Um=s._ArgMax=function(){return(Um=s._ArgMax=s.asm.u).apply(null,arguments)},jm=s._AvgPool=function(){return(jm=s._AvgPool=s.asm.v).apply(null,arguments)},li=s._BatchMatMul=function(){return(li=s._BatchMatMul=s.asm.w).apply(null,arguments)},Hm=s._Ceil=function(){return(Hm=s._Ceil=s.asm.x).apply(null,arguments)},Gm=s._ClipByValue=function(){return(Gm=s._ClipByValue=s.asm.y).apply(null,arguments)},qm=s._Conv2D=function(){return(qm=s._Conv2D=s.asm.z).apply(null,arguments)},Km=s._Conv2DBackpropInput=function(){return(Km=s._Conv2DBackpropInput=s.asm.A).apply(null,arguments)},Xm=s._Cos=function(){return(Xm=s._Cos=s.asm.B).apply(null,arguments)},Zm=s._CropAndResize=function(){return(Zm=s._CropAndResize=s.asm.C).apply(null,arguments)},Ym=s._Cumsum=function(){return(Ym=s._Cumsum=s.asm.D).apply(null,arguments)},Jm=s._DepthToSpace=function(){return(Jm=s._DepthToSpace=s.asm.E).apply(null,arguments)},Qm=s._DepthwiseConv2dNative=function(){return(Qm=s._DepthwiseConv2dNative=s.asm.F).apply(null,arguments)},bs=s._Equal=function(){return(bs=s._Equal=s.asm.G).apply(null,arguments)},zu=s._Exp=function(){return(zu=s._Exp=s.asm.H).apply(null,arguments)},Pu=s._FlipLeftRight=function(){return(Pu=s._FlipLeftRight=s.asm.I).apply(null,arguments)},eg=s._Floor=function(){return(eg=s._Floor=s.asm.J).apply(null,arguments)},tg=s._FloorDiv=function(){return(tg=s._FloorDiv=s.asm.K).apply(null,arguments)},ng=s._FusedBatchNorm=function(){return(ng=s._FusedBatchNorm=s.asm.L).apply(null,arguments)},ag=s._FusedConv2D=function(){return(ag=s._FusedConv2D=s.asm.M).apply(null,arguments)},rg=s._FusedDepthwiseConv2D=function(){return(rg=s._FusedDepthwiseConv2D=s.asm.N).apply(null,arguments)},Xe=s._Gather=function(){return(Xe=s._Gather=s.asm.O).apply(null,arguments)},sg=s._GatherNd=function(){return(sg=s._GatherNd=s.asm.P).apply(null,arguments)},ig=s._Greater=function(){return(ig=s._Greater=s.asm.Q).apply(null,arguments)},og=s._GreaterEqual=function(){return(og=s._GreaterEqual=s.asm.R).apply(null,arguments)},lg=s._LeakyRelu=function(){return(lg=s._LeakyRelu=s.asm.S).apply(null,arguments)},ug=s._Less=function(){return(ug=s._Less=s.asm.T).apply(null,arguments)},dg=s._LessEqual=function(){return(dg=s._LessEqual=s.asm.U).apply(null,arguments)},Lu=s._Log=function(){return(Lu=s._Log=s.asm.V).apply(null,arguments)},Lp=s._LogicalAnd=function(){return(Lp=s._LogicalAnd=s.asm.W).apply(null,arguments)},Wp=s._Max=function(){return(Wp=s._Max=s.asm.X).apply(null,arguments)},hg=s._MaxPool=function(){return(hg=s._MaxPool=s.asm.Y).apply(null,arguments)},pg=s._Maximum=function(){return(pg=s._Maximum=s.asm.Z).apply(null,arguments)},cg=s._Mean=function(){return(cg=s._Mean=s.asm._).apply(null,arguments)},fg=s._Min=function(){return(fg=s._Min=s.asm.$).apply(null,arguments)},mg=s._Minimum=function(){return(mg=s._Minimum=s.asm.aa).apply(null,arguments)},gg=s._MirrorPad=function(){return(gg=s._MirrorPad=s.asm.ba).apply(null,arguments)},yg=s._Multiply=function(){return(yg=s._Multiply=s.asm.ca).apply(null,arguments)},pt=s._Neg=function(){return(pt=s._Neg=s.asm.da).apply(null,arguments)},Ag=s._NonMaxSuppressionV3=function(){return(Ag=s._NonMaxSuppressionV3=s.asm.ea).apply(null,arguments)},xg=s._NonMaxSuppressionV4=function(){return(xg=s._NonMaxSuppressionV4=s.asm.fa).apply(null,arguments)},bg=s._NonMaxSuppressionV5=function(){return(bg=s._NonMaxSuppressionV5=s.asm.ga).apply(null,arguments)},Eo=s._NotEqual=function(){return(Eo=s._NotEqual=s.asm.ha).apply(null,arguments)},Bp=s._OneHot=function(){return(Bp=s._OneHot=s.asm.ia).apply(null,arguments)},Vp=s._PadV2=function(){return(Vp=s._PadV2=s.asm.ja).apply(null,arguments)},Up=s._Pow=function(){return(Up=s._Pow=s.asm.ka).apply(null,arguments)},vg=s._Prelu=function(){return(vg=s._Prelu=s.asm.la).apply(null,arguments)},wg=s._Prod=function(){return(wg=s._Prod=s.asm.ma).apply(null,arguments)},jp=s._RealDiv=function(){return(jp=s._RealDiv=s.asm.na).apply(null,arguments)},kg=s._Relu=function(){return(kg=s._Relu=s.asm.oa).apply(null,arguments)},Hp=s._Relu6=function(){return(Hp=s._Relu6=s.asm.pa).apply(null,arguments)},vs=s._ResizeBilinear=function(){return(vs=s._ResizeBilinear=s.asm.qa).apply(null,arguments)},Ig=s._Reverse=function(){return(Ig=s._Reverse=s.asm.ra).apply(null,arguments)},Sg=s._RotateWithOffset=function(){return(Sg=s._RotateWithOffset=s.asm.sa).apply(null,arguments)},b3=s._Round=function(){return(b3=s._Round=s.asm.ta).apply(null,arguments)},Gp=s._Rsqrt=function(){return(Gp=s._Rsqrt=s.asm.ua).apply(null,arguments)},Ng=s._ScatterNd=function(){return(Ng=s._ScatterNd=s.asm.va).apply(null,arguments)},Tg=s._SelectV2=function(){return(Tg=s._SelectV2=s.asm.wa).apply(null,arguments)},Eg=s._Sigmoid=function(){return(Eg=s._Sigmoid=s.asm.xa).apply(null,arguments)},Cg=s._Sin=function(){return(Cg=s._Sin=s.asm.ya).apply(null,arguments)},Mg=s._Softmax=function(){return(Mg=s._Softmax=s.asm.za).apply(null,arguments)},$g=s._Sqrt=function(){return($g=s._Sqrt=s.asm.Aa).apply(null,arguments)},Rg=s._Square=function(){return(Rg=s._Square=s.asm.Ba).apply(null,arguments)},Fg=s._SquaredDifference=function(){return(Fg=s._SquaredDifference=s.asm.Ca).apply(null,arguments)},Og=s._Step=function(){return(Og=s._Step=s.asm.Da).apply(null,arguments)},Dg=s._StridedSlice=function(){return(Dg=s._StridedSlice=s.asm.Ea).apply(null,arguments)},_g=s._Sub=function(){return(_g=s._Sub=s.asm.Fa).apply(null,arguments)},zg=s._Sum=function(){return(zg=s._Sum=s.asm.Ga).apply(null,arguments)},Pg=s._Tan=function(){return(Pg=s._Tan=s.asm.Ha).apply(null,arguments)},Lg=s._Tanh=function(){return(Lg=s._Tanh=s.asm.Ia).apply(null,arguments)},Wg=s._Tile=function(){return(Wg=s._Tile=s.asm.Ja).apply(null,arguments)},Bg=s._TopK=function(){return(Bg=s._TopK=s.asm.Ka).apply(null,arguments)},Vg=s._Transform=function(){return(Vg=s._Transform=s.asm.La).apply(null,arguments)},Ug=s._Transpose=function(){return(Ug=s._Transpose=s.asm.Ma).apply(null,arguments)},jg=s.__FusedMatMul=function(){return(jg=s.__FusedMatMul=s.asm.Na).apply(null,arguments)},Hg=s._malloc=function(){return(Hg=s._malloc=s.asm.Oa).apply(null,arguments)},Gg=s._free=function(){return(Gg=s._free=s.asm.Pa).apply(null,arguments)},qp=s.___errno_location=function(){return(qp=s.___errno_location=s.asm.Qa).apply(null,arguments)},Kp=s.stackSave=function(){return(Kp=s.stackSave=s.asm.Ra).apply(null,arguments)},Xp=s.stackRestore=function(){return(Xp=s.stackRestore=s.asm.Sa).apply(null,arguments)},Wu=s.stackAlloc=function(){return(Wu=s.stackAlloc=s.asm.Ta).apply(null,arguments)};s.cwrap=ee;var Co;function qg(ne){this.name="ExitStatus",this.message="Program terminated with exit("+ne+")",this.status=ne}Vr=function ne(){Co||Bu(),Co||(Vr=ne)};function Bu(ne){if(ne=ne||d,Ba>0||(ba(),Ba>0))return;function oe(){Co||(Co=!0,s.calledRun=!0,!_&&(sa(),Rn(),i(s),s.onRuntimeInitialized&&s.onRuntimeInitialized(),wn()))}s.setStatus?(s.setStatus("Running..."),setTimeout(function(){setTimeout(function(){s.setStatus("")},1),oe()},1)):oe()}if(s.run=Bu,s.preInit)for(typeof s.preInit=="function"&&(s.preInit=[s.preInit]);s.preInit.length>0;)s.preInit.pop()();return Bu(),r.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)}),TR="3.7.0",ER="3.7.0",CR="3.7.0",MR="3.7.0",$R="3.7.0",RR="3.7.0",FR="3.7.0",OR="3.7.0",DR=1e-7,_R=1e-4,zR=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}},L3=class{refCount(e){return Va("refCount")}incRef(e){return Va("incRef")}timerAvailable(){return!0}time(e){return Va("time")}read(e){return Va("read")}readSync(e){return Va("readSync")}numDataIds(){return Va("numDataIds")}disposeData(e,t){return Va("disposeData")}write(e,t,n){return Va("write")}move(e,t,n,a,r){return Va("move")}memory(){return Va("memory")}floatPrecision(){return Va("floatPrecision")}epsilon(){return this.floatPrecision()===32?DR:_R}dispose(){return Va("dispose")}};function Va(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 W3(e){let t=e.length,n=0,a=0;for(;t>0;)a=Math.random()*t|0,t--,n=e[t],e[t]=e[a],e[a]=n}function PR(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,a,r,s=0;for(;n>0;)s=Math.random()*n|0,n--,a=e[n],r=t[n],e[n]=e[s],t[n]=t[s],e[s]=a,t[s]=r}function qu(e,t,n){return Math.max(e,Math.min(t,n))}function LR(e){return e%2==0?e:e+1}function WR(e){let t=0;for(let n=0;nn+` Shapes ${e} and ${t} must match`)}function hi(e){L(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function pi(e,t=[],n=!1){if(t==null&&(t=[]),Array.isArray(e)||En(e)&&!n)for(let a=0;a0,n){return new Promise((a,r)=>{let s=0,i=()=>{if(e()){a();return}s++;let o=t(s);if(n!=null&&s>=n){r();return}setTimeout(i,o)};i()})}function KR(e,t){let n=1,a=-1;for(let s=0;s=0)n*=e[s];else if(e[s]===-1){if(a!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${a} and dim ${s}`);a=s}else if(e[s]<0)throw Error(`Shapes can not be < 0. Found ${e[s]} at dim ${s}`);if(a===-1){if(t>0&&t!==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 r=e.slice();return r[a]=t/n,r}function Xu(e,t){let n=t.length;return e=e==null?t.map((a,r)=>r):[].concat(e),L(e.every(a=>a>=-n&&a`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),L(e.every(a=>Zn(a)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(a=>a<0?n+a:a)}function B3(e,t){let n=[],a=[],r=t!=null&&Array.isArray(t)&&t.length===0,s=t==null||r?null:Xu(t,e).sort(),i=0;for(let o=0;oo)&&e[o]===1&&(n.push(e[o]),a.push(o)),s[i]<=o&&i++}e[o]!==1&&(n.push(e[o]),a.push(o))}return{newShape:n,keptDims:a}}function V3(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 U3(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 j3(e,t){for(let n=0;nt+=n.length),t}function Is(e){return typeof e=="string"||e instanceof String}function q3(e){return typeof e=="boolean"}function K3(e){return typeof e=="number"}function ec(e){return Array.isArray(e)?ec(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":K3(e)?"float32":Is(e)?"string":q3(e)?"bool":"float32"}function Ss(e){return!!(e&&e.constructor&&e.call&&e.apply)}function tc(e,t){for(let n=t;n=0;--a)n[a]=n[a+1]*e[a+1];return n}function X3(e,t,n,a=!1){let r=new Array;if(t.length===1){let s=t[0]*(a?2:1);for(let i=0;il*u)*(a?2:1);for(let l=0;lr*s)*(n?2:1);if(a===0)return[];if(a!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return X3(0,e,t,n)}function ny(e,t){let n=nc(e,t);for(let a=0;aa*r,1);if(t==null||t==="float32")return zo(e,new Float32Array(n));if(t==="int32")return zo(e,new Int32Array(n));if(t==="bool")return zo(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function ay(e){e.forEach(t=>{L(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function YR(e,t,n){if(t===0)return 0;if(t===1)return e[0];let a=e[e.length-1];for(let r=0;r{let[n,a]=t.split(":");this.urlFlags[n]=tF(n,a)})}};function QR(e){let t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...a)=>(eF(t,a[0],a[1]),a.join("="))),t}function eF(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function tF(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 ht(){return ka}var ka=null;function nF(e){ka=e}var sy;function J3(){if(sy==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");sy=e}return sy}function aF(){let e=J3();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function iy(e,t){let n=aF();if(n.has(e))return n.get(e);{let a=t();return n.set(e,a),n.get(e)}}var Q3="Abs",ev="Acos",tv="Acosh",oy="Add",nv="AddN",av="All",rv="Any",sv="ArgMax",iv="ArgMin",ov="Asin",lv="Asinh",uv="Atan",dv="Atanh",hv="Atan2",pv="AvgPool",rF="AvgPoolGrad",cv="AvgPool3D",sF="AvgPool3DGrad",fv="BatchMatMul",mv="BatchToSpaceND",gv="Bincount",iF="BroadcastTo",ly="Cast",yv="Ceil",Av="ClipByValue",xv="Complex",bv="ComplexAbs",vv="Concat",wv="Conv2D",kv="Conv2DBackpropFilter",Iv="Conv2DBackpropInput",Sv="Conv3D",oF="Conv3DBackpropFilterV2",Nv="Conv3DBackpropInputV2",Tv="Cos",Ev="Cosh",Cv="Cumsum",Mv="CropAndResize",$v="DenseBincount",Rv="DepthToSpace",Fv="DepthwiseConv2dNative",Ov="DepthwiseConv2dNativeBackpropFilter",Dv="DepthwiseConv2dNativeBackpropInput",_v="Diag",zv="Dilation2D",lF="Dilation2DBackpropInput",uF="Dilation2DBackpropFilter",Pv="RealDiv",Lv="Einsum",Wv="Elu",dF="EluGrad",Bv="Erf",Vv="Equal",Uv="Exp",jv="ExpandDims",Hv="Expm1",Gv="FFT",qv="Fill",Kv="FlipLeftRight",Xv="Floor",Zv="FloorDiv",Yv="FusedBatchNorm",Jv="GatherV2",Qv="GatherNd",ew="Greater",tw="GreaterEqual",uy="Identity",nw="IFFT",aw="Imag",rw="IsFinite",sw="IsInf",iw="IsNan",ow="LeakyRelu",lw="Less",uw="LessEqual",dw="LinSpace",hw="Log",pw="Log1p",cw="LogicalAnd",fw="LogicalNot",mw="LogicalOr",hF="LogSoftmax",gw="LRN",pF="LRNGrad",yw="Max",Aw="Maximum",xw="MaxPool",cF="MaxPoolGrad",bw="MaxPool3D",fF="MaxPool3DGrad",vw="MaxPoolWithArgmax",ww="Mean",kw="Min",Iw="Minimum",Sw="MirrorPad",Nw="Mod",Tw="Multinomial",Ew="Multiply",Cw="Neg",Mw="NotEqual",$w="NonMaxSuppressionV3",Rw="NonMaxSuppressionV4",Fw="NonMaxSuppressionV5",Ow="OnesLike",Dw="OneHot",_w="Pack",zw="PadV2",mF="Pool",Pw="Pow",Lw="Prelu",Ww="Prod",Bw="Range",Vw="Real",Uw="Reciprocal",jw="Relu",Hw="Reshape",Gw="ResizeNearestNeighbor",gF="ResizeNearestNeighborGrad",qw="ResizeBilinear",yF="ResizeBilinearGrad",Kw="Relu6",Xw="Reverse",Zw="Round",Yw="Rsqrt",Jw="ScatterNd",Qw="Select",e7="Selu",t7="Slice",n7="Sin",a7="Sinh",r7="Sign",s7="Sigmoid",i7="Softplus",o7="Sqrt",l7="Sum",u7="SpaceToBatchND",d7="SplitV",h7="Softmax",p7="SparseFillEmptyRows",c7="SparseReshape",f7="SparseSegmentMean",m7="SparseSegmentSum",g7="SparseToDense",y7="SquaredDifference",AF="Square",A7="StridedSlice",x7="StringNGrams",b7="StringSplit",v7="StringToHashBucketFast",w7="Sub",k7="Tan",I7="Tanh",dy="Tile",S7="TopK",N7="Transform",T7="Transpose",E7="Unique",C7="Unpack",M7="UnsortedSegmentSum",$7="ZerosLike",R7="Step",hy="FromPixels",F7="RotateWithOffset",py="_FusedMatMul",cy="FusedConv2D",fy="FusedDepthwiseConv2D",Po=iy("kernelRegistry",()=>new Map),Zu=iy("gradRegistry",()=>new Map);function ac(e,t){let n=gy(e,t);return Po.get(n)}function my(e){return Zu.get(e)}function Lo(e){let t=Po.entries(),n=[];for(;;){let{done:a,value:r}=t.next();if(a)break;let[s,i]=r,[o]=s.split("_");o===e&&n.push(i)}return n}function rc(e){let{kernelName:t,backendName:n}=e,a=gy(t,n);Po.has(a)&&console.warn(`The kernel '${t}' for backend '${n}' is already registered`),Po.set(a,e)}function xF(e){let{kernelName:t}=e;Zu.has(t)&&ht().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${t}'`),Zu.set(t,e)}function bF(e,t){let n=gy(e,t);if(!Po.has(n))throw new Error(`The kernel '${e}' for backend '${t}' is not registered`);Po.delete(n)}function vF(e){if(!Zu.has(e))throw new Error(`The gradient '${e}' for backend is not registered`);Zu.delete(e)}function wF(e,t){Lo(e).forEach(n=>{let a=Object.assign({},n,{backendName:t});rc(a)})}function gy(e,t){return`${t}_${e}`}var O7={};$e(O7,{arraysEqual:()=>Kr,assert:()=>L,assertNonNegativeIntegerDimensions:()=>ay,assertNonNull:()=>hi,assertShapesMatch:()=>On,bytesFromStringArray:()=>G3,bytesPerElement:()=>ty,checkConversionForErrors:()=>j3,clamp:()=>qu,computeStrides:()=>_o,createScalarValue:()=>EF,createShuffledIndices:()=>GR,decodeString:()=>oc,distSquared:()=>VR,encodeString:()=>Qu,fetch:()=>MF,fingerPrint64:()=>TF,flatten:()=>pi,getArrayFromDType:()=>U3,getTypedArrayFromDType:()=>V3,hasEncodingLoss:()=>XR,hexToLong:()=>Yu,indexToLoc:()=>JR,inferDtype:()=>ec,inferFromImplicitShape:()=>KR,isBoolean:()=>q3,isFunction:()=>Ss,isInt:()=>Zn,isNumber:()=>K3,isPromise:()=>ry,isScalarShape:()=>UR,isString:()=>Is,isTypedArray:()=>En,isValidDtype:()=>H3,locToIndex:()=>YR,makeOnesTypedArray:()=>ny,makeZerosNestedTypedArray:()=>ZR,makeZerosTypedArray:()=>nc,nearestDivisor:()=>tc,nearestLargerEven:()=>LR,now:()=>Ju,parseAxisParam:()=>Xu,randUniform:()=>BR,repeatedTry:()=>qR,rightPad:()=>Ku,shuffle:()=>W3,shuffleCombo:()=>PR,sizeFromShape:()=>Jt,sizeToSquarishShape:()=>HR,squeezeShape:()=>B3,sum:()=>WR,tanh:()=>jR,toNestedArray:()=>zo,toTypedArray:()=>ic});var D7=qr(D3()),ci=D7.default||D7;function Yu(e){return ci.fromString(e,!0,16)}var _7=Yu("c3a5c85c97cb3127"),fi=Yu("b492b66fbe98f273"),Dn=Yu("9ae16a3b2f90404f");function yy(e){return e.xor(e.shru(47))}function z7(e,t,n){let a=e.slice(t,t+n);return ci.fromBytes(Array.from(a),!0,!0)}function It(e,t){return z7(e,t,8)}function P7(e,t){return z7(e,t,4)}function fn(e,t){return t===0?e:e.shru(t).or(e.shl(64-t))}function Ns(e,t,n=Yu("9ddfea08eb382d69")){let a=e.xor(t).mul(n);a=a.xor(a.shru(47));let r=t.xor(a).mul(n);return r=r.xor(r.shru(47)),r=r.mul(n),r}function kF(e,t,n,a,r,s){r=r.add(e),s=fn(s.add(r).add(a),21);let i=r;return r=r.add(t),r=r.add(n),s=s.add(fn(r,44)),[r.add(a),s.add(i)]}function sc(e,t,n,a){return kF(It(e,t),It(e,t+8),It(e,t+16),It(e,t+24),n,a)}function IF(e,t=e.length){if(t>=8){let n=Dn.add(t*2),a=It(e,0).add(Dn),r=It(e,t-8),s=fn(r,37).mul(n).add(a),i=fn(a,25).add(r).mul(n);return Ns(s,i,n)}if(t>=4){let n=Dn.add(t*2),a=P7(e,0);return Ns(a.shl(3).add(t),P7(e,t-4),n)}if(t>0){let n=e[0],a=e[t>>1],r=e[t-1],s=n+(a<<8),i=t+(r<<2);return yy(Dn.mul(s).xor(_7.mul(i))).mul(Dn)}return Dn}function SF(e,t=e.length){let n=Dn.add(t*2),a=It(e,0).mul(fi),r=It(e,8),s=It(e,t-8).mul(n),i=It(e,t-16).mul(Dn);return Ns(fn(a.add(r),43).add(fn(s,30)).add(i),a.add(fn(r.add(Dn),18)).add(s),n)}function NF(e,t=e.length){let n=Dn.add(t*2),a=It(e,0).mul(Dn),r=It(e,8),s=It(e,t-8).mul(n),i=It(e,t-16).mul(Dn),o=fn(a.add(r),43).add(fn(s,30)).add(i),l=Ns(o,a.add(fn(r.add(Dn),18)).add(s),n),u=It(e,16).mul(n),d=It(e,24),h=o.add(It(e,t-32)).mul(n),p=l.add(It(e,t-24)).mul(n);return Ns(fn(u.add(d),43).add(fn(h,30)).add(p),u.add(fn(d.add(a),18)).add(h),n)}function TF(e,t=e.length){let n=ci.fromNumber(81,!0);if(t<=32)return t<=16?IF(e,t):SF(e,t);if(t<=64)return NF(e,t);let a=n,r=n.mul(fi).add(113),s=yy(r.mul(Dn).add(113)).mul(Dn),i=[ci.UZERO,ci.UZERO],o=[ci.UZERO,ci.UZERO];a=a.mul(Dn).add(It(e,0));let l=0,u=(t-1>>6)*64,d=u+(t-1&63)-63;do a=fn(a.add(r).add(i[0]).add(It(e,l+8)),37).mul(fi),r=fn(r.add(i[1]).add(It(e,l+48)),42).mul(fi),a=a.xor(o[1]),r=r.add(i[0]).add(It(e,l+40)),s=fn(s.add(o[0]),33).mul(fi),i=sc(e,l,i[1].mul(fi),a.add(o[0])),o=sc(e,l+32,s.add(o[1]),r.add(It(e,l+16))),[s,a]=[a,s],l+=64;while(l!==u);let h=fi.add(s.and(255).shl(1));return l=d,o[0]=o[0].add(t-1&63),i[0]=i[0].add(o[0]),o[0]=o[0].add(i[0]),a=fn(a.add(r).add(i[0]).add(It(e,l+8)),37).mul(h),r=fn(r.add(i[1]).add(It(e,l+48)),42).mul(h),a=a.xor(o[1].mul(9)),r=r.add(i[0].mul(9).add(It(e,l+40))),s=fn(s.add(o[0]),33).mul(h),i=sc(e,l,i[1].mul(h),a.add(o[0])),o=sc(e,l+32,s.add(o[1]),r.add(It(e,l+16))),[s,a]=[a,s],Ns(Ns(i[0],o[0],h).add(yy(r).mul(_7)).add(s),Ns(i[1],o[1],h).add(a),h)}function EF(e,t){return t==="string"?Qu(e):ic([e],t)}function CF(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function ic(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=pi(e)),ht().getBool("DEBUG")&&j3(e,t),CF(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 a=0;a{a=n()},s,i=Ju();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(r);else{r();for(let o of a)o.dataSync();s=Promise.resolve({kernelMs:Ju()-i})}if(ht().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let o=0;o{RF(u,l.dtype,e)})}return{kernelName:e,outputs:a,inputs:t,timeMs:s.then(o=>o.kernelMs),extraInfo:s.then(o=>o.getExtraProfileInfo!=null?o.getExtraProfileInfo():"")}}logKernelProfile(e){let{kernelName:t,outputs:n,timeMs:a,inputs:r,extraInfo:s}=e;n.forEach(i=>{Promise.all([i.data(),a,s]).then(o=>{this.logger.logKernelProfile(t,i,o[0],o[1],r,o[2])})})}};function RF(e,t,n){if(t!=="float32")return!1;for(let a=0;a0?m:""} `}}console.log(`%c${o} %c${i} %c${l}D ${d} %c${u} %c${h} %c${s}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function OF(e,t,n){let a={},r={};for(let l=0;la[f.id]=!0),c=!0,r[u.id]=!0;break}if(c)break}}let s={};s[n.id]=!0;let i={};for(let l=e.length-1;l>=0;l--){let u=e[l],d=u.inputs;for(let h=0;h=0;r--){let s=t[r],i=[];if(s.outputs.forEach(l=>{let u=e[l.id];u!=null?i.push(u):i.push(null)}),s.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`);let o=s.gradient(i);for(let l in s.inputs){if(!(l in o))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(o)}.`);let u=n(()=>o[l]());if(u.dtype!=="float32")throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${u.dtype}'`);let d=s.inputs[l];if(!Kr(u.shape,d.shape))throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${l}' has shape '${u.shape}', which does not match the shape of the input '${d.shape}'`);if(e[d.id]==null)e[d.id]=u;else{let h=e[d.id];e[d.id]=a(h,u),h.dispose()}}}}var L7=20,ed=3,Ay=7;function _F(e,t,n,a){let r=_o(t),s=zF(e,t,n,r),i=t.length,o=lc(e,t,n,r,s),l=["Tensor"];return a&&(l.push(` dtype: ${n}`),l.push(` rank: ${i}`),l.push(` shape: [${t}]`),l.push(" values:")),l.push(o.map(u=>" "+u).join(` `)),l.join(` `)}function zF(e,t,n,a){let r=Jt(t),s=a[a.length-1],i=new Array(s).fill(0),o=t.length,l=n==="complex64"?nd(e):e;if(o>1)for(let u=0;uL7){let g=ed*i,y=Array.from(e.slice(0,g)),A=Array.from(e.slice((o-ed)*i,o*i));return n==="complex64"&&(y=nd(y),A=nd(A)),["["+y.map((x,v)=>td(x,r[v],n)).join(", ")+", ..., "+A.map((x,v)=>td(x,r[o-ed+v],n)).join(", ")+"]"]}let f=n==="complex64"?nd(e):Array.from(e);return["["+f.map((g,y)=>td(g,r[y],n)).join(", ")+"]"]}let u=t.slice(1),d=a.slice(1),h=a[0]*i,p=[];if(o>L7){for(let f=0;f`Length of values '${a}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||U3(t,this.size),this.strides=_o(e)}set(e,...t){t.length===0&&(t=[0]),L(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 a of e){if(a<0||a>=this.shape[t]){let r=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(r)}t++}let n=e[e.length-1];for(let a=0;aoc(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}dataSync(){this.throwIfDisposed();let e=kr().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>oc(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 kr().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(kr().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Wo.print(this,e)}clone(){return this.throwIfDisposed(),Wo.clone(this)}toString(e=!1){let t=this.dataSync();return _F(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Wo.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),kr().makeVariable(this,e,t,n)}};Object.defineProperty(St,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function VF(){return iy("Tensor",()=>St)}VF();var ad=class extends St{constructor(e,t,n,a){super(e.shape,e.dtype,e.dataId,a);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(!Kr(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);kr().disposeTensor(this),this.dataId=e.dataId,kr().incRef(this,null)}dispose(){kr().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(ad,Symbol.hasInstance,{value:e=>e instanceof St&&e.assign!=null&&e.assign instanceof Function});var B7={};$e(B7,{assertTypesMatch:()=>V7,getTensorsInContainer:()=>Iy,isTensorInList:()=>HF,makeTypesMatch:()=>Vt});var xy;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(xy||(xy={}));var by;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(by||(by={}));var vy;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(vy||(vy={}));var wy;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(wy||(wy={}));var ky;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(ky||(ky={}));var UF={float32:wy,int32:by,bool:vy,complex64:ky};function dc(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return UF[e][t]}function jF(e){return dc(e,"int32")}function Vt(e,t){if(e.dtype===t.dtype)return[e,t];let n=dc(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function V7(e,t){L(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function HF(e,t){return t.some(n=>n.id===e.id)}function Iy(e){let t=[],n=new Set;return U7(e,t,n),t}function U7(e,t,n){if(e==null)return;if(e instanceof St){t.push(e);return}if(!GF(e))return;let a=e;for(let r in a){let s=a[r];n.has(s)||(n.add(s),U7(s,t,n))}}function GF(e){return Array.isArray(e)||typeof e=="object"}function Sy(e){return e.kernelName!=null}var j7=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()}},Ny=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new j7}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.setupFunc!=null&&e.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){Lo(e).forEach(t=>{t.disposeFunc!=null&&t.disposeFunc(this.registry[e])})}initializeBackend(e){let t=this.registryFactory[e];if(t==null)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{let n=t.factory();if(n&&!(n instanceof L3)&&typeof n.then=="function"){let a=++this.pendingBackendInitId,r=n.then(s=>a(athis.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){let e=this.getSortedBackends();for(let t=0;tthis.startScope(n),()=>this.endScope(a),()=>(a=t(),a instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),a))}scopedRun(e,t,n){e();try{let a=n();return t(),a}catch(a){throw t(),a}}nextTensorId(){return Ny.nextTensorId++}nextVariableId(){return Ny.nextVariableId++}clone(e){let t=V.runKernel(uy,{x:e}),n={x:e},a=s=>({x:()=>{let i="float32",o={x:s},l={dtype:i};return V.runKernel(ly,o,l)}}),r=[];return this.addTapeNode(this.state.activeScope.name,n,[t],a,r,{}),t}runKernel(e,t,n){if(ac(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 a=this.backend.numDataIds(),r=0;n.forEach(o=>{r+=o.dtype==="complex64"?3:1});let s=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=a-t-r-s;if(i>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${i} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[],a=this.isTapeOn(),r=this.state.numBytes,s=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let i;this.backendName==null&&this.backend;let o,l=Sy(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(Sy(e)){let{kernelName:c,inputs:m,attrs:f}=e;this.backendName==null&&this.backend;let g=ac(c,this.backendName);L(g!=null,()=>`Cannot find registered kernel '${c}' for backend '${this.backendName}'`),i=()=>{let y=this.backend.numDataIds();o=g.kernelFunc({inputs:m,attrs:f,backend:this.backend});let A=Array.isArray(o)?o:[o];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(c,y,A);let x=A.map(v=>{if(v.rank!=null)return v;let{dataId:b,shape:w,dtype:I}=v;return this.makeTensorFromDataId(b,w,I)});if(a){let v=this.getTensorsForGradient(c,m,x);n=this.saveTensorsForBackwardMode(v)}return x}}else{let{forwardFunc:c}=e,m=f=>{!a||(n=f.map(g=>this.keep(this.clone(g))))};i=()=>{let f=this.backend.numDataIds();o=this.tidy(()=>c(this.backend,m));let g=Array.isArray(o)?o:[o];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,f,g),g}}let{inputs:u,attrs:d}=e,h=Sy(e)?null:e.backwardsFunc,p;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=i():(p=this.profiler.profileKernel(l,u,()=>i()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(p),t=p.outputs)}),a&&this.addTapeNode(l,u,t,h,n,d),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-r,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-s,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(u).map(c=>u[c]!=null?u[c].shape:null),outputShapes:t.map(c=>c.shape),kernelTimeMs:p.timeMs,extraInfo:p.extraInfo}),Array.isArray(o)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(t=>this.keep(this.clone(t)))}getTensorsForGradient(e,t,n){let a=my(e);if(a!=null){let r=a.inputsToSave||[],s=a.outputsToSave||[],i;a.saveAllInputs?(L(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),i=Object.keys(t).map(l=>t[l])):i=r.map(l=>t[l]);let o=n.filter((l,u)=>s[u]);return i.concat(o)}return[]}makeTensor(e,t,n,a){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",a=a||this.backend;let r=e;n==="string"&&Is(e[0])&&(r=e.map(o=>Qu(o)));let s=a.write(r,t,n),i=new St(t,n,s,this.nextTensorId());if(this.trackTensor(i,a),n==="string"){let o=this.state.tensorInfo.get(s),l=G3(r);this.state.numBytes+=l-o.bytes,o.bytes=l}return i}makeTensorFromDataId(e,t,n,a){n=n||"float32";let r=new St(t,n,e,this.nextTensorId());return this.trackTensor(r,a),r}makeVariable(e,t=!0,n,a){n=n||this.nextVariableId().toString(),a!=null&&a!==e.dtype&&(e=e.cast(a));let r=new ad(e,t,n,this.nextTensorId());if(this.state.registeredVariables[r.name]!=null)throw new Error(`Variable with name ${r.name} was already registered`);return this.state.registeredVariables[r.name]=r,this.incRef(r,this.backend),r}trackTensor(e,t){this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++;let n=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(n=e.size*ty(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 ad||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*ty(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(a=>a.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(let a of this.state.activeProfile.kernels)a.kernelTimeMs=await a.kernelTimeMs,a.extraInfo=await a.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,n,a,r,s){let i={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:r},o=my(e);o!=null&&(a=o.gradFunc),a!=null&&(i.gradient=l=>(l=l.map((u,d)=>{if(u==null){let h=n[d],p=nc(h.size,h.dtype);return this.makeTensor(p,h.shape,h.dtype)}return u}),a(l.length>1?l:l[0],r,s))),this.state.activeTape.push(i)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){let t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){let t=Iy(e),n=new Set(t.map(r=>r.id));for(let r=0;r{!r.kept&&r.scopeId===a.id&&this.track(r)})}gradients(e,t,n,a=!1){if(L(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 r=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));L(r instanceof St,()=>"The result y returned by f() must be a tensor.");let s=OF(this.state.activeTape,t,r);if(!a&&s.length===0&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",()=>{let i={};i[r.id]=n==null?qF(r.shape):n,DF(i,s,l=>this.tidy(l),KF);let o=t.map(l=>i[l.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(l=>{for(let u of l.saved)u.dispose()}),this.state.activeTape=null),{value:r,grads:o}})}customGrad(e){return L(Ss(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{L(t.every(i=>i instanceof St),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n,a={};t.forEach((i,o)=>{a[o]=i});let r=(i,o)=>(n=e(...t,o),L(n.value instanceof St,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),L(Ss(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),s=(i,o)=>{let l=n.gradFunc(i,o),u=Array.isArray(l)?l:[l];L(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(...)."),L(u.every(h=>h instanceof St),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");let d={};return u.forEach((h,p)=>{d[p]=()=>h}),d};return this.runKernelFunc({forwardFunc:r,backwardsFunc:s,inputs:a})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}async time(e){let t=Ju(),n=await this.backend.time(e);return n.wallMs=Ju()-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 j7;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}},Ty=Ny;Ty.nextTensorId=0,Ty.nextVariableId=0;function qF(e){let t=ny(Jt(e),"float32");return V.makeTensor(t,e,"float32")}function H7(){let e=J3();if(e._tfengine==null){let t=new Y3(e);e._tfengine=new Ty(t)}return nF(e._tfengine.ENV),LF(()=>e._tfengine),e._tfengine}var V=H7();function KF(e,t){let n={a:e,b:t};return V.runKernel(oy,n)}var G7={};$e(G7,{isBrowser:()=>q7,isMobile:()=>ZF});function XF(){return typeof navigator!="undefined"&&navigator!=null}function ZF(e){if(e||XF()){if(e||(e=navigator),e.product==="ReactNative")return!0;let t=e.userAgent||e.vendor||window.opera;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 q7(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var Qa=ht();Qa.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.")});Qa.registerFlag("IS_BROWSER",()=>q7());Qa.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");Qa.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));Qa.registerFlag("PROD",()=>!1);Qa.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>Qa.getBool("DEBUG"));Qa.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);Qa.registerFlag("IS_TEST",()=>!1);Qa.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);Qa.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);function Ir(e,t){let n=e;if(En(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];let a=[];for(;Array.isArray(n)||En(n)&&t!=="string";)a.push(n.length),n=n[0];return Array.isArray(e)&&ht().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&K7(e,a,[]),a}function K7(e,t,n){if(n=n||[],!Array.isArray(e)&&!En(e)){L(t.length===0,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}L(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),L(e.length===t[0],()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);let a=t.slice(1);for(let r=0;r=0&&(r=a),X7(a,r,t,n),e==null||!En(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string"){let o=e==null?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${o}'`)}let s=Ir(e,r);!En(e)&&!Array.isArray(e)&&(e=[e]);let i=r!=="string"?ic(e,r):pi(e,[],!0);return V.makeTensor(i,s,r)}function rd(e,t,n,a="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map((r,s)=>O(r,`${t}[${s}]`,n,a))}var Z7="__op";function U(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],a=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n=n+Z7;let r=(...s)=>{V.startScope(n);try{let i=a(...s);return ry(i)&&console.error("Cannot return a Promise inside of tidy."),V.endScope(i),i}catch(i){throw V.endScope(null),i}};return Object.defineProperty(r,"name",{value:n,configurable:!0}),r}function YF(e,t){let n=O(e,"real","complex"),a=O(t,"imag","complex");On(n.shape,a.shape,`real and imag shapes, ${n.shape} and ${a.shape}, must match in call to tf.complex().`);let r={real:n,imag:a};return V.runKernel(xv,r)}var mi=U({complex_:YF});function Ts(e,t,n,a){if(a==null&&(a=ec(e)),a==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!En(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){ay(t);let r=Jt(t),s=Jt(n);L(r===s,()=>`Based on the provided shape, [${t}], the tensor should have ${r} values but has ${s}`);for(let i=0;i`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `)}}return!En(e)&&!Array.isArray(e)&&(e=[e]),t=t||n,e=a!=="string"?ic(e,a):pi(e,[],!0),V.makeTensor(e,t,a)}function er(e,t,n){let a=Ir(e,n);return Ts(e,t,a,n)}var Ey={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},hc=4;async function JF(e,t){let n=[],a=[],r=Array.isArray(e)?e.map(i=>i.name):Object.keys(e);for(let i=0;i{let p=await l.bytes(),c=p.reduce((g,y)=>g+y.length,0)+hc*p.length,m=new Uint8Array(c),f=0;for(let g=0;g{if(t+=s.byteLength,n.push(s.byteLength===s.buffer.byteLength?s:new s.constructor(s)),!(s instanceof Float32Array||s instanceof Int32Array||s instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${s.constructor.name}`)});let a=new Uint8Array(t),r=0;return n.forEach(s=>{a.set(new Uint8Array(s.buffer),r),r+=s.byteLength}),a.buffer}var Cy=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function J7(e){return Cy?Buffer.byteLength(e):new Blob([e]).size}function eO(e){if(Cy)return Buffer.from(e).toString("base64");let t=new Uint8Array(e),n="";for(let a=0,r=t.length;a{t+=r.byteLength});let n=new Uint8Array(t),a=0;return e.forEach(r=>{n.set(new Uint8Array(r),a),a+=r.byteLength}),n.buffer}function Q7(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 sd(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:J7(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:J7(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function nO(){let e=n=>{let a=n<<13,r=0;for(;(a&8388608)==0;)r-=8388608,a<<=1;return a&=~8388608,r+=947912704,a|r},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 aO(){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 rO(){let e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function sO(){let e=nO(),t=aO(),n=rO();return a=>{let r=new ArrayBuffer(4*a.length),s=new Uint32Array(r);for(let i=0;i>10]+(o&1023)]+t[o>>10];s[i]=l}return new Float32Array(r)}}var Gt=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return Gt.instance==null&&(Gt.instance=new Gt),Gt.instance}static registerSaveRouter(e){Gt.getInstance().saveRouters.push(e)}static registerLoadRouter(e){Gt.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return Gt.getHandlers(e,"save")}static getLoadHandlers(e,t){return Gt.getHandlers(e,"load",t)}static getHandlers(e,t,n){let a=[];return(t==="load"?Gt.getInstance().loadRouters:Gt.getInstance().saveRouters).forEach(r=>{let s=r(e,n);s!==null&&a.push(s)}),a}},iO=e=>Gt.registerSaveRouter(e),oO=e=>Gt.registerLoadRouter(e),lO=e=>Gt.getSaveHandlers(e),uO=(e,t)=>Gt.getLoadHandlers(e,t),$y="tensorflowjs",Ry=1,gi="models_store",Es="model_info_store";function ek(){if(!ht().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 Fy(e){let t=e.result;t.createObjectStore(gi,{keyPath:"modelPath"}),t.createObjectStore(Es,{keyPath:"modelPath"})}var yi=class{constructor(e){if(this.indexedDB=ek(),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,a)=>{let r=this.indexedDB.open($y,Ry);r.onupgradeneeded=()=>Fy(r),r.onsuccess=()=>{let s=r.result;if(t==null){let i=s.transaction(gi,"readonly"),o=i.objectStore(gi).get(this.modelPath);o.onsuccess=()=>{if(o.result==null)return s.close(),a(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));n(o.result.modelArtifacts)},o.onerror=l=>(s.close(),a(o.error)),i.oncomplete=()=>s.close()}else{let i=sd(t),o=s.transaction(Es,"readwrite"),l=o.objectStore(Es),u=l.put({modelPath:this.modelPath,modelArtifactsInfo:i}),d;u.onsuccess=()=>{d=s.transaction(gi,"readwrite");let h=d.objectStore(gi).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:i});h.onsuccess=()=>n({modelArtifactsInfo:i}),h.onerror=p=>{l=o.objectStore(Es);let c=l.delete(this.modelPath);c.onsuccess=()=>(s.close(),a(h.error)),c.onerror=m=>(s.close(),a(h.error))}},u.onerror=h=>(s.close(),a(u.error)),o.oncomplete=()=>{d==null?s.close():d.oncomplete=()=>s.close()}}},r.onerror=s=>a(r.error)})}};yi.URL_SCHEME="indexeddb://";var tk=e=>ht().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(yi.URL_SCHEME)?dO(e.slice(yi.URL_SCHEME.length)):null;Gt.registerSaveRouter(tk);Gt.registerLoadRouter(tk);function dO(e){return new yi(e)}function hO(e){return e.startsWith(yi.URL_SCHEME)?e.slice(yi.URL_SCHEME.length):e}var pO=class{constructor(){this.indexedDB=ek()}async listModels(){return new Promise((e,t)=>{let n=this.indexedDB.open($y,Ry);n.onupgradeneeded=()=>Fy(n),n.onsuccess=()=>{let a=n.result,r=a.transaction(Es,"readonly"),s=r.objectStore(Es).getAll();s.onsuccess=()=>{let i={};for(let o of s.result)i[o.modelPath]=o.modelArtifactsInfo;e(i)},s.onerror=i=>(a.close(),t(s.error)),r.oncomplete=()=>a.close()},n.onerror=a=>t(n.error)})}async removeModel(e){return e=hO(e),new Promise((t,n)=>{let a=this.indexedDB.open($y,Ry);a.onupgradeneeded=()=>Fy(a),a.onsuccess=()=>{let r=a.result,s=r.transaction(Es,"readwrite"),i=s.objectStore(Es),o=i.get(e),l;o.onsuccess=()=>{if(o.result==null)return r.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{let u=i.delete(e),d=()=>{l=r.transaction(gi,"readwrite");let h=l.objectStore(gi).delete(e);h.onsuccess=()=>t(o.result.modelArtifactsInfo),h.onerror=p=>n(o.error)};u.onsuccess=d,u.onerror=h=>(d(),r.close(),n(o.error))}},o.onerror=u=>(r.close(),n(o.error)),s.oncomplete=()=>{l==null?r.close():l.oncomplete=()=>r.close()}},a.onerror=r=>n(a.error)})}},Xr="/",Bo="tensorflowjs_models",nk="info",cO="model_topology",fO="weight_specs",mO="weight_data",gO="model_metadata";function ak(e){return{info:[Bo,e,nk].join(Xr),topology:[Bo,e,cO].join(Xr),weightSpecs:[Bo,e,fO].join(Xr),weightData:[Bo,e,mO].join(Xr),modelMetadata:[Bo,e,gO].join(Xr)}}function yO(e){let t=e.split(Xr);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(Xr)}function AO(e){return e.startsWith(Ai.URL_SCHEME)?e.slice(Ai.URL_SCHEME.length):e}var Ai=class{constructor(e){if(!ht().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=ak(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),a=sd(e);try{this.LS.setItem(this.keys.info,JSON.stringify(a)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,eO(e.weightData));let r={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};return e.signature!=null&&(r.signature=e.signature),e.userDefinedMetadata!=null&&(r.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(r.modelInitializer=e.modelInitializer),this.LS.setItem(this.keys.modelMetadata,JSON.stringify(r)),{modelArtifactsInfo:a}}catch(r){throw this.LS.removeItem(this.keys.info),this.LS.removeItem(this.keys.topology),this.LS.removeItem(this.keys.weightSpecs),this.LS.removeItem(this.keys.weightData),this.LS.removeItem(this.keys.modelMetadata),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${a.modelTopologyBytes}, weightSpecsBytes=${a.weightSpecsBytes}, weightDataBytes=${a.weightDataBytes}.`)}}}async load(){let e=JSON.parse(this.LS.getItem(this.keys.info));if(e==null)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if(e.modelTopologyType!=="JSON")throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");let t={},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 a=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(a==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=a;let r=this.LS.getItem(this.keys.modelMetadata);if(r!=null){let i=JSON.parse(r);t.format=i.format,t.generatedBy=i.generatedBy,t.convertedBy=i.convertedBy,i.signature!=null&&(t.signature=i.signature),i.userDefinedMetadata!=null&&(t.userDefinedMetadata=i.userDefinedMetadata),i.modelInitializer!=null&&(t.modelInitializer=i.modelInitializer)}let s=this.LS.getItem(this.keys.weightData);if(s==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=tO(s),t}};Ai.URL_SCHEME="localstorage://";var rk=e=>ht().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Ai.URL_SCHEME)?xO(e.slice(Ai.URL_SCHEME.length)):null;Gt.registerSaveRouter(rk);Gt.registerLoadRouter(rk);function xO(e){return new Ai(e)}var bO=class{constructor(){L(ht().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),L(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let e={},t=Bo+Xr,n=Xr+nk;for(let a=0;a"scheme must not be undefined or null."),e.endsWith(Vo)&&(e=e.slice(0,e.indexOf(Vo))),L(e.length>0,()=>"scheme must not be an empty string.");let n=Ia.getInstance();L(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 pc(e){if(e.indexOf(Vo)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Ia.getSchemes().join(",")}`);return{scheme:e.split(Vo)[0],path:e.split(Vo)[1]}}async function sk(e,t,n=!1){L(e!==t,()=>`Old path and new path are the same: '${e}'`);let a=Gt.getLoadHandlers(e);L(a.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),L(a.length<2,()=>`Copying failed because more than one (${a.length}) load handlers for source URL ${e}.`);let r=a[0],s=Gt.getSaveHandlers(t);L(s.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),L(s.length<2,()=>`Copying failed because more than one (${a.length}) save handlers for destination URL ${t}.`);let i=s[0],o=pc(e).scheme,l=pc(e).path,u=o===pc(e).scheme,d=await r.load();n&&u&&await Ia.getManager(o).removeModel(l);let h=await i.save(d);return n&&!u&&await Ia.getManager(o).removeModel(l),h.modelArtifactsInfo}async function vO(){let e=Ia.getSchemes(),t={};for(let n of e){let a=await Ia.getManager(n).listModels();for(let r in a){let s=n+Vo+r;t[s]=a[r]}}return t}async function wO(e){let t=pc(e);return Ia.getManager(t.scheme).removeModel(t.path)}async function kO(e,t){return sk(e,t,!1)}async function IO(e,t){return sk(e,t,!0)}var SO=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(ht().get("IS_BROWSER")){ht().setPlatform("browser",new SO);try{Ia.registerManager(Ai.URL_SCHEME,new bO)}catch(e){}try{Ia.registerManager(yi.URL_SCHEME,new pO)}catch(e){}}var NO={importFetch:()=>_3()},Oy,TO=class{constructor(){this.util=di("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return ht().global.fetch!=null?ht().global.fetch(e,t):(Oy==null&&(Oy=NO.importFetch()),Oy(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)}};ht().get("IS_NODE")&&ht().setPlatform("node",new TO);function Zr(e,t="float32",n){return t=t||"float32",ay(e),new uc(e,t,n)}function EO(e,t){let n=O(e,"x","cast");if(!H3(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 a={x:n},r={dtype:t};return V.runKernel(ly,a,r)}var zt=U({cast_:EO});function CO(e){let t={x:O(e,"x","clone","string_or_numeric")};return V.runKernel(uy,t)}var Yr=U({clone_:CO});function ik(e,t=!1){console.log(e.toString(t))}H7();var MO={buffer:Zr,cast:zt,clone:Yr,print:ik};WF(MO);var ok={};$e(ok,{browserFiles:()=>zO,browserHTTPRequest:()=>VO,concatenateArrayBuffers:()=>My,copyModel:()=>kO,decodeWeights:()=>Y7,encodeWeights:()=>JF,fromMemory:()=>jO,getLoadHandlers:()=>uO,getModelArtifactsInfoForJSON:()=>sd,getSaveHandlers:()=>lO,http:()=>Py,isHTTPScheme:()=>zy,listModels:()=>vO,loadWeights:()=>PO,moveModel:()=>IO,registerLoadRouter:()=>oO,registerSaveRouter:()=>iO,removeModel:()=>wO,weightsLoaderFactory:()=>hk,withSaveHandler:()=>HO});var $O="model",RO=".json",FO=".weights.bin";function lk(e){return new Promise(t=>setTimeout(t)).then(e)}var Dy=class{constructor(e){if(!ht().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Dy.URL_SCHEME)&&(e=e.slice(Dy.URL_SCHEME.length)),(e==null||e.length===0)&&(e=$O),this.modelTopologyFileName=e+RO,this.weightDataFileName=e+FO}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}],a={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:n};e.signature!=null&&(a.signature=e.signature),e.userDefinedMetadata!=null&&(a.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(a.modelInitializer=e.modelInitializer);let r=window.URL.createObjectURL(new Blob([JSON.stringify(a)],{type:"application/json"})),s=this.jsonAnchor==null?document.createElement("a"):this.jsonAnchor;if(s.download=this.modelTopologyFileName,s.href=r,await lk(()=>s.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){let i=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;i.download=this.weightDataFileName,i.href=t,await lk(()=>i.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:sd(e)}}}},cc=Dy;cc.URL_SCHEME="downloads://";var OO=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.files=e}async load(){let e=this.files[0],t=this.files.slice(1);return new Promise((n,a)=>{let r=new FileReader;r.onload=s=>{let i=JSON.parse(s.target.result),o=i.modelTopology;if(o==null){a(new Error(`modelTopology field is missing from file ${e.name}`));return}t.length===0&&n({modelTopology:o});let l=i.weightsManifest;if(l==null){a(new Error(`weightManifest field is missing from file ${e.name}`));return}let u;try{u=this.checkManifestAndWeightFiles(l,t)}catch(c){a(c);return}let d=[],h=[],p=[];l.forEach(c=>{c.paths.forEach(m=>{h.push(m),p.push(null)}),d.push(...c.weights)}),l.forEach(c=>{c.paths.forEach(m=>{let f=new FileReader;f.onload=g=>{let y=g.target.result,A=h.indexOf(m);if(p[A]=y,p.indexOf(null)===-1){let x={modelTopology:o,weightSpecs:d,weightData:My(p),format:i.format,generatedBy:i.generatedBy,convertedBy:i.convertedBy};i.signature!=null&&(x.signature=i.signature),i.userDefinedMetadata!=null&&(x.userDefinedMetadata=i.userDefinedMetadata),i.modelInitializer!=null&&(x.modelInitializer=i.modelInitializer),n(x)}},f.onerror=g=>a(`Failed to weights data from file of path '${m}'.`),f.readAsArrayBuffer(u[m])})})},r.onerror=s=>a(`Failed to read model topology and weights manifest JSON from file '${e.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),r.readAsText(e)})}checkManifestAndWeightFiles(e,t){let n=[],a=t.map(s=>Q7(s.name)),r={};for(let s of e)s.paths.forEach(i=>{let o=Q7(i);if(n.indexOf(o)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${o}'`);if(n.push(o),a.indexOf(o)===-1)throw new Error(`Weight file with basename '${o}' is not provided.`);r[i]=t[a.indexOf(o)]});if(n.length!==t.length)throw new Error(`Mismatch in the number of files in weights manifest (${n.length}) and the number of weight files provided (${t.length}).`);return r}},DO=e=>ht().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(cc.URL_SCHEME)?_O(e.slice(cc.URL_SCHEME.length)):null;Gt.registerSaveRouter(DO);function _O(e="model"){return new cc(e)}function zO(e){return new OO(e)}function uk(e,t,n,a){i(e),n=n==null?0:n,a=a==null?1:a,o(n,a);let r=0,s=l=>(l.then(u=>{let d=n+ ++r/e.length*(a-n);return t(d),u}),l);function i(l){L(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function o(l,u){L(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),L(u>=0&&u<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${u}`),L(u>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${u}`)}return Promise.all(e.map(s))}async function dk(e,t){t==null&&(t={});let n=t.fetchFunc==null?ht().platform.fetch:t.fetchFunc,a=e.map(u=>n(u,t.requestInit,{isBinary:!0})),r=0,s=.5,i=(t.onProgress==null?await Promise.all(a):await uk(a,t.onProgress,r,s)).map(u=>u.arrayBuffer()),o=.5,l=1;return t.onProgress==null?await Promise.all(i):await uk(i,t.onProgress,o,l)}async function PO(e,t="",n,a){return hk(r=>dk(r,{requestInit:a}))(e,t,n)}function hk(e){return async(t,n="",a)=>{let r=t.map(()=>!1),s={},i=a!=null?a.map(()=>!1):[],o=[];if(t.forEach((c,m)=>{let f=0;c.weights.forEach(g=>{let y="quantization"in g?g.quantization.dtype:g.dtype,A=Ey[y]*Jt(g.shape),x=()=>{r[m]=!0,s[m]==null&&(s[m]=[]),s[m].push({manifestEntry:g,groupOffset:f,sizeBytes:A})};a!=null?a.forEach((v,b)=>{v===g.name&&(x(),i[b]=!0)}):x(),o.push(g.name),f+=A})}),!i.every(c=>c)){let c=a.filter((m,f)=>!i[f]);throw new Error(`Could not find weights in manifest with names: ${c.join(", ")}. Manifest JSON has weights with names: ${o.join(", ")}.`)}let l=r.reduce((c,m,f)=>(m&&c.push(f),c),[]),u=[];l.forEach(c=>{t[c].paths.forEach(m=>{let f=n+(n.endsWith("/")?"":"/")+m;u.push(f)})});let d=await e(u),h={},p=0;return l.forEach(c=>{let m=t[c].paths.length,f=0;for(let x=0;x{let v=g.slice(x.groupOffset,x.groupOffset+x.sizeBytes),b=Y7(v,[x.manifestEntry]);for(let w in b)h[w]=b[w]}),p+=m}),h}}var LO="application/octet-stream",WO="application/json",_y=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?(L(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=ht().platform.fetch,L(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&L(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}],a={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:n};e.signature!=null&&(a.signature=e.signature),e.userDefinedMetadata!=null&&(a.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(a.modelInitializer=e.modelInitializer),t.body.append("model.json",new Blob([JSON.stringify(a)],{type:WO}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:LO}),"model.weights.bin");let r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:sd(e),responses:[r]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${r.status}.`)}async load(){let e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(c){let m=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?m+=" 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.":m+=" Please make sure the server is serving valid JSON for this request.",new Error(m)}let n=t.modelTopology,a=t.weightsManifest,r=t.generatedBy,s=t.convertedBy,i=t.format,o=t.signature,l=t.userDefinedMetadata;if(n==null&&a==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);let u,d;a!=null&&([u,d]=await this.loadWeights(a));let h={modelTopology:n,weightSpecs:u,weightData:d,generatedBy:r,convertedBy:s,format:i};o!=null&&(h.signature=o),l!=null&&(h.userDefinedMetadata=l);let p=t.modelInitializer;return p&&(h.modelInitializer=p),h}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,a]=BO(t),r=this.weightPathPrefix||n,s=[];for(let u of e)s.push(...u.weights);let i=[],o=[];for(let u of e)for(let d of u.paths)this.weightUrlConverter!=null?o.push(this.weightUrlConverter(d)):i.push(r+d+a);this.weightUrlConverter&&i.push(...await Promise.all(o));let l=await dk(i,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[s,My(l)]}};_y.URL_SCHEME_REGEX=/^https?:\/\//;function BO(e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),a=e.substring(0,t),r=n>t?e.substring(n):"";return[a+"/",r]}function zy(e){return e.match(_y.URL_SCHEME_REGEX)!=null}var pk=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(a=>zy(a)):n=zy(e),n)return Py(e,t)}return null};Gt.registerSaveRouter(pk);Gt.registerLoadRouter(pk);function Py(e,t){return new _y(e,t)}function VO(e,t){return Py(e,t)}var Ly=class{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}},UO=class{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}};function jO(e,t,n,a){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new Ly(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 Ly({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 Ly({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:a}))}function HO(e){return new UO(e)}var ck={};$e(ck,{confusionMatrix:()=>ZO});function GO(e,t,n=!1,a=!1){let r=O(e,"a","matMul"),s=O(t,"b","matMul");[r,s]=Vt(r,s);let i={a:r,b:s},o={transposeA:n,transposeB:a};return V.runKernel(fv,i,o)}var yt=U({matMul_:GO});function qO(e,t,n=1,a=0){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);let r={indices:O(e,"indices","oneHot","int32")},s={depth:t,onValue:n,offValue:a};return V.runKernel(Dw,r,s)}var Wy=U({oneHot_:qO});function KO(e,t){let n=O(e,"x","transpose");if(t==null&&(t=n.shape.map((s,i)=>i).reverse()),L(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`),t.forEach(s=>{L(s>=0&&s`All entries in 'perm' must be between 0 and ${n.rank-1} but got ${t}`)}),n.rank<=1)return n.clone();let a={x:n},r={perm:t};return V.runKernel(T7,a,r)}var fc=U({transpose_:KO});function XO(e,t,n){let a=O(e,"labels","confusionMatrix"),r=O(t,"predictions","confusionMatrix");L(n==null||n>0&&Number.isInteger(n),()=>`If provided, numClasses must be a positive integer, but got ${n}`),L(a.rank===1,()=>`Expected the rank of labels to be 1, but got ${a.rank}`),L(r.rank===1,()=>`Expected the rank of predictions to be 1, but got ${r.rank}`),L(a.shape[0]===r.shape[0],()=>`Mismatch in the number of examples: ${a.shape[0]} vs. ${r.shape[0]}. Labels and predictions should have the same number of elements.`),L(n>0&&Number.isInteger(n),()=>`numClasses is required to be a positive integer, but got ${n}`);let s=Wy(zt(a,"int32"),n),i=Wy(zt(r,"int32"),n),o=fc(s),l=yt(o,i);return zt(l,"int32")}var ZO=U({confusionMatrix_:XO}),Ua={};$e(Ua,{fromPixels:()=>aD,fromPixelsAsync:()=>tD,toPixels:()=>nD});function mc(e,t,n){if(hi(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let a=Ir(e,n);if(a.length!==3&&a.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return Ts(e,t,a,n)}var Uo;function fk(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,a=!1,r=!1,s=!1,i=!1,o=!1;if(e.data instanceof Uint8Array)n=!0;else if(typeof ImageData!="undefined"&&e instanceof ImageData)a=!0;else if(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)r=!0;else if(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement)s=!0;else if(e.getContext!=null)i=!0;else if(typeof ImageBitmap!="undefined"&&e instanceof ImageBitmap)o=!0;else throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${e.constructor.name}`);if(r){let p=2;if(r&&e.readyState element.")}if(ac(hy,V.backendName)!=null){let p={pixels:e},c={numChannels:t};return V.runKernel(hy,p,c)}let[l,u]=r?[e.videoWidth,e.videoHeight]:[e.width,e.height],d;i?d=e.getContext("2d").getImageData(0,0,l,u).data:a||n?d=e.data:(s||r||o)&&(Uo==null&&(Uo=document.createElement("canvas").getContext("2d")),Uo.canvas.width=l,Uo.canvas.height=u,Uo.drawImage(e,0,0,l,u),d=Uo.getImageData(0,0,l,u).data);let h;if(t===4)h=new Int32Array(d);else{let p=l*u;h=new Int32Array(p*t);for(let c=0;c4||s===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${s}`);if(n.dtype!=="float32"&&n.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${n.dtype}. Please use float32 or int32 tensors.`);let i=await n.data(),o=n.dtype==="float32"?255:1,l=new Uint8ClampedArray(r*a*4);for(let u=0;u1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${c}.`)}else if(n.dtype==="int32"&&(c<0||c>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${c}.`);s===1?(d[0]=c*o,d[1]=c*o,d[2]=c*o):d[p]=c*o}let h=u*4;l[h+0]=Math.round(d[0]),l[h+1]=Math.round(d[1]),l[h+2]=Math.round(d[2]),l[h+3]=Math.round(d[3])}if(t!=null){t.width=r,t.height=a;let u=t.getContext("2d"),d=new ImageData(l,r,a);u.putImageData(d,0,0)}return n!==e&&n.dispose(),l}var aD=U({fromPixels_:fk}),mk={};$e(mk,{prepareAndValidate:()=>gk});function gk(e,t){let n=e.shape.length,a=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(a<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${a}.`);if(t.dtype!=="int32")throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[a-1]>n)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[a-1]} vs. ${n}`);if(Jt(e.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);let r=t.shape,s=r[r.length-1],i=1;for(let h=0;hh/u),1].slice(0,s);return[l,i,u,d]}var yk={};$e(yk,{calculateShapes:()=>Ak,validateInput:()=>Vy,validateUpdateShape:()=>By});function By(e,t,n){let a=t.rank>1?t.shape[t.rank-1]:1,r=t.rank>1?t.rank-1:1,s=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${a}, and batchDim: ${r}.`;if(n.rank1?t.shape[a-1]:1,s=n.length,i=1;for(let h=r;hrD,computeFlatOffset:()=>iD,computeOutShape:()=>xk,getNormalizedAxes:()=>kk,isSliceContinous:()=>sD,maskToAxes:()=>gc,parseSliceParams:()=>oD,sliceInfo:()=>lD,startForAxis:()=>Tk,startIndicesWithElidedDims:()=>Ik,stopForAxis:()=>Ek,stopIndicesWithElidedDims:()=>Sk,stridesForAxis:()=>Nk,stridesWithElidedDims:()=>bk});function rD(e,t,n){let a=e.shape.length;L(a===t.length,()=>`Error in slice${a}D: Length of begin ${t} must match the rank of the array (${a}).`),L(a===n.length,()=>`Error in slice${a}D: Length of size ${n} must match the rank of the array (${a}).`);for(let r=0;r`Error in slice${a}D: begin[${r}] + size[${r}] (${t[r]+n[r]}) would overflow input.shape[${r}] (${e.shape[r]})`)}function gc(e){let t=[],n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function xk(e,t,n){let a=[];for(let r=0;r0){let c=t[0],m=n+1;d=Ik(i,c,m,a,e),h=Sk(o,c,m,r,e),p=bk(s,c,m,e)}else for(let c=0;c-1)s[o]=0;else{let l=vk(t,n,o),u=a[l];e&1<-1)s[o]=Number.MAX_SAFE_INTEGER;else{let l=vk(t,n,o),u=a[l];e&1<0?i=Number.MIN_SAFE_INTEGER:i=Number.MAX_SAFE_INTEGER);let l=a[r];return i<0&&(i+=l),i=qu(0,i,l-1),i}function Ek(e,t,n,a,r,s){let i=t[r],o=n[r]||1;(e&1<0?i=Number.MAX_SAFE_INTEGER:i=Number.MIN_SAFE_INTEGER);let l=a[r];return i<0&&(i+=l),o>0?i=qu(0,i,l):i=qu(-1,i,l-1),i}function sD(e,t,n){let a=n.length;for(let r=0;r1){a=r;break}for(let r=a+1;r0||n[r]!==e[r])return!1;return!0}function iD(e,t){let n=e.length>0?e[e.length-1]:1;for(let a=0;a{L(i!==-1,()=>"slice() does not support negative begin indexing.")});let s;return n==null?s=new Array(r).fill(-1):typeof n=="number"?s=[n,...new Array(r-1).fill(-1)]:n.lengthi>=0?i:(L(i===-1,()=>`Negative size values should be exactly -1 but got ${i} for the slice() size at index ${o}.`),e.shape[o]-a[o])),[a,s]}function lD(e,t,n,a,r,s,i,o,l){let u=t.slice(),d=n.slice(),h=a;a==null&&(h=new Array(u.length));let p=gc(i);if(p.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(i!==0&&o!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(i!==0&&l!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");let c=e.length-u.length,m=gc(o),f=e.slice();m.forEach(w=>{u[w]=0,d[w]=1,f.splice(w,0,1)});let{begin:g,end:y,strides:A}=kk(f,p,c,u,d,h,r,s,i);u=g,d=y,h=A;let x=gc(l);x.forEach(w=>{d[w]=u[w]+1,h[w]=1});let v=xk(u,d,h),b=v.filter((w,I)=>x.indexOf(I)===-1);return{nonStrided:h.every(w=>w===1),$begin:u,$end:d,$strides:h,size:v,newShape:f,outShape:b}}var Ck={};$e(Ck,{Serializable:()=>Mk,SerializationMap:()=>xi,registerClass:()=>Cs});var Mk=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},xi=class{constructor(){this.classNameMap={}}static getMap(){return xi.instance==null&&(xi.instance=new xi),xi.instance}static register(e){xi.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function Cs(e){L(e.className!=null,()=>"Class being registered does not have the static className property defined."),L(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),L(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),xi.register(e)}var $k={};$e($k,{TEST_EPSILON_FLOAT16:()=>Rk,encodeStrings:()=>Fk,expectArrayBuffersEqual:()=>mD,expectArraysClose:()=>dD,expectArraysEqual:()=>pD,expectNumbersClose:()=>cD,expectPromiseToFail:()=>hD,expectValuesInRange:()=>fD,testEpsilon:()=>jy});var uD=.001,Rk=.1;function dD(e,t,n){return n==null&&(n=jy()),Hy(e,t,(a,r)=>Gy(a,r,n))}function jy(){return V.backend.floatPrecision()===32?uD:Rk}function Hy(e,t,n){let a=!0;if((En(e)||En(t))&&(a=!1),En(e)&&En(t)&&(a=!0),a){let i=e.constructor.name,o=t.constructor.name;if(i!==o)throw new Error(`Arrays are of different type. Actual: ${i}. Expected: ${o}`)}if(Array.isArray(e)&&Array.isArray(t)){let i=Ir(e),o=Ir(t);if(!Kr(i,o))throw new Error(`Arrays have different shapes. Actual: [${i}]. Expected: [${o}]`)}let r=En(e)?e:pi(e),s=En(t)?t:pi(t);if(r.length!==s.length)throw new Error(`Arrays have different lengths actual: ${r.length} vs expected: ${s.length}. Actual: ${r}. Expected: ${s}.`);for(let i=0;it.fail(),()=>t())}function pD(e,t){let n=typeof t=="string"||typeof t=="number"||typeof t=="boolean"?[t]:t;return Is(e)||Is(e[0])||Is(t)||Is(t[0])?Hy(e,n,(a,r)=>a==r):Hy(e,t,(a,r)=>Gy(a,r,0))}function cD(e,t,n){if(n==null&&(n=jy()),!Gy(e,t,n))throw new Error(`Numbers differ: actual === ${e}, expected === ${t}`)}function Gy(e,t,n){return!isFinite(e)&&!isFinite(t)?!0:!(isNaN(e)||isNaN(t)||Math.abs(e-t)>n)}function fD(e,t,n){for(let a=0;an)throw new Error(`Value out of range:${e[a]} low: ${t}, high: ${n}`)}function mD(e,t){expect(new Float32Array(e)).toEqual(new Float32Array(t))}function Fk(e){for(let t=0;tt.dispose())}function Dk(e){return V.keep(e)}function ID(e){return V.time(e)}function SD(e){return V.setBackend(e)}function ND(){return V.ready()}function TD(){return V.backendName}function ED(e){V.removeBackend(e)}function qy(e){return V.findBackend(e)}function CD(e){return V.findBackendFactory(e)}function Ky(e,t,n=1){return V.registerBackend(e,t,n)}function MD(){return V.backend}function $D(e,t){ht().setPlatform(e,t)}function RD(e,t){let n=O(e,"a","add"),a=O(t,"b","add");[n,a]=Vt(n,a);let r={a:n,b:a};return V.runKernel(oy,r)}var De=U({add_:RD});function FD(e,t){let n=O(e,"a","floorDiv"),a=O(t,"b","floorDiv");[n,a]=Vt(n,a);let r={a:n,b:a};return V.runKernel(Zv,r)}var _k=U({floorDiv_:FD});function OD(e,t){let n=O(e,"a","div"),a=O(t,"b","div");if([n,a]=Vt(n,a),n.dtype==="int32"&&a.dtype==="int32")return _k(n,a);let r={a:n,b:a},s={};return V.runKernel(Pv,r,s)}var Qe=U({div_:OD});function DD(e,t){let n=O(e,"a","mul"),a=O(t,"b","mul");[n,a]=Vt(n,a);let r={a:n,b:a};return V.runKernel(Ew,r)}var fe=U({mul_:DD});function _D(e){let t=O(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return V.runKernel(bv,n)}else{let n={x:t};return V.runKernel(Q3,n)}}var Sa=U({abs_:_D});function zD(e){let t={x:O(e,"x","acos")};return V.runKernel(ev,t)}var PD=U({acos_:zD});function LD(e){let t={x:O(e,"x","acosh")};return V.runKernel(tv,t)}var WD=U({acosh_:LD});function BD(e){L(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),L(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);let t=e.map((r,s)=>O(r,`tensors${s}`,"addN")),n=t[0];t.forEach(r=>{if(r.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(r=>{if(!Kr(r.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let a=t;return V.runKernel(nv,a)}var Xy=U({addN_:BD});function VD(e,t=null,n=!1){let a={x:O(e,"x","all","bool")},r={axis:t,keepDims:n};return V.runKernel(av,a,r)}var UD=U({all_:VD});function jD(e,t=null,n=!1){let a={x:O(e,"x","any","bool")},r={axis:t,keepDims:n};return V.runKernel(rv,a,r)}var HD=U({any_:jD});function GD(e,t=0){let n={x:O(e,"x","argMax")},a={axis:t};return V.runKernel(sv,n,a)}var Zy=U({argMax_:GD});function qD(e,t=0){let n={x:O(e,"x","argMin")},a={axis:t};return V.runKernel(iv,n,a)}var KD=U({argMin_:qD});function XD(e){let t={x:O(e,"x","asin")};return V.runKernel(ov,t)}var ZD=U({asin_:XD});function YD(e){let t={x:O(e,"x","asinh")};return V.runKernel(lv,t)}var JD=U({asinh_:YD});function QD(e){let t={x:O(e,"x","atan")};return V.runKernel(uv,t)}var e_=U({atan_:QD});function t_(e,t){let n=O(e,"a","atan2"),a=O(t,"b","atan2");[n,a]=Vt(n,a);let r={a:n,b:a};return V.runKernel(hv,r)}var n_=U({atan2_:t_});function a_(e){let t={x:O(e,"x","atanh")};return V.runKernel(dv,t)}var r_=U({atanh_:a_});function s_(e,t,n,a,r="NHWC",s){let i=e[3],o=[...t,i],l=Lk(r);return id(e,o,n,s,a,null,null,l)}function zk(e,t,n,a,r,s,i="channelsLast"){let[o,l]=yc(t),u;if(i==="channelsLast")u=[o,l,e[3],e[3]];else if(i==="channelsFirst")u=[o,l,e[1],e[1]];else throw new Error(`Unknown dataFormat ${i}`);return id(e,u,n,a,r,s,!1,i)}function i_(e,t,n,a,r,s,i="NDHWC"){let[o,l,u]=Jy(t),d,h;if(i==="NDHWC")h="channelsLast",d=[o,l,u,e[4],e[4]];else if(i==="NCDHW")h="channelsFirst",d=[o,l,u,e[1],e[1]];else throw new Error(`Unknown dataFormat ${i}`);return Pk(e,d,n,a,r,!1,h,s)}function id(e,t,n,a,r,s,i=!1,o="channelsLast"){let[l,u,d,h]=[-1,-1,-1,-1];if(o==="channelsLast")[l,u,d,h]=e;else if(o==="channelsFirst")[l,h,u,d]=e;else throw new Error(`Unknown dataFormat ${o}`);let[p,c,,m]=t,[f,g]=yc(n),[y,A]=yc(a),x=jo(p,y),v=jo(c,A),{padInfo:b,outHeight:w,outWidth:I}=u_(r,u,d,f,g,x,v,s,o),T=i?m*h:m,C;return o==="channelsFirst"?C=[l,T,w,I]:o==="channelsLast"&&(C=[l,w,I,T]),{batchSize:l,dataFormat:o,inHeight:u,inWidth:d,inChannels:h,outHeight:w,outWidth:I,outChannels:T,padInfo:b,strideHeight:f,strideWidth:g,filterHeight:p,filterWidth:c,effectiveFilterHeight:x,effectiveFilterWidth:v,dilationHeight:y,dilationWidth:A,inShape:e,outShape:C,filterShape:t}}function Pk(e,t,n,a,r,s=!1,i="channelsLast",o){let[l,u,d,h,p]=[-1,-1,-1,-1,-1];if(i==="channelsLast")[l,u,d,h,p]=e;else if(i==="channelsFirst")[l,p,u,d,h]=e;else throw new Error(`Unknown dataFormat ${i}`);let[c,m,f,,g]=t,[y,A,x]=Jy(n),[v,b,w]=Jy(a),I=jo(c,v),T=jo(m,b),C=jo(f,w),{padInfo:z,outDepth:$,outHeight:S,outWidth:D}=d_(r,u,d,h,y,A,x,I,T,C,o),_=s?g*p:g,W;return i==="channelsFirst"?W=[l,_,$,S,D]:i==="channelsLast"&&(W=[l,$,S,D,_]),{batchSize:l,dataFormat:i,inDepth:u,inHeight:d,inWidth:h,inChannels:p,outDepth:$,outHeight:S,outWidth:D,outChannels:_,padInfo:z,strideDepth:y,strideHeight:A,strideWidth:x,filterDepth:c,filterHeight:m,filterWidth:f,effectiveFilterDepth:I,effectiveFilterHeight:T,effectiveFilterWidth:C,dilationDepth:v,dilationHeight:b,dilationWidth:w,inShape:e,outShape:W,filterShape:t}}function o_(e,t,n,a,r){a==null&&(a=Yy(e,t,n));let s=e[0],i=e[1],o=bi((s-t+2*a)/n+1,r),l=bi((i-t+2*a)/n+1,r);return[o,l]}function l_(e,t,n,a,r,s){r==null&&(r=Yy(e,t,a));let i=e[0],o=e[1],l=e[2],u=bi((i-t+2*r)/a+1,s),d=bi((o-t+2*r)/a+1,s),h=bi((l-t+2*r)/a+1,s);return[u,d,h,n]}function Yy(e,t,n,a=1){let r=jo(t,a);return Math.floor((e[0]*(n-1)-n+r)/2)}function yc(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function Jy(e){return typeof e=="number"?[e,e,e]:e}function jo(e,t){return t<=1?e:e+(e-1)*(t-1)}function u_(e,t,n,a,r,s,i,o,l){let u,d,h;if(typeof e=="number"){u={top:e,bottom:e,left:e,right:e,type:e===0?"VALID":"NUMBER"};let p=o_([t,n],s,a,e,o);d=p[0],h=p[1]}else if(e==="same"){d=Math.ceil(t/a),h=Math.ceil(n/r);let p=Math.max(0,(d-1)*a+s-t),c=Math.max(0,(h-1)*r+i-n),m=Math.floor(p/2),f=p-m,g=Math.floor(c/2),y=c-g;u={top:m,bottom:f,left:g,right:y,type:"SAME"}}else if(e==="valid")u={top:0,bottom:0,left:0,right:0,type:"VALID"},d=Math.ceil((t-s+1)/a),h=Math.ceil((n-i+1)/r);else if(typeof e=="object"){let p=l==="channelsLast"?e[1][0]:e[2][0],c=l==="channelsLast"?e[1][1]:e[2][1],m=l==="channelsLast"?e[2][0]:e[3][0],f=l==="channelsLast"?e[2][1]:e[3][1];u={top:p,bottom:c,left:m,right:f,type:p===0&&c===0&&m===0&&f===0?"VALID":"EXPLICIT"},d=bi((t-s+p+c)/a+1,o),h=bi((n-i+m+f)/r+1,o)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:u,outHeight:d,outWidth:h}}function d_(e,t,n,a,r,s,i,o,l,u,d){let h,p,c,m;if(typeof e=="number"){h={top:e,bottom:e,left:e,right:e,front:e,back:e,type:e===0?"VALID":"NUMBER"};let f=l_([t,n,a,1],o,1,r,e,d);p=f[0],c=f[1],m=f[2]}else if(e==="same"){p=Math.ceil(t/r),c=Math.ceil(n/s),m=Math.ceil(a/i);let f=(p-1)*r+o-t,g=(c-1)*s+l-n,y=(m-1)*i+u-a,A=Math.floor(f/2),x=f-A,v=Math.floor(g/2),b=g-v,w=Math.floor(y/2),I=y-w;h={top:v,bottom:b,left:w,right:I,front:A,back:x,type:"SAME"}}else if(e==="valid")h={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},p=Math.ceil((t-o+1)/r),c=Math.ceil((n-l+1)/s),m=Math.ceil((a-u+1)/i);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:h,outDepth:p,outHeight:c,outWidth:m}}function bi(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 od(e){let[t,n,a]=yc(e);return t===1&&n===1&&a===1}function Jr(e,t){return od(e)||od(t)}function Lk(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function h_(e,t){let n={x:O(e,"x","reshape","string_or_numeric")},a={shape:t};return V.runKernel(Hw,n,a)}var le=U({reshape_:h_});function p_(e,t,n,a,r){let s=O(e,"x","avgPool","float32"),i=1;L(Jr(n,i),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`);let o=s,l=!1;s.rank===3&&(l=!0,o=le(s,[1,s.shape[0],s.shape[1],s.shape[2]])),L(o.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${o.rank}.`),r!=null&&L(Zn(a),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${r} but got pad ${a}.`);let u={x:o},d={filterSize:t,strides:n,pad:a,dimRoundingMode:r},h=V.runKernel(pv,u,d);return h=zt(h,s.dtype),l?le(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var Wk=U({avgPool_:p_});function c_(e,t,n,a,r,s="NDHWC"){let i=O(e,"x","avgPool3d","float32"),o=i,l=!1;i.rank===4&&(l=!0,o=le(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),L(o.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${o.rank}.`),L(s==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),r!=null&&L(Zn(a),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${a}.`);let u={x:o},d={filterSize:t,strides:n,pad:a,dimRoundingMode:r,dataFormat:s},h=V.runKernel(cv,u,d);return h=zt(h,o.dtype),l?le(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var f_=U({avgPool3d_:c_});function m_(e,t=0){L(e.length>=1,()=>"Pass at least one tensor to concat");let n=rd(e,"tensors","concat","string_or_numeric");if(n[0].dtype==="complex64"&&n.forEach(s=>{if(s.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor with dtype ${s.dtype}. `)}),n.length===1)return Yr(n[0]);let a=n,r={axis:t};return V.runKernel(vv,a,r)}var sn=U({concat_:m_});function g_(e){let t={x:O(e,"x","sigmoid")};return V.runKernel(s7,t)}var Sr=U({sigmoid_:g_});function y_(e,t,n){let a=O(e,"x","slice","string_or_numeric");if(a.rank===0)throw new Error("Slicing scalar is not possible");let r={x:a},s={begin:t,size:n};return V.runKernel(t7,r,s)}var Ze=U({slice_:y_});function A_(e){let t={x:O(e,"x","tanh")};return V.runKernel(I7,t)}var Qy=U({tanh_:A_});function x_(e,t,n,a,r,s){let i=O(e,"forgetBias","basicLSTMCell"),o=O(t,"lstmKernel","basicLSTMCell"),l=O(n,"lstmBias","basicLSTMCell"),u=O(a,"data","basicLSTMCell"),d=O(r,"c","basicLSTMCell"),h=O(s,"h","basicLSTMCell"),p=sn([u,h],1),c=yt(p,o),m=De(c,l),f=m.shape[0],g=m.shape[1]/4,y=[f,g],A=Ze(m,[0,0],y),x=Ze(m,[0,g],y),v=Ze(m,[0,g*2],y),b=Ze(m,[0,g*3],y),w=De(fe(Sr(A),Qy(x)),fe(d,Sr(De(i,v)))),I=fe(Qy(w),Sr(b));return[w,I]}var b_=U({basicLSTMCell_:x_});function v_(e,t,n){let a=O(e,"x","batchToSpaceND"),r=t.reduce((o,l)=>o*l);L(a.rank>=1+t.length,()=>`input rank is ${a.rank} but should be > than blockShape.length ${t.length}`),L(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),L(a.shape[0]%r==0,()=>`input tensor batch is ${a.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${r}`);let s={x:a},i={blockShape:t,crops:n};return V.runKernel(mv,s,i)}var Bk=U({batchToSpaceND_:v_});function w_(e){let t;return e.rank===0||e.rank===1?t=le(e,[1,1,1,e.size]):e.rank===2?t=le(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=le(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function k_(e,t,n,a,r,s){s==null&&(s=.001);let i=O(e,"x","batchNorm"),o=O(t,"mean","batchNorm"),l=O(n,"variance","batchNorm"),u;r!=null&&(u=O(r,"scale","batchNorm"));let d;a!=null&&(d=O(a,"offset","batchNorm")),L(o.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),L(d==null||o.rank===d.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),L(u==null||o.rank===u.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let h={x:w_(i),scale:u,offset:d,mean:o,variance:l},p={varianceEpsilon:s},c=V.runKernel(Yv,h,p);return le(c,i.shape)}var Ac=U({batchNorm_:k_});function I_(e,t,n,a,r,s){let i=O(e,"x","batchNorm"),o=O(t,"mean","batchNorm"),l=O(n,"variance","batchNorm"),u;r!=null&&(u=O(r,"scale","batchNorm"));let d;return a!=null&&(d=O(a,"offset","batchNorm")),L(i.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`),L(o.rank===2||o.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${o.rank}.`),L(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),u!=null&&L(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`),d!=null&&L(d.rank===2||d.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${d.rank}.`),Ac(i,o,l,d,u,s)}var S_=U({batchNorm2d_:I_});function N_(e,t,n,a,r,s){let i=O(e,"x","batchNorm"),o=O(t,"mean","batchNorm"),l=O(n,"variance","batchNorm"),u;r!=null&&(u=O(r,"scale","batchNorm"));let d;return a!=null&&(d=O(a,"offset","batchNorm")),L(i.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`),L(o.rank===3||o.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${o.rank}.`),L(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),u!=null&&L(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`),d!=null&&L(d.rank===3||d.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${d.rank}.`),Ac(i,o,l,d,u,s)}var T_=U({batchNorm3d_:N_});function E_(e,t,n,a,r,s){let i=O(e,"x","batchNorm"),o=O(t,"mean","batchNorm"),l=O(n,"variance","batchNorm"),u;r!=null&&(u=O(r,"scale","batchNorm"));let d;return a!=null&&(d=O(a,"offset","batchNorm")),L(i.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}.`),L(o.rank===4||o.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${o.rank}.`),L(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),u!=null&&L(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`),d!=null&&L(d.rank===4||d.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${d.rank}.`),Ac(i,o,l,d,u,s)}var C_=U({batchNorm4d_:E_});function M_(e,t,n){let a=O(e,"x","bincount"),r=O(t,"weights","bincount");L(a.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${a.dtype}`),L(n>=0,()=>`size must be non-negative, but got ${n}.`),L(r.size===a.size||r.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${a.shape}, weights shape: ${r.shape}.`);let s={x:a,weights:r},i={size:n};return V.runKernel(gv,s,i)}var Vk=U({bincount_:M_});function $_(e,t){let n=O(e,"broadcastTo","x"),a=n.shape;if(t.some(l=>!(l>0)||l%1!=0))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.lengthn.rank){let l=n.shape.slice();for(;l.length=0;l--)if(r[l]===t[l])s[l]=1;else if(n.shape[l]!==1)throw new Error(`broadcastTo(): [${a}] cannot be broadcast to [${t}].`);if(s.map((l,u)=>l>1?u:-1).filter(l=>l>=0).length===0)return Yr(n);let i={x:n},o={reps:s};return V.runKernel(dy,i,o)}var xc=U({broadcastTo_:$_});function R_(e){let t={x:O(e,"x","ceil")};return V.runKernel(yv,t)}var F_=U({ceil_:R_});function O_(e,t,n){let a=O(e,"x","clipByValue");L(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`);let r={x:a},s={clipValueMin:t,clipValueMax:n};return V.runKernel(Av,r,s)}var D_=U({clipByValue_:O_});function __(e){return sn(e,0)}var z_=U({concat1d_:__});function P_(e,t){return sn(e,t)}var ld=U({concat2d_:P_});function L_(e,t){return sn(e,t)}var W_=U({concat3d_:L_});function B_(e,t){return sn(e,t)}var V_=U({concat4d_:B_});function U_(e,t,n,a,r="NHWC",s=[1,1],i){let o=O(e,"x","conv2d"),l=O(t,"filter","conv2d"),u=o,d=!1;o.rank===3&&(d=!0,u=le(o,[1,o.shape[0],o.shape[1],o.shape[2]])),L(u.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`),L(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),i!=null&&L(Zn(a),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${a}.`);let h=r==="NHWC"?u.shape[3]:u.shape[1];L(h===l.shape[2],()=>`Error in conv2d: depth of input (${h}) must match input depth for filter ${l.shape[2]}.`),L(Jr(n,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`);let p={x:u,filter:l},c={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i},m=V.runKernel(wv,p,c);return d?le(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var bc=U({conv2d_:U_});function j_(e,t,n,a,r="NWC",s=1,i){let o=O(e,"x","conv1d"),l=O(t,"filter","conv1d"),u=o,d=!1;o.rank===2&&(d=!0,u=le(o,[1,o.shape[0],o.shape[1]])),L(u.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${u.rank}.`),L(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),i!=null&&L(Zn(a),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${a}.`),L(u.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`),L(Jr(n,s),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${s}'`),L(r==="NWC",()=>`Error in conv1d: got dataFormat of ${r} but only NWC is currently supported.`);let h=le(l,[1,l.shape[0],l.shape[1],l.shape[2]]),p=le(u,[u.shape[0],1,u.shape[1],u.shape[2]]),c=bc(p,h,[1,n],a,"NHWC",[1,s],i);return d?le(c,[c.shape[2],c.shape[3]]):le(c,[c.shape[0],c.shape[2],c.shape[3]])}var H_=U({conv1d_:j_});function G_(e,t,n,a,r,s="NHWC",i){L(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let o=e,l=t,u=!1;t.rank===3&&(u=!0,l=le(t,[1,t.shape[0],t.shape[1],t.shape[2]]),o=[1,e[0],e[1],e[2]]),L(o.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${o.length}.`),L(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),L(n.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);let d=s==="NHWC"?o[3]:o[1],h=s==="NHWC"?l.shape[3]:l.shape[1];L(d===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${d}) must match input depth for filter ${n.shape[2]}.`),L(h===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${h}) must match output depth for filter ${n.shape[3]}.`),i!=null&&L(Zn(r),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${i} but got pad ${r}.`);let p={dy:l,filter:n},c={strides:a,pad:r,dataFormat:s,dimRoundingMode:i,inputShape:o},m=V.runKernel(Iv,p,c);return u?le(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var Uk=U({conv2DBackpropInput_:G_});function q_(e,t,n,a,r,s){let i=O(e,"x","conv2dTranspose"),o=O(t,"filter","conv2dTranspose");return Uk(n,i,o,a,r,"NHWC",s)}var K_=U({conv2dTranspose_:q_});function X_(e,t,n,a,r="NDHWC",s=[1,1,1]){let i=O(e,"x","conv3d"),o=O(t,"filter","conv3d"),l=i,u=!1;i.rank===4&&(u=!0,l=le(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),L(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),L(o.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${o.rank}.`),L(l.shape[4]===o.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${o.shape[3]}.`),L(Jr(n,s),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),L(r==="NDHWC",()=>`Error in conv3d: got dataFormat of ${r} but only NDHWC is currently supported.`);let d={x:l,filter:o},h={strides:n,pad:a,dataFormat:r,dilations:s},p=V.runKernel(Sv,d,h);return u?le(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var Z_=U({conv3d_:X_});function Y_(e,t,n,a,r){L(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let s=e,i=t,o=!1;t.rank===4&&(o=!0,i=le(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),s=[1,e[0],e[1],e[2],e[3]]);let l=s[4],u=i.shape[4];L(s.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`),L(i.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${i.rank}`),L(n.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),L(l===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`),L(u===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${u}) must match output depth for filter ${n.shape[4]}.`);let d={dy:i,filter:n},h={pad:r,strides:a,inputShape:s},p=V.runKernel(Nv,d,h);return o?le(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var J_=U({conv3DBackpropInput_:Y_});function Q_(e,t,n,a,r){let s=O(e,"x","conv3dTranspose"),i=O(t,"filter","conv3dTranspose");return J_(n,s,i,a,r)}var ez=U({conv3dTranspose_:Q_});function tz(e){let t={x:O(e,"x","cos")};return V.runKernel(Tv,t)}var nz=U({cos_:tz});function az(e){let t={x:O(e,"x","cosh")};return V.runKernel(Ev,t)}var rz=U({cosh_:az});function sz(e,t=0,n=!1,a=!1){let r={x:O(e,"x","cumsum")},s={axis:t,exclusive:n,reverse:a};return V.runKernel(Cv,r,s)}var iz=U({cumsum_:sz});function oz(e,t,n,a=!1){let r=O(e,"x","denseBincount"),s=O(t,"weights","denseBincount");L(r.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${r.dtype}`),L(r.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${r.rank}.`),L(n>=0,()=>`size must be non-negative, but got ${n}.`),L(s.size===r.size||s.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${r.shape}, weights shape: ${s.shape}.`);let i={x:r,weights:s},o={size:n,binaryOutput:a};return V.runKernel($v,i,o)}var lz=U({denseBincount_:oz});function uz(e,t,n="NHWC"){let a=O(e,"x","depthToSpace"),r=n==="NHWC"?a.shape[1]:a.shape[2],s=n==="NHWC"?a.shape[2]:a.shape[3],i=n==="NHWC"?a.shape[3]:a.shape[1];L(r*t>=0,()=>`Negative dimension size caused by overflow when multiplying ${r} and ${t} for depthToSpace with input shape ${a.shape}`),L(s*t>=0,()=>`Negative dimension size caused by overflow when multiplying ${s} and ${t} for depthToSpace with input shape ${a.shape}`),L(i%(t*t)==0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${i} for depthToSpace with input shape ${a.shape}`);let o={x:a},l={blockSize:t,dataFormat:n};return V.runKernel(Rv,o,l)}var dz=U({depthToSpace_:uz});function hz(e,t,n,a,r="NHWC",s=[1,1],i){let o=O(e,"x","depthwiseConv2d"),l=O(t,"filter","depthwiseConv2d"),u=o,d=!1;o.rank===3&&(d=!0,u=le(o,[1,o.shape[0],o.shape[1],o.shape[2]])),L(u.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`),L(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),L(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]}.`),i!=null&&L(Zn(a),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${a}.`);let h={x:u,filter:l},p={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i},c=V.runKernel(Fv,h,p);return d?le(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var e1=U({depthwiseConv2d_:hz});function pz(e){let t={x:O(e,"x","diag")};return V.runKernel(_v,t)}var cz=U({diag_:pz});function fz(e,t,n,a,r=[1,1],s="NHWC"){let i=O(e,"x","dilation2d"),o=O(t,"filter","dilation2d");L(i.rank===3||i.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`),L(o.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${o.rank}.`),L(s==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${s}`);let l=i,u=!1;i.rank===3&&(l=le(i,[1,i.shape[0],i.shape[1],i.shape[2]]),u=!0);let d={x:l,filter:o},h={strides:n,pad:a,dilations:r},p=V.runKernel(zv,d,h);return u?le(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var mz=U({dilation2d_:fz});function gz(e,t){let n=e.length,a=[];for(let r=0;r1&&i===1&&a.unshift(s)}return a}function jk(e,t){let n=[];for(let a=0;a1)&&n.unshift(s)}return n}function In(e,t){let n=[],a=Math.max(e.length,t.length);for(let r=0;r`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${a.rank}.`);let r=n.rank===1?n.size:n.shape[1],s=a.rank===1?a.size:a.shape[0];if(L(r===s,()=>`Error in dot: inner dimensions of inputs must match, but got ${r} and ${s}.`),n.rank===1&&a.rank===1){let i=le(n,[1,-1]),o=le(a,[-1,1]),l=yt(i,o);return le(l,[])}else if(n.rank===1&&a.rank===2){let i=le(n,[1,-1]),o=le(a,[a.shape[0],a.shape[1]]),l=yt(i,o);return le(l,[l.size])}else if(n.rank===2&&a.rank===1){let i=le(a,[-1,1]),o=yt(n,i);return le(o,[o.size])}else{let i=le(a,[a.shape[0],a.shape[1]]);return yt(n,i)}}var kz=U({dot_:wz});function Iz(e,...t){let n=t.map((r,s)=>O(r,`tensors${s}`,"einsum")),a={equation:e};return V.runKernel(Lv,n,a)}var Sz=U({einsum_:Iz});function Nz(e){let t={x:O(e,"x","elu")};return V.runKernel(Wv,t)}var Gk=U({elu_:Nz});function Tz(e){let t=O(e,"x","erf");L(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=zt(t,"float32"));let n={x:t};return V.runKernel(Bv,n)}var Ez=U({erf_:Tz});function Cz(e){let t={x:O(e,"x","exp")};return V.runKernel(Uv,t)}var vi=U({exp_:Cz});function Mz(e,t=0){let n=O(e,"x","expandDims","string_or_numeric");L(t<=n.rank,()=>"Axis must be <= rank of the tensor");let a={input:n},r={dim:t};return V.runKernel(jv,a,r)}var Qr=U({expandDims_:Mz});function $z(e){let t={x:O(e,"x","expm1")};return V.runKernel(Hv,t)}var Rz=U({expm1_:$z});function Fz(e,t){let n=O(e,"x","tile","string_or_numeric");L(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`);let a={x:n},r={reps:t};return V.runKernel(dy,a,r)}var vc=U({tile_:Fz});function Oz(e,t,n,a="float32"){t==null&&(t=e);let r=Zr([e,t],a),s=e<=t?e:t;for(let o=0;o`Error in localResponseNormalization: x must be rank 3 or 4 but got rank ${s.rank}.`),L(Zn(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let i=s,o=!1;s.rank===3&&(o=!0,i=le(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let l={x:i},u={depthRadius:t,bias:n,alpha:a,beta:r},d=V.runKernel(gw,l,u);return o?le(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var Jz=U({localResponseNormalization_:Yz});function Qz(e){let t={x:O(e,"x","log")};return V.runKernel(hw,t)}var ud=U({log_:Qz});function eP(e){let t={x:O(e,"x","log1p")};return V.runKernel(pw,t)}var Jk=U({log1p_:eP});function tP(e){return L(Ss(e),()=>"The f passed in grad(f) must be a function"),(t,n)=>{let a=O(t,"x","tf.grad","string_or_numeric"),r=n!=null?O(n,"dy","tf.grad"):null;return V.tidy(()=>{let{value:s,grads:i}=V.gradients(()=>e(a),[a],r);return r!=null&&On(s.shape,r.shape,"The shape of dy passed in grad(f)(x, dy) must match the shape returned by f(x)"),Ic(i),i[0]})}}function nP(e){return L(Ss(e),()=>"The f passed in grads(f) must be a function"),(t,n)=>{L(Array.isArray(t),()=>"The args passed in grads(f)(args) must be an array of `Tensor`s or `TensorLike`s");let a=rd(t,"args","tf.grads","string_or_numeric"),r=n!=null?O(n,"dy","tf.grads"):null;return V.tidy(()=>{let{value:s,grads:i}=V.gradients(()=>e(...a),a,r);return r!=null&&On(s.shape,r.shape,"The shape of dy passed in grads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Ic(i),i})}}function aP(e){return L(Ss(e),()=>"The f passed in valueAndGrad(f) must be a function"),(t,n)=>{L(t instanceof St,()=>"The x passed in valueAndGrad(f)(x) must be a tensor"),L(n==null||n instanceof St,()=>"The dy passed in valueAndGrad(f)(x, dy) must be a tensor");let{grads:a,value:r}=V.gradients(()=>e(t),[t],n);return Ic(a),{grad:a[0],value:r}}}function rP(e){return L(Ss(e),()=>"The f passed in valueAndGrads(f) must be a function"),(t,n)=>{L(Array.isArray(t)&&t.every(r=>r instanceof St),()=>"The args passed in valueAndGrads(f)(args) must be array of tensors"),L(n==null||n instanceof St,()=>"The dy passed in valueAndGrads(f)(args, dy) must be a tensor");let a=V.gradients(()=>e(...t),t,n);return n!=null&&On(a.value.shape,n.shape,"The shape of dy passed in valueAndGrads(f)([x1,...], dy) must match the shape returned by f([x1,...])"),Ic(a.grads),a}}function Qk(e,t){L(Ss(e),()=>"The f passed in variableGrads(f) must be a function"),L(t==null||Array.isArray(t)&&t.every(u=>u instanceof ad),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let n=t!=null;if(!n){t=[];for(let u in V.registeredVariables)t.push(V.registeredVariables[u])}let a=n?t.filter(u=>!u.trainable):null,r=t.length;t=t.filter(u=>u.trainable),L(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${r} variables is trainable.`);let s=!0,{value:i,grads:o}=V.gradients(e,t,null,s);L(o.some(u=>u!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),L(i.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${i.rank} tensor`);let l={};return t.forEach((u,d)=>{o[d]!=null&&(l[u.name]=o[d])}),a!=null&&a.forEach(u=>l[u.name]=null),{value:i,grads:l}}function Nr(e){return V.customGrad(e)}function Ic(e){if(e.filter(t=>t==null).length>0)throw new Error(`Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.`)}function sP(e){let t={x:O(e,"x","neg")};return V.runKernel(Cw,t)}var Ms=U({neg_:sP});function iP(e){let t={x:O(e,"x","softplus")};return V.runKernel(i7,t)}var e6=U({softplus_:iP});function oP(e){let t=O(e,"x","logSigmoid");return Nr(n=>({value:Ms(e6(Ms(n))),gradFunc:a=>fe(a,Sr(Ms(n)))}))(t)}var lP=U({logSigmoid_:oP});function uP(e,t=null,n=!1){let a={x:O(e,"x","max")},r={reductionIndices:t,keepDims:n};return V.runKernel(yw,a,r)}var $s=U({max_:uP});function dP(e,t){let n=O(e,"a","sub"),a=O(t,"b","sub");[n,a]=Vt(n,a);let r={a:n,b:a};return V.runKernel(w7,r)}var je=U({sub_:dP});function hP(e,t=null,n=!1){let a=O(e,"x","sum");a.dtype==="bool"&&(a=zt(a,"int32"));let r={x:a},s={axis:t,keepDims:n};return V.runKernel(l7,r,s)}var $t=U({sum_:hP});function pP(e,t=-1){let n=O(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 Nr((a,r)=>{let s=!0,i=$s(a,t,!0),o=je(a,i),l=je(zt(o,"float32"),ud($t(vi(o),t,s)));return r([l]),{value:l,gradFunc:(u,d)=>{let[h]=d,p=!0,c=vi(h);return je(u,fe($t(u,t,p),c))}}})(n)}var cP=U({logSoftmax_:pP});function a1(e,t){for(let n=0;ne[s]);return[n,r]}function dd(e,t){let n=t.map(a=>1);return t6(e,n,t)}function mP(e,t,n){L(a1(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function gP(e,t){if(a1(e,t))return null;let n=[];for(let a=0;an.push(a)),n}function yP(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function AP(e,t){let n=[];for(let a=t-e;a`Error in maxPool: input must be rank 4 but got rank ${o.rank}.`),L(Jr(n,i),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`),r!=null&&L(Zn(a),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${r} but got pad ${a}.`);let u={x:o},d={filterSize:t,strides:n,pad:a,dimRoundingMode:r},h=V.runKernel(xw,u,d);return l?le(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var s6=U({maxPool_:SP});function NP(e,t=[1,1,1],n,a,r,s="NDHWC"){let i=O(e,"x","maxPool3d"),o=i,l=!1;i.rank===4&&(l=!0,o=le(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),L(o.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${o.rank}.`),L(s==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),r!=null&&L(Zn(a),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${a}.`);let u={x:o},d={filterSize:t,strides:n,pad:a,dimRoundingMode:r,dataFormat:s},h=V.runKernel(bw,u,d);return l?le(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var TP=U({maxPool3d_:NP});function EP(e,t,n,a,r=!1){let s={x:O(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:a,includeBatchInIndex:r},o=V.runKernel(vw,s,i);return{result:o[0],indexes:o[1]}}var CP=U({maxPoolWithArgmax_:EP});function MP(e,t){let n=O(e,"a","maximum"),a=O(t,"b","maximum");[n,a]=Vt(n,a),n.dtype==="bool"&&(n=zt(n,"int32"),a=zt(a,"int32")),In(n.shape,a.shape);let r={a:n,b:a};return V.runKernel(Aw,r)}var i6=U({maximum_:MP});function $P(e,t=null,n=!1){let a={x:O(e,"x","mean")},r={axis:t,keepDims:n};return V.runKernel(ww,a,r)}var Nc=U({mean_:$P});function Go(e,t="float32"){if(t==="complex64"){let a=Go(e,"float32"),r=Go(e,"float32");return mi(a,r)}let n=nc(Jt(e),t);return V.makeTensor(n,e,t)}function wi(e,t="float32"){if(t==="complex64"){let a=wi(e,"float32"),r=Go(e,"float32");return mi(a,r)}let n=ny(Jt(e),t);return V.makeTensor(n,e,t)}function RP(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 a=O(e,"x","meshgrid",e instanceof St?e.dtype:"float32");if(t===void 0)return[a];let r=O(t,"y","meshgrid",t instanceof St?t.dtype:"float32"),s=Jt(a.shape),i=Jt(r.shape);return n==="xy"?(a=le(a,[1,-1]),r=le(r,[-1,1]),[yt(wi([i,1],a.dtype),a),yt(r,wi([1,s],r.dtype))]):(a=le(a,[-1,1]),r=le(r,[1,-1]),[yt(a,wi([1,i],a.dtype)),yt(wi([s,1],r.dtype),r)])}function FP(e,t=null,n=!1){let a={x:O(e,"x","min")},r={axis:t,keepDims:n};return V.runKernel(kw,a,r)}var r1=U({min_:FP});function OP(e,t){let n=O(e,"a","minimum"),a=O(t,"b","minimum");[n,a]=Vt(n,a),n.dtype==="bool"&&(n=zt(n,"int32"),a=zt(a,"int32")),In(n.shape,a.shape);let r={a:n,b:a};return V.runKernel(Iw,r)}var o6=U({minimum_:OP});function DP(e,t,n){L(n==="reflect"||n==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);let a=O(e,"x","mirrorPad");if(a.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");L(t.length===a.rank,()=>`Padding doesn't match input. Must be ${a.rank}. Got ${t.length}.`);let r=n==="reflect"?1:0;for(let o=0;o"Invalid number of paddings. Must be length of 2 each."),L(t[o][0]>=0&&t[o][0]<=a.shape[o]-r&&t[o][1]>=0&&t[o][1]<=a.shape[o]-r,()=>`Padding in dimension ${o} cannot be greater than or equal to ${a.shape[o]-r} or less than 0 for input of shape ${a.shape}`);let s={paddings:t,mode:n},i={x:a};return V.runKernel(Sw,i,s)}var _P=U({mirrorPad_:DP});function zP(e,t){let n=O(e,"a","mod"),a=O(t,"b","mod");[n,a]=Vt(n,a);let r={a:n,b:a};return V.runKernel(Nw,r)}var PP=U({mod_:zP});function LP(e){let t=O(e,"x","square"),n={};return V.runKernel("Square",{x:t},n)}var tr=U({square_:LP});function WP(e,t=null,n=!1){e=O(e,"x","moments");let a=Xu(t,e.shape),r=Nc(e,a,n),s=r.shape;n||(s=dd(r.shape,a));let i=tr(je(zt(e,"float32"),le(r,s))),o=Nc(i,a,n);return{mean:r,variance:o}}var BP=U({moments_:WP});function VP(e,t,n,a){let r=O(t,"data","multiRNNCell"),s=rd(n,"c","multiRNNCell"),i=rd(a,"h","multiRNNCell"),o=r,l=[];for(let h=0;h2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${i}`);n=n||Math.random();let o={logits:i===1?le(r,[1,-1]):r},l={numSamples:t,seed:n,normalized:a},u=V.runKernel(Tw,o,l);return i===1?le(u,[u.size]):u}var HP=U({multinomial_:jP});function GP(e,t){let n=O(e,"a","notEqual","string_or_numeric"),a=O(t,"b","notEqual","string_or_numeric");[n,a]=Vt(n,a),In(n.shape,a.shape);let r={a:n,b:a};return V.runKernel(Mw,r)}var l6=U({notEqual_:GP});function qP(e){let t={x:O(e,"x","onesLike")};return V.runKernel(Ow,t)}var KP=U({onesLike_:qP});function XP(e,t){let n=O(e,"v1","outerProduct"),a=O(t,"v2","outerProduct");L(n.rank===1&&a.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${a.rank}.`);let r=le(n,[-1,1]),s=le(a,[1,-1]);return yt(r,s)}var ZP=U({outerProduct_:XP});function YP(e,t,n=0){let a=O(e,"x","pad");if(a.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");let r={paddings:t,constantValue:n},s={x:a};return V.runKernel(zw,s,r)}var hd=U({pad_:YP});function JP(e,t,n=0){return L(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),hd(e,[t],n)}var QP=U({pad1d_:JP});function eL(e,t,n=0){return L(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),hd(e,t,n)}var tL=U({pad2d_:eL});function nL(e,t,n=0){return L(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."),hd(e,t,n)}var aL=U({pad3d_:nL});function rL(e,t,n=0){return L(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."),hd(e,t,n)}var sL=U({pad4d_:rL});function iL(e,t,n){let a=O(e,"x","spaceToBatchND");L(a.rank>=1+t.length,()=>`input rank ${a.rank} should be > than [blockShape] ${t.length}`),L(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),L(a.shape.reduce((i,o,l)=>l>0&&l<=t.length?i&&(o+n[l-1][0]+n[l-1][1])%t[l-1]==0:i,!0),()=>`input spatial dimensions ${a.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);let r={x:a},s={blockShape:t,paddings:n};return V.runKernel(u7,r,s)}var u6=U({spaceToBatchND_:iL});function oL(e,t,n,a,r,s){r==null&&(r=[1,1]),s==null&&(s=1),a===0&&(a="valid");let i=O(e,"x","maxPool"),o=i,l=!1;i.rank===3&&(l=!0,o=le(i,[1,i.shape[0],i.shape[1],i.shape[2]])),L(Jr(s,r),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${r}'`);let u=zk(o.shape,t,s,r,a),d=[u.dilationHeight,u.dilationWidth],h;a==="same"?h=uL([u.filterHeight,u.filterWidth],d):h=[[0,0],[0,0]];let p=d[0]===1&&d[1]===1,[c,m]=lL([u.inHeight,u.inWidth],d,h),f=p?a:"valid",g=p?o:u6(o,d,c),y=(n==="avg"?()=>Wk(g,t,s,f):()=>s6(g,t,s,f))(),A=p?y:Bk(y,d,m);return l?le(A,[A.shape[1],A.shape[2],A.shape[3]]):A}function lL(e,t,n){let a=n.map(d=>d[0]),r=n.map(d=>d[1]),s=e.concat(a,r),i=t.map((d,h)=>(d-s[h]%d)%d),o=r.map((d,h)=>d+i[h]),l=t.map((d,h)=>[a[h],o[h]]),u=t.map((d,h)=>[0,i[h]]);return[l,u]}function uL(e,t){let n=e.map((s,i)=>s+(s-1)*(t[i]-1)).map(s=>s-1),a=n.map(s=>Math.floor(s/2)),r=n.map((s,i)=>s-a[i]);return n.map((s,i)=>[a[i],r[i]])}var dL=U({pool_:oL});function hL(e,t){let n=O(e,"base","pow"),a=O(t,"exp","pow");[n,a]=Vt(n,a);let r={a:n,b:a};return V.runKernel(Pw,r)}var pd=U({pow_:hL});function pL(e,t){let n=O(e,"x","prelu"),a=O(t,"alpha","prelu"),r={x:n,alpha:a};return V.runKernel(Lw,r)}var d6=U({prelu_:pL});function cL(e,t=null,n=!1){let a=O(e,"x","prod");a.dtype==="bool"&&(a=zt(a,"int32"));let r={x:a},s={axis:t,keepDims:n};return V.runKernel(Ww,r,s)}var fL=U({prod_:cL});function mL(e,t,n){let a=Jt(e),r=null;if(n==null||n==="float32")r=new Float32Array(a);else if(n==="int32")r=new Int32Array(a);else if(n==="bool")r=new Uint8Array(a);else throw new Error(`Unknown data type ${n}`);for(let s=0;s=1||s===0);let i=Math.sqrt(-2*Math.log(s)/s);e=this.mean+this.stdDev*a*i,t=this.mean+this.stdDev*r*i,(!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}},yL=class{constructor(e,t,n,a){this.alpha=e,this.beta=1/t,this.dtype=n;let r=a||Math.random();this.randu=s1.alea(r.toString()),this.randn=new i1(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,a,r,s;for(;;){do a=this.randn.nextValue(),s=1+this.c*a;while(s<=0);if(s*=s*s,e=a*a,t=1-.331*e*e,n=.5*e+this.d*(1-s+Math.log(s)),r=this.randu(),rthis.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=n,a==null&&(a=Math.random()),typeof a=="number"&&(a=a.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=s1.alea(a)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function xL(e,t,n=1,a="float32",r){if(n==null&&(n=1),a==null&&(a="float32"),a!=="float32"&&a!=="int32")throw new Error(`Unsupported data type ${a}`);let s=new yL(t,n,a,r),i=Zr(e,a);for(let o=0;o`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),ki(t,0)}var $L=U({reverse1d_:ML});function RL(e,t){let n=O(e,"x","reverse");return L(n.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),ki(n,t)}var FL=U({reverse2d_:RL});function OL(e,t){let n=O(e,"x","reverse");return L(n.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),ki(n,t)}var DL=U({reverse3d_:OL});function _L(e,t){let n=O(e,"x","reverse");return L(n.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),ki(n,t)}var zL=U({reverse4d_:_L});function PL(e){let t={x:O(e,"x","round")};return V.runKernel(Zw,t)}var c6=U({round_:PL});function LL(e){let t={x:O(e,"x","rsqrt")};return V.runKernel(Yw,t)}var WL=U({rsqrt_:LL});function dt(e,t){if((En(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"&&En(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return Ts(e,[],[],t)}function BL(e){let t={x:O(e,"x","selu")};return V.runKernel(e7,t)}var VL=U({selu_:BL});function UL(e,t,n,a,r,s=[1,1],i="NHWC"){let o=O(e,"x","separableConv2d"),l=O(t,"depthwiseFilter","separableConv2d"),u=O(n,"pointwiseFilter","separableConv2d"),d=o,h=!1;if(o.rank===3&&(h=!0,d=le(o,[1,o.shape[0],o.shape[1],o.shape[2]])),i==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");L(d.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${d.rank}.`),L(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),L(u.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),L(u.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${u.shape[0]}.`),L(u.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${u.shape[1]}.`);let p=l.shape[2],c=l.shape[3];L(u.shape[2]===p*c,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${p*c}, but got ${u.shape[2]}.`);let m=e1(d,l,a,r,i,s),f=bc(m,u,1,"valid",i);return h?le(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var jL=U({separableConv2d_:UL});async function HL(e,t){let n=O(e,"x","setdiff1d"),a=O(t,"y","setdiff1d");L(n.dtype===a.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${a.dtype}).`),L(n.rank===1,()=>`x should be 1D tensor, but got x (${n.shape}).`),L(a.rank===1,()=>`y should be 1D tensor, but got y (${a.shape}).`);let r=await n.data(),s=await a.data(),i=new Set(s),o=0;for(let d=0;d`slice1d expects a rank-1 tensor, but got a rank-${a.rank} tensor`),Ze(a,[t],[n])}var eW=U({slice1d_:QL});function tW(e,t,n){let a=O(e,"x","slice2d");return L(a.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${a.rank} tensor`),Ze(a,t,n)}var nW=U({slice2d_:tW});function aW(e,t,n){let a=O(e,"x","slice3d");return L(a.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${a.rank} tensor`),Ze(a,t,n)}var rW=U({slice3d_:aW});function sW(e,t,n){let a=O(e,"x","slice4d");return L(a.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${a.rank} tensor`),Ze(a,t,n)}var iW=U({slice4d_:sW});function oW(e,t=-1){let n=O(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 a={logits:n},r={dim:t};return V.runKernel(h7,a,r)}var lW=U({softmax_:oW});function uW(e){L(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);let t={input:e};return V.runKernel(Gv,t)}var o1=U({fft_:uW});function dW(e){L(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);let t={input:e};return V.runKernel(nw,t)}var Cc=U({ifft_:dW});function hW(e){let t=e.shape[e.shape.length-1],n=e.size/t,a;if(t<=2){let r=le(e,[n,t]);a=Cc(r)}else{let r=[n,2*(t-1)],s=le(Tc(e),[n,t]),i=le(t1(e),[n,t]),o=ki(Ze(s,[0,1],[n,t-2]),1),l=fe(ki(Ze(i,[0,1],[n,t-2]),1),dt(-1)),u=sn([s,o],1),d=sn([i,l],1),h=le(mi(u,d),[r[0],r[1]]);a=Cc(h)}if(a=Tc(a),e.rank===3&&e.shape[0]!==0){let r=a,s=e.shape[0];a=le(a,[s,a.shape[0]/s,a.shape[1]]),r.dispose()}return a}var f6=U({irfft_:hW});function pW(e,t,n=0){let a={x:O(e,"x","split")},r={numOrSizeSplits:t,axis:n};return V.runKernel(d7,a,r)}var es=U({split_:pW});function cW(e,t){L(e.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let n=e.shape[e.shape.length-1],a=e.size/n,r;if(t!=null&&t0),f=e.shape.map(g=>g);f[e.shape.length-1]=t,r=Ze(e,m,f),n=t}else if(t!=null&&t>n){let m=e.shape.map(f=>f);m[e.shape.length-1]=t-n,r=sn([e,Go(m)],e.shape.length-1),n=t}else r=e;let s=Na(r),i=le(mi(r,s),[a,n]),o=o1(i),l=Math.floor(n/2)+1,u=Tc(o),d=t1(o),h=es(u,[l,n-l],u.shape.length-1),p=es(d,[l,n-l],d.shape.length-1),c=r.shape.slice();return c[r.shape.length-1]=l,le(mi(h[0],p[0]),c)}var l1=U({rfft_:cW});function fW(e){let t={x:O(e,"x","sqrt")};return V.runKernel(o7,t)}var ts=U({sqrt_:fW});function mW(e,t){let n=O(e,"a","squaredDifference"),a=O(t,"b","squaredDifference");[n,a]=Vt(n,a),In(n.shape,a.shape);let r={a:n,b:a},s={};return V.runKernel(y7,r,s)}var m6=U({squaredDifference_:mW});function gW(e,t){let n=O(e,"x","squeeze");return le(n,B3(n.shape,t).newShape)}var Yn=U({squeeze_:gW});function yW(e,t=0){let n=rd(e,"tensors","stack","string_or_numeric");L(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length>0&&L(t<=n[0].rank,()=>"Axis must be <= rank of the tensor");let a=n,r={axis:t};return V.runKernel(_w,a,r)}var Ii=U({stack_:yW});function AW(e,t=0){let n={x:O(e,"x","step")},a={alpha:t};return V.runKernel(R7,n,a)}var g6=U({step_:AW});function xW(e,t,n,a,r=0,s=0,i=0,o=0,l=0){let u={x:O(e,"x","stridedSlice","string_or_numeric")},d={begin:t,end:n,strides:a,beginMask:r,endMask:s,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};return V.runKernel(A7,u,d)}var bW=U({stridedSlice_:xW});function vW(e){let t={x:O(e,"x","tan")};return V.runKernel(k7,t)}var wW=U({tan_:vW});function oa(e,t){hi(e);let n=Ir(e,t);if(n.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return Ts(e,null,n,t)}function ns(e,t,n){if(hi(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let a=Ir(e,n);if(a.length!==2&&a.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return Ts(e,t,a,n)}function kW(e,t,n){if(hi(e),t!=null&&t.length!==4)throw new Error("tensor4d() requires shape to have four numbers");let a=Ir(e,n);if(a.length!==4&&a.length!==1)throw new Error("tensor4d() requires values to be number[][][][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor4d() requires shape to be provided when `values` are a flat array");return Ts(e,t,a,n)}function IW(e,t,n){if(hi(e),t!=null&&t.length!==5)throw new Error("tensor5d() requires shape to have five numbers");let a=Ir(e,n);if(a.length!==5&&a.length!==1)throw new Error("tensor5d() requires values to be number[][][][][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor5d() requires shape to be provided when `values` are a flat array");return Ts(e,t,a,n)}function SW(e,t,n){if(hi(e),t!=null&&t.length!==6)throw new Error("tensor6d() requires shape to have six numbers");let a=Ir(e,n);if(a.length!==6&&a.length!==1)throw new Error("tensor6d() requires values to be number[][][][][][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor6d() requires shape to be provided when `values` are a flat array");return t=t||a,Ts(e,t,a,n)}function NW(e,t=1,n=!0){let a=O(e,"x","topk");if(a.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let r=a.shape[a.shape.length-1];if(t>r)throw new Error(`'k' passed to topk() must be <= the last dimension (${r}) but got ${t}`);let s={x:a},i={k:t,sorted:n},[o,l]=V.runKernel(S7,s,i);return{values:o,indices:l}}var TW=U({topk_:NW});function EW(e,t=0,n=1,a,r){if(a!=null&&a==="bool")throw new Error("Unsupported data type $ { dtype }");let s=new i1(t,n,a,!0,r),i=Zr(e,a);for(let o=0;o0,()=>"The input tensor must be at least 1D");let a={x:n},r={axis:t},[s,i]=V.runKernel(E7,a,r);return{values:s,indices:i}}var $W=U({unique_:MW});function RW(e,t,n){let a=O(e,"x","unsortedSegmentSum"),r=O(t,"segmentIds","unsortedSegmentSum","int32");L(Zn(n),()=>"numSegments must be of dtype int");let s={x:a,segmentIds:r},i={numSegments:n};return V.runKernel(M7,s,i)}var FW=U({unsortedSegmentSum_:RW});function OW(e,t=0){let n=O(e,"x","unstack","string_or_numeric");L(t>=-n.shape.length&&t`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`);let a={value:n},r={axis:t};return V.runKernel(C7,a,r)}var fd=U({unstack_:OW});function DW(e,t=!0,n,a){return V.makeVariable(e,t,n,a)}function y6(e,t){let n=[];for(let s=0;s0,()=>"mask cannot be scalar"),On(o.slice(s,s+i),r.shape,"mask's shape must match the first K dimensions of tensor's shape,");let l=1;for(let f=s;f"Shape mismatch in v and x");let l=dt(1),u=je(l,o),d=fe(je(i,s),u);if(r){L(a!=null,()=>"When using zeroDebias: true, step is required.");let h=O(a,"step","movingAverage");d=Qe(d,je(l,pd(o,h)))}return De(s,d)}var BW=U({movingAverage_:WW});function VW(e,t,n){let a=O(e,"indices","scatterND","int32"),r=O(t,"updates","scatterND");Vy(r,a,n);let s={indices:a,updates:r},i={shape:n};return V.runKernel(Jw,s,i)}var UW=U({scatterND_:VW});function jW(e,t,n,a){if(e.dtype!=="int32")throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);let r=e.rank>0?e.shape[0]:1,s=e.rank>1?e.shape[1]:1;if(n.length!==s)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${s}.`);let i=t.size;if(!(t.rank===0||t.rank===1&&i===r))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${r}]`);if(t.dtype!==a.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function HW(e,t,n,a=0){let r=O(e,"sparseIndices","sparseToDense","int32"),s=O(t,"sparseValues","sparseToDense"),i=O(a,"defaultValue","sparseToDense",s.dtype);jW(r,s,n,i);let o={sparseIndices:r,sparseValues:s,defaultValue:i},l={outputShape:n};return V.runKernel(g7,o,l)}var GW=U({sparseToDense_:HW});function qW(e,t){let n=O(t,"indices","gatherND","int32"),a={params:O(e,"x","gatherND","string_or_numeric"),indices:n};return V.runKernel(Qv,a)}var KW=U({gatherND_:qW});function XW(e,t){if(t==null)return e.shape.slice();if(Kr(e.shape,t))return t;if(e.shape.length===t.length){let n=[];for(let a=0;a`x has to be a floating point tensor since it's going to be scaled, but got a ${r.dtype} tensor instead.`),L(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof St?r.clone():r;let s=XW(r,n),i=1-t,o=Qe(Kk(De(h6(s,0,1,"float32",a),i)),i);return fe(r,o)}var YW=U({dropout_:ZW});function b6(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function d1(e,t,n){let a=1-e%2,r=new Float32Array(e);for(let s=0;s1,()=>`inTopK() expects the predictions to be of rank 2 or higher, but got ${a.rank}`),L(a.rank-1===r.rank,()=>`predictions rank should be 1 larger than targets rank, but got predictions rank ${a.rank} and targets rank ${r.rank}`),On(a.shape.slice(0,a.shape.length-1),r.shape,"predictions's shape should be align with the targets' shape, except the last dimension.");let s=a.shape[a.shape.length-1];L(n>0&&n<=s,()=>`'k' passed to inTopK() must be > 0 && <= the predictions last dimension (${s}), but got ${n}`);let i=await a.data(),o=await r.data(),[l,u]=[i.length/s,s],d=V3("bool",l);for(let h=0;hg.value-f.value),d[h]=0;for(let f=0;faB,depthwiseConv2d:()=>uB,matMul:()=>hB});function eB(e,t,n,a,r,s="NHWC",i){let o=e;e.rank===3&&(o=le(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=le(t,[1,t.shape[0],t.shape[1],t.shape[2]])),L(o.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${o.shape}.`),L(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),L(n.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);let u=s==="NHWC"?o.shape[3]:o.shape[1],d=s==="NHWC"?l.shape[3]:l.shape[1];L(u===n[2],()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${n[2]}.`),L(d===n[3],()=>`Error in conv2dDerFilter: depth of dy (${d}) must match output depth for filter (${n[3]}).`),i!=null&&L(Zn(r),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${i} but got pad ${r}.`);let h={x:o,dy:l},p={strides:a,pad:r,dataFormat:s,dimRoundingMode:i,filterShape:n};return V.runKernel(kv,h,p)}var tB=U({conv2DBackpropFilter_:eB});function Mc(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return fe(e,g6(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function $c(e,t){let n=t,a=jk(e.shape,t.shape);return a.length>0&&(n=$t(n,a)),le(n,e.shape)}function Rc(e,t,n,a){if(t==="linear")return e;if(t==="relu")return Ec(e);if(t==="elu")return Gk(e);if(t==="relu6")return p6(e);if(t==="prelu")return d6(e,n);if(t==="leakyrelu")return Yk(e,a);if(t==="sigmoid")return Sr(e);throw new Error(`Unknown fused activation ${t}.`)}var Fc=(e,t)=>!(e>0)||t==="linear";function nB({x:e,filter:t,strides:n,pad:a,dataFormat:r="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:d}){if(l=l||"linear",Fc(V.state.gradientDepth,l)===!1){let b=bc(e,t,n,a,r,s,i);return o!=null&&(b=De(b,o)),Rc(b,l,u,d)}let h=O(e,"x","conv2d"),p=O(t,"filter","conv2d"),c=h,m=!1;h.rank===3&&(m=!0,c=le(h,[1,h.shape[0],h.shape[1],h.shape[2]])),L(c.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${c.rank}.`),L(p.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${p.rank}.`),i!=null&&L(Zn(a),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${a}.`),L(c.shape[3]===p.shape[2],()=>`Error in conv2d: depth of input (${c.shape[3]}) must match input depth for filter ${p.shape[2]}.`),L(Jr(n,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),L(r==="NHWC",()=>`Error in conv2d: got dataFormat of ${r} but only NHWC is currently supported.`);let f=id(c.shape,p.shape,n,s,a,i),g;o!=null&&(g=O(o,"bias","fused conv2d"),[g]=Vt(g,h),In(f.outShape,g.shape));let y;u!=null&&(y=O(u,"prelu weights","fused conv2d"));let A=(b,w)=>{let[I,T,C,z]=w,$=Mc(b,C,l);L(od(s),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let S=Uk(T.shape,$,I,n,a),D=tB(T,$,I.shape,n,a),_=[S,D];if(z!=null){let W=$c(z,$);_.push(W)}return _},x={x:c,filter:p,bias:g,preluActivationWeights:y},v={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:d};return o==null?Nr((b,w,I)=>{let T=V.runKernel(cy,x,v);return I([w,b,T]),m&&(T=le(T,[T.shape[1],T.shape[2],T.shape[3]])),{value:T,gradFunc:A}})(c,p):Nr((b,w,I,T)=>{let C=V.runKernel(cy,x,v);return T([w,b,C,I]),m&&(C=le(C,[C.shape[1],C.shape[2],C.shape[3]])),{value:C,gradFunc:A}})(c,p,g)}var aB=U({fusedConv2d_:nB});function rB(e,t,n,a,r,s=[1,1],i){let o=e;e.rank===3&&(o=le(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=le(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let u={x:o,dy:l},d={strides:a,pad:r,dimRoundingMode:i,dilations:s,filterShape:n};return V.runKernel(Ov,u,d)}var sB=U({depthwiseConv2dNativeBackpropFilter_:rB});function iB(e,t,n,a,r,s=[1,1],i){let o=t,l=!1;t.rank===3&&(l=!0,o=le(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let u={dy:o,filter:n},d={strides:a,pad:r,dimRoundingMode:i,dilations:s,inputShape:e},h=V.runKernel(Dv,u,d);return l?le(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var oB=U({depthwiseConv2dNativeBackpropInput_:iB});function lB({x:e,filter:t,strides:n,pad:a,dataFormat:r="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:d}){if(Fc(V.state.gradientDepth,l)===!1){let b=e1(e,t,n,a,r,s,i);return o!=null&&(b=De(b,o)),Rc(b,l,u,d)}let h=O(e,"x","depthwiseConv2d"),p=O(t,"filter","depthwiseConv2d"),c=h,m=!1;h.rank===3&&(m=!0,c=le(h,[1,h.shape[0],h.shape[1],h.shape[2]])),L(c.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`),L(p.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${p.rank}.`),L(c.shape[3]===p.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${c.shape[3]}) must match the inChannels dimension in filter ${p.shape[2]}.`),s==null&&(s=[1,1]),L(Jr(n,s),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),i!=null&&L(Zn(a),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${i} but got pad ${a}.`);let f=id(c.shape,p.shape,n,s,a,i,!0),g;o!=null&&(g=O(o,"bias","fused conv2d"),[g]=Vt(g,h),In(f.outShape,g.shape));let y;u!=null&&(y=O(u,"prelu weights","fused depthwiseConv2d"));let A=(b,w)=>{L(od(s),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);let[I,T,C,z]=w,$=Mc(b,C,l),S=oB(T.shape,$,I,n,a,s,i),D=sB(T,$,I.shape,n,a,s,i);if(z!=null){let _=$c(g,$);return[S,D,_]}return[S,D]},x={x:c,filter:p,bias:g,preluActivationWeights:y},v={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:d};return o==null?Nr((b,w,I)=>{let T=V.runKernel(fy,x,v);return I([w,b,T]),m&&(T=le(T,[T.shape[1],T.shape[2],T.shape[3]])),{value:T,gradFunc:A}})(c,p):Nr((b,w,I,T)=>{let C=V.runKernel(fy,x,v);return T([w,b,C,I]),m&&(C=le(C,[C.shape[1],C.shape[2],C.shape[3]])),{value:C,gradFunc:A}})(c,p,g)}var uB=U({fusedDepthwiseConv2d_:lB});function dB({a:e,b:t,transposeA:n=!1,transposeB:a=!1,bias:r,activation:s="linear",preluActivationWeights:i,leakyreluAlpha:o}){if(Fc(V.state.gradientDepth,s)===!1){let z=yt(e,t,n,a);return r!=null&&(z=De(z,r)),Rc(z,s,i,o)}let l=O(e,"a","fused matMul"),u=O(t,"b","fused matMul");[l,u]=Vt(l,u);let d=n?l.shape[l.rank-2]:l.shape[l.rank-1],h=a?u.shape[u.rank-1]:u.shape[u.rank-2],p=n?l.shape[l.rank-1]:l.shape[l.rank-2],c=a?u.shape[u.rank-2]:u.shape[u.rank-1],m=l.shape.slice(0,-2),f=u.shape.slice(0,-2),g=Jt(m),y=Jt(f);L(l.rank>=2&&u.rank>=2&&l.rank===u.rank,()=>`Error in fused matMul: inputs must have the same rank of at least 2, got ranks ${l.rank} and ${u.rank}.`),L(Kr(m,f),()=>`Error in fused matMul: outer dimensions (${m}) and (${f}) of Tensors with shapes ${l.shape} and ${u.shape} must match.`),L(d===h,()=>`Error in fused matMul: inner shapes (${d}) and (${h}) of Tensors with shapes ${l.shape} and ${u.shape} and transposeA=${n} and transposeB=${a} must match.`);let A=l.shape.slice(0,-2).concat([p,c]),x=n?le(l,[g,d,p]):le(l,[g,p,d]),v=a?le(u,[y,c,h]):le(u,[y,h,c]),b;r!=null&&(b=O(r,"bias","fused matMul"),[b]=Vt(b,l),In(A,b.shape));let w;i!=null&&(w=O(i,"prelu weights","fused matMul"));let I=(z,$)=>{let[S,D,_,W]=$,X=Mc(le(z,_.shape),_,s),q,Q;if(!n&&!a?(q=yt(X,D,!1,!0),Q=yt(S,X,!0,!1)):!n&&a?(q=yt(X,D,!1,!1),Q=yt(X,S,!0,!1)):n&&!a?(q=yt(D,X,!1,!0),Q=yt(S,X,!1,!1)):(q=yt(D,X,!0,!0),Q=yt(X,S,!0,!0)),r!=null){let ee=$c(W,X);return[q,Q,ee]}else return[q,Q]},T={a:x,b:v,bias:b,preluActivationWeights:w},C={transposeA:n,transposeB:a,activation:s,leakyreluAlpha:o};return r==null?Nr((z,$,S)=>{let D=V.runKernel(py,T,C);return S([z,$,D]),{value:le(D,A),gradFunc:I}})(x,v):Nr((z,$,S,D)=>{let _=V.runKernel(py,T,C);return D([z,$,_,S]),{value:le(_,A),gradFunc:I}})(x,v,b)}var hB=U({fusedMatMul_:dB});function pB(e){return d1(e,.54,.46)}var cB=U({hammingWindow_:pB});function fB(e){return d1(e,.5,.5)}var w6=U({hannWindow_:fB});function mB(e,t,n,a=!1,r=0){let s=0,i=[];for(;s+t<=e.size;)i.push(Ze(e,s,t)),s+=n;if(a)for(;s`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`),L(o.rank===2&&o.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${u},4] but had shape ${o.shape}.`),L(l.rank===1&&l.shape[0]===u,()=>`Error in cropAndResize: boxInd must be have size [${u}] but had shape ${o.shape}.`),L(a.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${a.length}.`),L(a[0]>=1&&a[1]>=1,()=>`cropSize must be atleast [1,1], but was ${a}`),L(r==="bilinear"||r==="nearest",()=>`method must be bilinear or nearest, but was ${r}`);let d={image:i,boxes:o,boxInd:l},h={method:r,extrapolationValue:s,cropSize:a};return V.runKernel(Mv,d,h)}var xB=U({cropAndResize_:AB});function bB(e){let t=O(e,"image","flipLeftRight","float32");L(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);let n={image:t};return V.runKernel(Kv,n,{})}var vB=U({flipLeftRight_:bB});function wB(e,t,n=0,a=.5){let r=O(e,"image","rotateWithOffset","float32");L(r.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${r.rank}.`);let s={image:r},i={radians:t,fillValue:n,center:a};return V.runKernel(F7,s,i)}var kB=U({rotateWithOffset_:wB});function qo(e,t,n,a,r,s){a==null&&(a=.5),r==null&&(r=Number.NEGATIVE_INFINITY),s==null&&(s=0);let i=e.shape[0];return n=Math.min(n,i),L(0<=a&&a<=1,()=>`iouThreshold must be in [0, 1], but was '${a}'`),L(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),L(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),L(t.rank===1,()=>"scores must be a 1D tensor"),L(t.shape[0]===i,()=>`scores has incompatible shape with boxes. Expected ${i}, but was ${t.shape[0]}`),L(0<=s&&s<=1,()=>`softNmsSigma must be in [0, 1], but was '${s}'`),{maxOutputSize:n,iouThreshold:a,scoreThreshold:r,softNmsSigma:s}}function IB(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY){let s=O(e,"boxes","nonMaxSuppression"),i=O(t,"scores","nonMaxSuppression"),o=qo(s,i,n,a,r);n=o.maxOutputSize,a=o.iouThreshold,r=o.scoreThreshold;let l={maxOutputSize:n,iouThreshold:a,scoreThreshold:r};return V.runKernel($w,{boxes:s,scores:i},l)}var SB=U({nonMaxSuppression_:IB});function NB(e,t,n){let a=TB(e,t,n),r=a<0?-(a+1):a;e.splice(r,0,t)}function TB(e,t,n){return CB(e,t,n||EB)}function EB(e,t){return e>t?1:e>>1);let o=n(t,e[s]);o>0?a=s+1:(r=s,i=!o)}return i?a:-a-1}function I6(e,t,n,a,r){return h1(e,t,n,a,r,0)}function S6(e,t,n,a,r,s){return h1(e,t,n,a,r,0,!1,s,!0)}function N6(e,t,n,a,r,s){return h1(e,t,n,a,r,s,!0)}function h1(e,t,n,a,r,s,i=!1,o=!1,l=!1){let u=[];for(let g=0;gr&&u.push({score:t[g],boxIndex:g,suppressBeginIndex:0});u.sort(T6);let d=s>0?-.5/s:0,h=[],p=[];for(;h.length0;){let g=u.pop(),{score:y,boxIndex:A,suppressBeginIndex:x}=g;if(y=x;--b){let w=MB(e,A,h[b]);if(w>=a){v=!0;break}if(g.score=g.score*$B(a,d,w),g.score<=r)break}g.suppressBeginIndex=h.length,v||(g.score===y?(h.push(A),p.push(g.score)):g.score>r&&NB(u,g,T6))}let c=h.length,m=n-c;o&&m>0&&(h.push(...new Array(m).fill(0)),p.push(...new Array(m).fill(0)));let f={selectedIndices:h};return i&&(f.selectedScores=p),l&&(f.validOutputs=c),f}function MB(e,t,n){let a=e.subarray(t*4,t*4+4),r=e.subarray(n*4,n*4+4),s=Math.min(a[0],a[2]),i=Math.min(a[1],a[3]),o=Math.max(a[0],a[2]),l=Math.max(a[1],a[3]),u=Math.min(r[0],r[2]),d=Math.min(r[1],r[3]),h=Math.max(r[0],r[2]),p=Math.max(r[1],r[3]),c=(o-s)*(l-i),m=(h-u)*(p-d);if(c<=0||m<=0)return 0;let f=Math.max(s,u),g=Math.max(i,d),y=Math.min(o,h),A=Math.min(l,p),x=Math.max(y-f,0)*Math.max(A-g,0);return x/(c+m-x)}function $B(e,t,n){let a=Math.exp(t*n*n);return n<=e?a:0}function T6(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function RB(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY){let s=O(e,"boxes","nonMaxSuppressionAsync"),i=O(t,"scores","nonMaxSuppressionAsync"),o=qo(s,i,n,a,r);n=o.maxOutputSize,a=o.iouThreshold,r=o.scoreThreshold;let l=await Promise.all([s.data(),i.data()]),u=l[0],d=l[1],{selectedIndices:h}=I6(u,d,n,a,r);return s!==e&&s.dispose(),i!==t&&i.dispose(),oa(h,"int32")}var FB=RB;function OB(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=0){let i=O(e,"boxes","nonMaxSuppression"),o=O(t,"scores","nonMaxSuppression"),l=qo(i,o,n,a,r,s);n=l.maxOutputSize,a=l.iouThreshold,r=l.scoreThreshold,s=l.softNmsSigma;let u={boxes:i,scores:o},d={maxOutputSize:n,iouThreshold:a,scoreThreshold:r,softNmsSigma:s},h=V.runKernel(Fw,u,d);return{selectedIndices:h[0],selectedScores:h[1]}}var DB=U({nonMaxSuppressionWithScore_:OB});async function _B(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=0){let i=O(e,"boxes","nonMaxSuppressionAsync"),o=O(t,"scores","nonMaxSuppressionAsync"),l=qo(i,o,n,a,r,s);n=l.maxOutputSize,a=l.iouThreshold,r=l.scoreThreshold,s=l.softNmsSigma;let u=await Promise.all([i.data(),o.data()]),d=u[0],h=u[1],{selectedIndices:p,selectedScores:c}=N6(d,h,n,a,r,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:oa(p,"int32"),selectedScores:oa(c)}}var zB=_B;function PB(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=!1){let i=O(e,"boxes","nonMaxSuppression"),o=O(t,"scores","nonMaxSuppression"),l=qo(i,o,n,a,r,null),u=l.maxOutputSize,d=l.iouThreshold,h=l.scoreThreshold,p={boxes:i,scores:o},c={maxOutputSize:u,iouThreshold:d,scoreThreshold:h,padToMaxOutputSize:s},m=V.runKernel(Rw,p,c);return{selectedIndices:m[0],validOutputs:m[1]}}var LB=U({nonMaxSuppressionPadded_:PB});async function WB(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=!1){let i=O(e,"boxes","nonMaxSuppressionAsync"),o=O(t,"scores","nonMaxSuppressionAsync"),l=qo(i,o,n,a,r,null),u=l.maxOutputSize,d=l.iouThreshold,h=l.scoreThreshold,[p,c]=await Promise.all([i.data(),o.data()]),{selectedIndices:m,validOutputs:f}=S6(p,c,u,d,h,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:oa(m,"int32"),validOutputs:dt(f,"int32")}}var BB=WB;function VB(e,t,n=!1,a=!1){let r=O(e,"images","resizeBilinear");L(r.rank===3||r.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${r.rank}.`),L(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),L(a===!1||n===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let s=r,i=!1;r.rank===3&&(i=!0,s=le(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,o={images:s},l={alignCorners:n,halfPixelCenters:a,size:t},u=V.runKernel(qw,o,l);return i?le(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var UB=U({resizeBilinear_:VB});function jB(e,t,n=!1,a=!1){let r=O(e,"images","resizeNearestNeighbor");L(r.rank===3||r.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${r.rank}.`),L(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),L(r.dtype==="float32"||r.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),L(a===!1||n===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let s=r,i=!1;r.rank===3&&(i=!0,s=le(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,o={images:s},l={alignCorners:n,halfPixelCenters:a,size:t},u=V.runKernel(Gw,o,l);return i?le(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var HB=U({resizeNearestNeighbor_:jB});function GB(e,t="binary",n=!1,a=.5){let r=O(e,"image","threshold"),s=.2989,i=.587,o=.114,l=r.shape[0]*r.shape[1],u=fe(oa([a]),255),d,h,p,c;if(L(r.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${r.rank}.`),L(r.shape[2]===3||r.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${r.shape[2]}.`),L(r.dtype==="int32"||r.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${r.dtype}.`),L(t==="otsu"||t==="binary",()=>`Method must be binary or otsu, but was ${t}`),r.shape[2]===3){[d,h,p]=es(r,[1,1,1],-1);let f=fe(d,s),g=fe(h,i),y=fe(p,o);c=De(De(f,g),y)}else c=e;if(t==="otsu"){let f=Vk(zt(c6(c),"int32"),er([]),256);u=qB(f,l)}let m=n?n1(c,u):kc(c,u);return zt(fe(m,255),"int32")}function qB(e,t){let n=oa([-1]),a=oa([0]),r=oa([0]),s,i,o,l,u,d;for(let h=0;h`Error in transform: image must be rank 4,but got rank ${i.rank}.`),L(o.rank===2&&(o.shape[0]===i.shape[0]||o.shape[0]===1)&&o.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),L(s==null||s.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${s}.`);let l={image:i,transforms:o},u={interpolation:n,fillMode:a,fillValue:r,outputShape:s};return V.runKernel(N7,l,u)}var ZB=U({transform_:XB});function YB(e,t,n){L(t%1==0,()=>`bandPart(): numLower must be an integer, got ${t}.`),L(n%1==0,()=>`bandPart(): numUpper must be an integer, got ${n}.`);let a=O(e,"a","bandPart");L(a.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${a.rank}.`);let r=a.shape,[s,i]=a.shape.slice(-2);if(!(t<=s))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${s}).`);if(!(n<=i))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${i}).`);t<0&&(t=s),n<0&&(n=i);let o=le(cd(0,s,1,"int32"),[-1,1]),l=cd(0,i,1,"int32"),u=je(o,l),d=Sc(n1(u,dt(+t,"int32")),Zk(u,dt(-n,"int32"))),h=Go([s,i],a.dtype);return le(Ii(fd(le(a,[-1,s,i])).map(p=>Ho(d,p,h))),r)}var JB=U({bandPart_:YB});function QB(e){let t;if(Array.isArray(e)){t=!1,L(e!=null&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");let r=e[0].shape[0];for(let s=1;s`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[s].shape[0]} vs. ${r})`)}else t=!0,e=es(e,e.shape[0],0).map(r=>Yn(r,[0]));L(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);let n=[],a=e;for(let r=0;r{let s=a[r];if(r>0)for(let i=0;i=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return E6(e,t);{let n=e.shape.slice(0,e.shape.length-2).reduce((l,u)=>l*u),a=fd(le(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),r=[],s=[];a.forEach(l=>{let[u,d]=E6(l,t);r.push(u),s.push(d)});let i=le(Ii(r,0),e.shape),o=le(Ii(s,0),e.shape);return[i,o]}}function E6(e,t=!1){return V.tidy(()=>{L(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);let n=e.shape[0],a=e.shape[1],r=qk(n),s=Yr(e),i=ns([[1]],[1,1]),o=Yr(i),l=n>=a?a:n;for(let u=0;u{let c=Ze(s,[u,u],[n-u,1]),m=u1(c),f=Ze(s,[u,u],[1,1]),g=Ho(kc(f,0),ns([[-1]]),ns([[1]])),y=je(f,fe(g,m)),A=Qe(c,y);A.shape[0]===1?o=Yr(i):o=sn([i,Ze(A,[1,0],[A.shape[0]-1,A.shape[1]])],0);let x=Ms(Qe(yt(g,y),m)),v=Ze(s,[u,0],[n-u,a]),b=fe(x,o),w=fc(o);if(u===0)s=je(v,yt(b,yt(w,v)));else{let C=je(v,yt(b,yt(w,v)));s=sn([Ze(s,[0,0],[u,a]),C],0)}let I=fc(b),T=Ze(r,[0,u],[n,r.shape[1]-u]);if(u===0)r=je(T,yt(yt(T,o),I));else{let C=je(T,yt(yt(T,o),I));r=sn([Ze(r,[0,0],[n,u]),C],1)}return[o,s,r]}),Ve([d,h,p])}return!t&&n>a&&(r=Ze(r,[0,0],[n,a]),s=Ze(s,[0,0],[a,a])),[r,s]})}var nV=U({qr_:tV}),_n;(function(e){e[e.NONE=0]="NONE",e[e.MEAN=1]="MEAN",e[e.SUM=2]="SUM",e[e.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"})(_n||(_n={}));function aV(e,t,n=_n.SUM_BY_NONZERO_WEIGHTS){let a=O(e,"losses","computeWeightedLoss"),r=null;t!=null&&(r=O(t,"weights","computeWeightedLoss"));let s=r==null?a:fe(a,r);if(n===_n.NONE)return s;if(n===_n.SUM)return $t(s);if(n===_n.MEAN){if(r==null)return Nc(s);{let i=a.size/r.size,o=Qe($t(s),$t(r));return i>1?Qe(o,dt(i)):o}}if(n===_n.SUM_BY_NONZERO_WEIGHTS){if(r==null)return Qe($t(s),dt(a.size));{let i=fe(r,wi(a.shape)),o=zt($t(l6(i,dt(0))),"float32");return Qe($t(s),o)}}throw Error(`Unknown reduction: ${n}`)}var as=U({computeWeightedLoss_:aV});function rV(e,t,n,a=_n.SUM_BY_NONZERO_WEIGHTS){let r=O(e,"labels","absoluteDifference"),s=O(t,"predictions","absoluteDifference"),i=null;n!=null&&(i=O(n,"weights","absoluteDifference")),On(r.shape,s.shape,"Error in absoluteDifference: ");let o=Sa(je(r,s));return as(o,i,a)}var sV=U({absoluteDifference_:rV});function iV(e,t,n,a,r=_n.SUM_BY_NONZERO_WEIGHTS){let s=O(e,"labels","cosineDistance"),i=O(t,"predictions","cosineDistance"),o=null;a!=null&&(o=O(a,"weights","cosineDistance")),On(s.shape,i.shape,"Error in cosineDistance: ");let l=dt(1),u=je(l,$t(fe(s,i),n,!0));return as(u,o,r)}var oV=U({cosineDistance_:iV});function lV(e,t,n,a=_n.SUM_BY_NONZERO_WEIGHTS){let r=O(e,"labels","hingeLoss"),s=O(t,"predictions","hingeLoss"),i=null;n!=null&&(i=O(n,"weights","hingeLoss")),On(r.shape,s.shape,"Error in hingeLoss: ");let o=dt(1);r=je(fe(dt(2),r),o);let l=Ec(je(o,fe(r,s)));return as(l,i,a)}var uV=U({hingeLoss_:lV});function dV(e,t,n,a=1,r=_n.SUM_BY_NONZERO_WEIGHTS){let s=O(e,"labels","huberLoss"),i=O(t,"predictions","huberLoss"),o=null;n!=null&&(o=O(n,"weights","huberLoss")),On(s.shape,i.shape,"Error in huberLoss: ");let l=dt(a),u=Sa(je(i,s)),d=o6(u,l),h=je(u,d),p=De(fe(dt(.5),tr(d)),fe(l,h));return as(p,o,r)}var hV=U({huberLoss_:dV});function pV(e,t,n,a=1e-7,r=_n.SUM_BY_NONZERO_WEIGHTS){let s=O(e,"labels","logLoss"),i=O(t,"predictions","logLoss"),o=null;n!=null&&(o=O(n,"weights","logLoss")),On(s.shape,i.shape,"Error in logLoss: ");let l=dt(1),u=dt(a),d=Ms(fe(s,ud(De(i,u)))),h=fe(je(l,s),ud(De(je(l,i),u))),p=je(d,h);return as(p,o,r)}var cV=U({logLoss_:pV});function fV(e,t,n,a=_n.SUM_BY_NONZERO_WEIGHTS){let r=O(e,"labels","meanSquaredError"),s=O(t,"predictions","meanSquaredError"),i=null;n!=null&&(i=O(n,"weights","meanSquaredError")),On(r.shape,s.shape,"Error in meanSquaredError: ");let o=m6(r,s);return as(o,i,a)}var mV=U({meanSquaredError_:fV});function gV(e,t){let n=O(e,"labels","sigmoidCrossEntropyWithLogits"),a=O(t,"logits","sigmoidCrossEntropyWithLogits");On(n.shape,a.shape,"Error in sigmoidCrossEntropyWithLogits: ");let r=Ec(a),s=fe(a,n),i=Jk(vi(Ms(Sa(a))));return De(je(r,s),i)}function yV(e,t,n,a=0,r=_n.SUM_BY_NONZERO_WEIGHTS){let s=O(e,"multiClassLabels","sigmoidCrossEntropy"),i=O(t,"logits","sigmoidCrossEntropy"),o=null;if(n!=null&&(o=O(n,"weights","sigmoidCrossEntropy")),On(s.shape,i.shape,"Error in sigmoidCrossEntropy: "),a>0){let u=dt(a),d=dt(1),h=dt(.5);s=De(fe(s,je(d,u)),fe(h,u))}let l=gV(s,i);return as(l,o,r)}var AV=U({sigmoidCrossEntropy_:yV});function xV(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 Nr((a,r,s)=>{let i=n6(r,[n],!0),o=je(zt(r,"float32"),i);s([a,o]);let l=Ms(fe(o,a));return{value:$t(l,[n]),gradFunc:(u,d)=>{let[h,p]=d,c=dd(u.shape,[n]);return[fe(le(u,c),je(zt(h,"float32"),vi(p))),fe(le(u,c),je(vi(p),zt(h,"float32")))]}}})(e,t)}function bV(e,t,n,a=0,r=_n.SUM_BY_NONZERO_WEIGHTS){let s=O(e,"onehotLabels","softmaxCrossEntropy"),i=O(t,"logits","softmaxCrossEntropy"),o=null;if(n!=null&&(o=O(n,"weights","softmaxCrossEntropy")),On(s.shape,i.shape,"Error in softmaxCrossEntropy: "),a>0){let u=dt(a),d=dt(1),h=dt(s.shape[1]);s=De(fe(s,je(d,u)),Qe(u,h))}let l=xV(s,i);return as(l,o,r)}var vV=U({softmaxCrossEntropy_:bV});function wV(e,t,n,a){let r=O(e,"indices","sparseFillEmptyRows"),s=O(t,"values","sparseFillEmptyRows"),i=O(n,"denseShape","sparseFillEmptyRows"),o=O(a,"defaultValue","sparseFillEmptyRows",s.dtype);if(r.rank!==2)throw new Error(`Indices should be Tensor2D but received shape ${r.shape}`);if(s.rank!==1)throw new Error(`Values should be Tensor1D but received shape ${s.shape}`);if(i.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${i.shape}`);if(o.rank!==0)throw new Error(`Default value should be a scalar but received shape ${o.shape}`);let l={indices:r,values:s,denseShape:i,defaultValue:o},u=V.runKernel(p7,l);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}var kV=U({sparseFillEmptyRows_:wV});function IV(e,t,n){let a=O(e,"inputIndices","sparseReshape"),r=O(t,"inputShape","sparseReshape"),s=O(n,"newShape","sparseReshape");if(a.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape ${a.shape}`);if(r.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${r.shape}`);if(s.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${s.shape}`);let i={inputIndices:a,inputShape:r,newShape:s},o=V.runKernel(c7,i);return{outputIndices:o[0],outputShape:o[1]}}var SV=U({sparseReshape_:IV});function NV(e,t,n){let a=O(e,"data","sparseSegmentMean"),r=O(t,"indices","sparseSegmentMean"),s=O(n,"segmentIds","sparseSegmentMean");if(a.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.rank!==1)throw new Error(`Indices should be Tensor1D but received shape ${r.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape ${s.shape}`);let i={data:a,indices:r,segmentIds:s};return V.runKernel(f7,i)}var TV=U({sparseSegmentMean_:NV});function EV(e,t,n){let a=O(e,"data","sparseSegmentSum"),r=O(t,"indices","sparseSegmentSum"),s=O(n,"segmentIds","sparseSegmentSum");if(a.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.rank!==1)throw new Error(`Indices should be Tensor1D but received shape ${r.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape ${s.shape}`);let i={data:a,indices:r,segmentIds:s};return V.runKernel(m7,i)}var CV=U({sparseSegmentSum_:EV});function MV(e,t,n,a,r,s,i,o){let l=O(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=O(t,"dataSplits","stringNGrams");if(u.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let d={separator:n,nGramWidths:a,leftPad:r,rightPad:s,padWidth:i,preserveShortSequences:o},h={data:l,dataSplits:u},p=V.runKernel(x7,h,d);return{nGrams:p[0],nGramsSplits:p[1]}}var $V=U({stringNGrams_:MV});function RV(e,t,n=!0){let a=O(e,"input","stringSplit","string"),r=O(t,"delimiter","stringSplit","string");if(a.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${a.shape}`);if(r.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${r.shape}`);let s={skipEmpty:n},i={input:a,delimiter:r},o=V.runKernel(b7,i,s);return{indices:o[0],values:o[1],shape:o[2]}}var FV=U({stringSplit_:RV});function OV(e,t){let n=O(e,"input","stringToHashBucketFast","string"),a={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");let r={input:n};return V.runKernel(v7,r,a)}var DV=U({stringToHashBucketFast_:OV}),_V={fft:o1,ifft:Cc,rfft:l1,irfft:f6},zV={hammingWindow:cB,hannWindow:w6,frame:k6,stft:yB},Ye={flipLeftRight:vB,resizeNearestNeighbor:HB,resizeBilinear:UB,rotateWithOffset:kB,cropAndResize:xB,nonMaxSuppression:SB,nonMaxSuppressionAsync:FB,nonMaxSuppressionWithScore:DB,nonMaxSuppressionWithScoreAsync:zB,nonMaxSuppressionPadded:LB,nonMaxSuppressionPaddedAsync:BB,threshold:KB,transform:ZB},PV={bandPart:JB,gramSchmidt:eV,qr:nV},LV={absoluteDifference:sV,computeWeightedLoss:as,cosineDistance:oV,hingeLoss:uV,huberLoss:hV,logLoss:cV,meanSquaredError:mV,sigmoidCrossEntropy:AV,softmaxCrossEntropy:vV},WV={sparseFillEmptyRows:kV,sparseReshape:SV,sparseSegmentMean:TV,sparseSegmentSum:CV},BV={stringNGrams:$V,stringSplit:FV,stringToHashBucketFast:DV},Rs=class extends Mk{minimize(e,t=!1,n){let{value:a,grads:r}=this.computeGradients(e,n);if(n!=null){let s=n.map(i=>({name:i.name,tensor:r[i.name]}));this.applyGradients(s)}else this.applyGradients(r);return Ve(r),t?a:(a.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return Qk(e,t)}dispose(){this.iterations_!=null&&Ve(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:dt(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(Rs,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var Oc=class extends Rs{constructor(e,t,n=null){super();this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=V.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=V.registeredVariables[t],r=!1;this.accumulatedGrads[n]==null&&(this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:Ue(()=>Na(a).variable(r))}),this.accumulatedUpdates[n]==null&&(this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:Ue(()=>Na(a).variable(r))});let s=Array.isArray(e)?e[n].tensor:e[t];if(s==null)return;let i=this.accumulatedGrads[n].variable,o=this.accumulatedUpdates[n].variable;Ue(()=>{let l=De(fe(i,this.rho),fe(tr(s),1-this.rho)),u=fe(Qe(ts(De(o,this.epsilon)),ts(De(i,this.epsilon))),s),d=De(fe(o,this.rho),fe(tr(u),1-this.rho));i.assign(l),o.assign(d);let h=De(fe(u,-this.learningRate),a);a.assign(h)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(Ve(this.accumulatedGrads.map(e=>e.variable)),Ve(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(a=>({originalName:a.name,variable:a.tensor.variable(n)})),this.accumulatedUpdates=e.slice(t,t*2).map(a=>({originalName:a.name,variable:a.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)}};Oc.className="Adadelta";Cs(Oc);var Dc=class extends Rs{constructor(e,t=.1){super();this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=V.registeredVariables[t];if(this.accumulatedGrads[n]==null){let i=!1;this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:Ue(()=>wc(a.shape,this.initialAccumulatorValue).variable(i))}}let r=Array.isArray(e)?e[n].tensor:e[t];if(r==null)return;let s=this.accumulatedGrads[n].variable;Ue(()=>{let i=De(s,tr(r));s.assign(i);let o=De(fe(Qe(r,ts(De(i,V.backend.epsilon()))),-this.learningRate),a);a.assign(o)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&Ve(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)}};Dc.className="Adagrad";Cs(Dc);var _c=class extends Rs{constructor(e,t,n,a=null){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=a,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],Ue(()=>{this.accBeta1=dt(t).variable(),this.accBeta2=dt(n).variable()}),a==null&&(this.epsilon=V.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);Ue(()=>{let n=je(1,this.accBeta1),a=je(1,this.accBeta2);t.forEach((r,s)=>{let i=V.registeredVariables[r],o=!1;this.accumulatedFirstMoment[s]==null&&(this.accumulatedFirstMoment[s]={originalName:`${r}/m`,variable:Ue(()=>Na(i).variable(o))}),this.accumulatedSecondMoment[s]==null&&(this.accumulatedSecondMoment[s]={originalName:`${r}/v`,variable:Ue(()=>Na(i).variable(o))});let l=Array.isArray(e)?e[s].tensor:e[r];if(l==null)return;let u=this.accumulatedFirstMoment[s].variable,d=this.accumulatedSecondMoment[s].variable,h=De(fe(u,this.beta1),fe(l,1-this.beta1)),p=De(fe(d,this.beta2),fe(tr(l),1-this.beta2)),c=Qe(h,n),m=Qe(p,a);u.assign(h),d.assign(p);let f=De(fe(Qe(c,De(ts(m),this.epsilon)),-this.learningRate),i);i.assign(f)}),this.accBeta1.assign(fe(this.accBeta1,this.beta1)),this.accBeta2.assign(fe(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&Ve(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&Ve(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),Ue(()=>{this.accBeta1.assign(pd(this.beta1,this.iterations_+1)),this.accBeta2.assign(pd(this.beta2,this.iterations_+1))});let t=e.length/2,n=!1;this.accumulatedFirstMoment=e.slice(0,t).map(a=>({originalName:a.name,variable:a.tensor.variable(n)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(a=>({originalName:a.name,variable:a.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)}};_c.className="Adam";Cs(_c);var zc=class extends Rs{constructor(e,t,n,a=null,r=0){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=a,this.decay=r,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],Ue(()=>{this.iteration=dt(0).variable(),this.accBeta1=dt(t).variable()}),a==null&&(this.epsilon=V.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);Ue(()=>{let n=je(1,this.accBeta1),a=Qe(-this.learningRate,De(fe(this.iteration,this.decay),1));t.forEach((r,s)=>{let i=V.registeredVariables[r],o=!1;this.accumulatedFirstMoment[s]==null&&(this.accumulatedFirstMoment[s]={originalName:`${r}/m`,variable:Na(i).variable(o)}),this.accumulatedWeightedInfNorm[s]==null&&(this.accumulatedWeightedInfNorm[s]={originalName:`${r}/v`,variable:Na(i).variable(o)});let l=Array.isArray(e)?e[s].tensor:e[r];if(l==null)return;let u=this.accumulatedFirstMoment[s].variable,d=this.accumulatedWeightedInfNorm[s].variable,h=De(fe(u,this.beta1),fe(l,1-this.beta1)),p=fe(d,this.beta2),c=Sa(l),m=i6(p,c);u.assign(h),d.assign(m);let f=De(fe(Qe(a,n),Qe(h,De(m,this.epsilon))),i);i.assign(f)}),this.iteration.assign(De(this.iteration,1)),this.accBeta1.assign(fe(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&Ve(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&Ve(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)}};zc.className="Adamax";Cs(zc);var md=class extends Rs{constructor(e){super();this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=Array.isArray(e)?e[n].tensor:e[t];if(a==null)return;let r=V.registeredVariables[t];Ue(()=>{let s=De(fe(this.c,a),r);r.assign(s)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=Dk(dt(-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)}};md.className="SGD";Cs(md);var Pc=class extends md{constructor(e,t,n=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=dt(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=V.registeredVariables[t];if(this.accumulations[n]==null){let i=!1;this.accumulations[n]={originalName:`${t}/momentum`,variable:Ue(()=>Na(a).variable(i))}}let r=this.accumulations[n].variable,s=Array.isArray(e)?e[n].tensor:e[t];s!=null&&Ue(()=>{let i,o=De(fe(this.m,r),s);this.useNesterov?i=De(fe(this.c,De(s,fe(o,this.m))),a):i=De(fe(this.c,o),a),r.assign(o),a.assign(i)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&Ve(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)}};Pc.className="Momentum";Cs(Pc);var Lc=class extends Rs{constructor(e,t=.9,n=0,a=null,r=!1){super();if(this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=a,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=r,a==null&&(this.epsilon=V.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=V.registeredVariables[t],r=!1;this.accumulatedMeanSquares[n]==null&&(this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:Ue(()=>Na(a).variable(r))}),this.accumulatedMoments[n]==null&&(this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:Ue(()=>Na(a).variable(r))}),this.accumulatedMeanGrads[n]==null&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:Ue(()=>Na(a).variable(r))});let s=Array.isArray(e)?e[n].tensor:e[t];if(s==null)return;let i=this.accumulatedMeanSquares[n].variable,o=this.accumulatedMoments[n].variable;Ue(()=>{let l=De(fe(i,this.decay),fe(tr(s),1-this.decay));if(this.centered){let u=this.accumulatedMeanGrads[n].variable,d=De(fe(u,this.decay),fe(s,1-this.decay)),h=Qe(fe(s,this.learningRate),ts(je(l,De(tr(d),this.epsilon)))),p=De(fe(o,this.momentum),h);i.assign(l),u.assign(d),o.assign(p);let c=je(a,p);a.assign(c)}else{let u=De(fe(i,this.decay),fe(tr(s),1-this.decay)),d=De(fe(o,this.momentum),Qe(fe(s,this.learningRate),ts(De(u,this.epsilon))));i.assign(u),o.assign(d);let h=je(a,d);a.assign(h)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&Ve(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&Ve(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&Ve(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(a=>({originalName:a.name,variable:a.tensor.variable(n)})),this.accumulatedMoments=e.slice(t,t*2).map(a=>({originalName:a.name,variable:a.tensor.variable(n)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(a=>({originalName:a.name,variable:a.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)}};Lc.className="RMSProp";Cs(Lc);var Si=class{static sgd(e){return new md(e)}static momentum(e,t,n=!1){return new Pc(e,t,n)}static rmsprop(e,t=.9,n=0,a=null,r=!1){return new Lc(e,t,n,a,r)}static adam(e=.001,t=.9,n=.999,a=null){return new _c(e,t,n,a)}static adadelta(e=.001,t=.95,n=null){return new Oc(e,t,n)}static adamax(e=.002,t=.9,n=.999,a=null,r=0){return new zc(e,t,n,a,r)}static adagrad(e,t=.1){return new Dc(e,t)}},VV={sgd:Si.sgd,momentum:Si.momentum,adadelta:Si.adadelta,adagrad:Si.adagrad,rmsprop:Si.rmsprop,adamax:Si.adamax,adam:Si.adam},UV=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function jV(){return new Promise(e=>UV(()=>e()))}var C6={};$e(C6,{ERF_A1:()=>aU,ERF_A2:()=>rU,ERF_A3:()=>sU,ERF_A4:()=>iU,ERF_A5:()=>oU,ERF_P:()=>nU,PARALLELIZE_THRESHOLD:()=>p1,SELU_SCALE:()=>tU,SELU_SCALEALPHA:()=>eU,applyActivation:()=>Rc,assertAndGetBroadcastShape:()=>In,assertAxesAreInnerMostDims:()=>mP,assertParamsConsistent:()=>HV,assignToTypedArray:()=>mU,axesAreInnerMostDims:()=>a1,calculateShapes:()=>Ak,checkEinsumDimSizes:()=>vU,combineLocations:()=>t6,complexWithEvenIndex:()=>pU,complexWithOddIndex:()=>cU,computeConv2DInfo:()=>id,computeConv3DInfo:()=>Pk,computeDefaultPad:()=>Yy,computeDilation2DInfo:()=>s_,computeOptimalWindowSize:()=>qV,computeOutAndReduceShapes:()=>fP,computeOutShape:()=>GV,computePool2DInfo:()=>zk,computePool3DInfo:()=>i_,convertConv2DDataFormat:()=>Lk,decodeEinsumEquation:()=>xU,eitherStridesOrDilationsAreOne:()=>Jr,expandShapeToKeepDim:()=>dd,exponent:()=>yU,exponents:()=>gU,fromStringArrayToUint8:()=>MU,fromUint8ToStringArray:()=>CU,getAxesPermutation:()=>gP,getBroadcastDims:()=>gz,getComplexWithIndex:()=>fU,getEinsumComputePath:()=>wU,getEinsumPermutation:()=>bU,getFusedBiasGradient:()=>$c,getFusedDyActivation:()=>Mc,getImageCenter:()=>KV,getInnerMostAxes:()=>AP,getPermuted:()=>ZV,getReductionAxes:()=>jk,getReshaped:()=>XV,getReshapedPermuted:()=>YV,getSliceBeginCoords:()=>JV,getSliceSize:()=>QV,getUndoAxesPermutation:()=>yP,isIdentityPermutation:()=>kU,log:()=>uU,mergeRealAndImagArrays:()=>dU,prepareAndValidate:()=>gk,prepareSplitSize:()=>SU,segment_util:()=>R6,shouldFuse:()=>Fc,slice_util:()=>Uy,splitRealAndImagArrays:()=>hU,tupleValuesAreOne:()=>od,upcastType:()=>dc,validateInput:()=>Vy,validateUpdateShape:()=>By,warn:()=>lU});function HV(e,t){let n=e[0].length;e.forEach((r,s)=>{L(r.length===n,()=>`Error in concat${n}D: rank of tensors[${s}] must be the same as the rank of the rest (${n})`)}),L(t>=0&&t`Error in concat${n}D: axis must be between 0 and ${n-1}.`);let a=e[0];e.forEach((r,s)=>{for(let i=0;i`Error in concat${n}D: Shape of tensors[${s}] (${r}) does not match the shape of the rest (${a}) along the non-concatenated axis ${s}.`)})}function GV(e,t){let n=e[0].slice();for(let a=1;a=t*2+1||i%2==1?s.push(i):r.push(i);a.push(...r),a.push(0),a.push(...s)}return a}function YV(e,t,n,a=!0){let r=[];a?r.push(e[0]/n):r.push(e[0]*n);for(let s=1;s/g,M6=",",$6="...";function xU(e,t){e=e.replace(/\s/g,"");let n=(e.length-e.replace(AU,"").length)/c1.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 ("${c1}").`);let[a,r]=e.split(c1);L(a.indexOf($6)===-1,()=>`The ellipsis notation ("${$6}") is not supported yet.`);let s=a.split(M6),i=s.length;if(t!==i)throw new Error(`Expected ${i} input tensors, received ${t}`);if(i>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");let o=[];for(let p=0;pm.indexOf(c)!==-1))throw new Error(`Output subscripts contain the label ${c} not present in the input subscripts.`);o.indexOf(c)===-1&&o.push(c)}for(let p=0;pr!==-1),{permutationIndices:n,expandDims:a}}function vU(e,t,n){let a=new Array(e);for(let r=0;r`Expected dimension ${a[t[r][i]]} at axis ${i} of input shaped ${JSON.stringify(s)}, but got dimension ${s[i]}`)}}function wU(e,t){let n=e,a=[],r=0;e.length===0&&n.push(-1),r=e.length+1;for(let i=0;it===n)}function IU(e,t){let n=[];for(let a=0;a"Number of splits must evenly divide the axis."),a=new Array(t).fill(e.shape[n]/t);else{let r=t.reduce((i,o)=>(o===-1&&(i+=1),i),0);L(r<=1,()=>"There should be only one negative value in split array.");let s=t.indexOf(-1);if(s!==-1){let i=t.reduce((o,l)=>l>0?o+l:o);t[s]=e.shape[n]-i}L(e.shape[n]===t.reduce((i,o)=>i+o),()=>"The sum of sizes must match the size of the axis dimension."),a=t}return a}var R6={};$e(R6,{collectGatherOpShapeInfo:()=>EU,computeOutShape:()=>TU,segOpComputeOptimalWindowSize:()=>NU});function NU(e,t){let n=!1,a;for(e<=p1?(a=e,n=!0):a=tc(e,Math.floor(Math.sqrt(e)));!n;)a>t||a===e?n=!0:a=tc(e,a+1);return a}function TU(e,t,n){let a=[],r=e.length;for(let s=0;sr))throw new Error(`Expect batchDims in the range of [-${r}, ${r}], but got ${a}`);if(a<0&&(a+=r),a>s)throw new Error(`batchDims (${a}) must be less than rank(x) ( ${s}).`);if(noc(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function MU(e){return e.map(t=>Qu(t))}var F6={};$e(F6,{nonMaxSuppressionV3Impl:()=>I6,nonMaxSuppressionV4Impl:()=>S6,nonMaxSuppressionV5Impl:()=>N6,whereImpl:()=>y6});var $U=1e-7,RU=1e-4,f1=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}},Wc=class{refCount(e){return ja("refCount")}incRef(e){return ja("incRef")}timerAvailable(){return!0}time(e){return ja("time")}read(e){return ja("read")}readSync(e){return ja("readSync")}numDataIds(){return ja("numDataIds")}disposeData(e,t){return ja("disposeData")}write(e,t,n){return ja("write")}move(e,t,n,a,r){return ja("move")}memory(){return ja("memory")}floatPrecision(){return ja("floatPrecision")}epsilon(){return this.floatPrecision()===32?$U:RU}dispose(){return ja("dispose")}};function ja(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 O6(e){let t=e.length,n=0,a=0;for(;t>0;)a=Math.random()*t|0,t--,n=e[t],e[t]=e[a],e[a]=n}function FU(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,a,r,s=0;for(;n>0;)s=Math.random()*n|0,n--,a=e[n],r=t[n],e[n]=e[s],t[n]=t[s],e[s]=a,t[s]=r}function gd(e,t,n){return Math.max(e,Math.min(t,n))}function OU(e){return e%2==0?e:e+1}function DU(e){let t=0;for(let n=0;nn+` Shapes ${e} and ${t} must match`)}function Bc(e){P(e!=null,()=>"The input to the tensor constructor must be a non-null value.")}function yd(e,t=[],n=!1){if(t==null&&(t=[]),Array.isArray(e)||ar(e)&&!n)for(let a=0;a0,n){return new Promise((a,r)=>{let s=0,i=()=>{if(e()){a();return}s++;let o=t(s);if(n!=null&&s>=n){r();return}setTimeout(i,o)};i()})}function UU(e,t){let n=1,a=-1;for(let s=0;s=0)n*=e[s];else if(e[s]===-1){if(a!==-1)throw Error(`Shapes can only have 1 implicit size. Found -1 at dim ${a} and dim ${s}`);a=s}else if(e[s]<0)throw Error(`Shapes can not be < 0. Found ${e[s]} at dim ${s}`);if(a===-1){if(t>0&&t!==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 r=e.slice();return r[a]=t/n,r}function Ha(e,t){let n=t.length;return e=e==null?t.map((a,r)=>r):[].concat(e),P(e.every(a=>a>=-n&&a`All values in axis param must be in range [-${n}, ${n}) but got axis ${e}`),P(e.every(a=>mn(a)),()=>`All values in axis param must be integers but got axis ${e}`),e.map(a=>a<0?n+a:a)}function D6(e,t){let n=[],a=[],r=t!=null&&Array.isArray(t)&&t.length===0,s=t==null||r?null:Ha(t,e).sort(),i=0;for(let o=0;oo)&&e[o]===1&&(n.push(e[o]),a.push(o)),s[i]<=o&&i++}e[o]!==1&&(n.push(e[o]),a.push(o))}return{newShape:n,keptDims:a}}function jU(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 _6(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 z6(e,t){for(let n=0;nt+=n.length),t}function Vc(e){return typeof e=="string"||e instanceof String}function W6(e){return typeof e=="boolean"}function B6(e){return typeof e=="number"}function Uc(e){return Array.isArray(e)?Uc(e[0]):e instanceof Float32Array?"float32":e instanceof Int32Array||e instanceof Uint8Array?"int32":B6(e)?"float32":Vc(e)?"string":W6(e)?"bool":"float32"}function jc(e){return!!(e&&e.constructor&&e.call&&e.apply)}function Hc(e,t){for(let n=t;n=0;--a)n[a]=n[a+1]*e[a+1];return n}function V6(e,t,n,a=!1){let r=new Array;if(t.length===1){let s=t[0]*(a?2:1);for(let i=0;il*u)*(a?2:1);for(let l=0;lr*s)*(n?2:1);if(a===0)return[];if(a!==t.length)throw new Error(`[${e}] does not match the input size ${t.length}${n?" for a complex tensor":""}.`);return V6(0,e,t,n)}function g1(e,t){let n=Gc(e,t);for(let a=0;aa*r,1);if(t==null||t==="float32")return Xo(e,new Float32Array(n));if(t==="int32")return Xo(e,new Int32Array(n));if(t==="bool")return Xo(e,new Uint8Array(n));throw new Error(`Unknown data type ${t}`)}function y1(e){e.forEach(t=>{P(Number.isInteger(t)&&t>=0,()=>`Tensor must have a shape comprised of positive integers but got shape [${e}].`)})}function qU(e,t,n){if(t===0)return 0;if(t===1)return e[0];let a=e[e.length-1];for(let r=0;r{let[n,a]=t.split(":");this.urlFlags[n]=JU(n,a)})}};function ZU(e){let t={};return e.replace(/[?&]([^=?&]+)(?:=([^&]*))?/g,(n,...a)=>(YU(t,a[0],a[1]),a.join("="))),t}function YU(e,t,n){e[decodeURIComponent(t)]=decodeURIComponent(n||"")}function JU(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 se(){return j6}var j6=null;function QU(e){j6=e}var x1;function H6(){if(x1==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");x1=e}return x1}function ej(){let e=H6();return e._tfGlobals==null&&(e._tfGlobals=new Map),e._tfGlobals}function b1(e,t){let n=ej();if(n.has(e))return n.get(e);{let a=t();return n.set(e,a),n.get(e)}}var xd="Abs",bd="Acos",vd="Acosh",Os="Add",Zo="AddN",wd="All",kd="Any",Yo="ArgMax",qc="ArgMin",Id="Asin",Sd="Asinh",Nd="Atan",Td="Atanh",Ed="Atan2",Jo="AvgPool",v1="AvgPoolGrad",Kc="AvgPool3D",w1="AvgPool3DGrad",Qo="BatchMatMul",Xc="BatchToSpaceND",k1="Bincount",tj="BroadcastTo",el="Cast",Ni="Ceil",Ti="ClipByValue",I1="Complex",Zc="ComplexAbs",Cd="Concat",tl="Conv2D",S1="Conv2DBackpropFilter",nl="Conv2DBackpropInput",Yc="Conv3D",N1="Conv3DBackpropFilterV2",T1="Conv3DBackpropInputV2",al="Cos",Md="Cosh",rl="Cumsum",$d="CropAndResize",E1="DenseBincount",Rd="DepthToSpace",sl="DepthwiseConv2dNative",C1="DepthwiseConv2dNativeBackpropFilter",M1="DepthwiseConv2dNativeBackpropInput",$1="Diag",Jc="Dilation2D",R1="Dilation2DBackpropInput",F1="Dilation2DBackpropFilter",il="RealDiv",O1="Einsum",Fd="Elu",D1="EluGrad",Od="Erf",ol="Equal",Ei="Exp",Dd="ExpandDims",ll="Expm1",_1="FFT",Qc="Fill",_d="FlipLeftRight",Ci="Floor",ul="FloorDiv",dl="FusedBatchNorm",zd="GatherV2",Pd="GatherNd",hl="Greater",Mi="GreaterEqual",pl="Identity",z1="IFFT",P1="Imag",Ld="IsFinite",Wd="IsInf",Bd="IsNan",cl="LeakyRelu",fl="Less",ml="LessEqual",L1="LinSpace",$i="Log",Vd="Log1p",Ud="LogicalAnd",ef="LogicalNot",tf="LogicalOr",nj="LogSoftmax",nf="LRN",W1="LRNGrad",gl="Max",Ri="Maximum",yl="MaxPool",B1="MaxPoolGrad",af="MaxPool3D",V1="MaxPool3DGrad",U1="MaxPoolWithArgmax",Al="Mean",xl="Min",Fi="Minimum",bl="MirrorPad",jd="Mod",j1="Multinomial",Oi="Multiply",Hd="Neg",vl="NotEqual",Gd="NonMaxSuppressionV3",qd="NonMaxSuppressionV4",Kd="NonMaxSuppressionV5",Xd="OnesLike",wl="OneHot",Zd="Pack",kl="PadV2",Il="Pow",Sl="Prelu",Yd="Prod",rf="Range",H1="Real",Jd="Reciprocal",Nl="Relu",Qd="Reshape",sf="ResizeNearestNeighbor",G1="ResizeNearestNeighborGrad",Tl="ResizeBilinear",q1="ResizeBilinearGrad",El="Relu6",Cl="Reverse",Ml="Round",Di="Rsqrt",eh="ScatterNd",th="Select",nh="Selu",ah="Slice",$l="Sin",rh="Sinh",sh="Sign",Rl="Sigmoid",ih="Softplus",Fl="Sqrt",Ol="Sum",of="SpaceToBatchND",oh="SplitV",Dl="Softmax",K1="SparseFillEmptyRows",X1="SparseReshape",Z1="SparseSegmentMean",Y1="SparseSegmentSum",J1="SparseToDense",_i="SquaredDifference",lf="Square",lh="StridedSlice",Q1="StringNGrams",eA="StringSplit",tA="StringToHashBucketFast",zi="Sub",_l="Tan",zl="Tanh",Pi="Tile",uh="TopK",dh="Transform",Pl="Transpose",nA="Unique",hh="Unpack",uf="UnsortedSegmentSum",ph="ZerosLike",Li="Step",aA="FromPixels",ch="RotateWithOffset",Ll="_FusedMatMul",Wl="FusedConv2D",Bl="FusedDepthwiseConv2D",df=b1("kernelRegistry",()=>new Map),rA=b1("gradRegistry",()=>new Map);function sA(e,t){let n=K6(e,t);return df.get(n)}function G6(e){return rA.get(e)}function q6(e){let t=df.entries(),n=[];for(;;){let{done:a,value:r}=t.next();if(a)break;let[s,i]=r,[o]=s.split("_");o===e&&n.push(i)}return n}function iA(e){let{kernelName:t,backendName:n}=e,a=K6(t,n);df.has(a)&&console.warn(`The kernel '${t}' for backend '${n}' is already registered`),df.set(a,e)}function aj(e){let{kernelName:t}=e;rA.has(t)&&se().getBool("DEBUG")&&console.warn(`Overriding the gradient for '${t}'`),rA.set(t,e)}function K6(e,t){return`${t}_${e}`}var k={};$e(k,{arraysEqual:()=>Fs,assert:()=>P,assertNonNegativeIntegerDimensions:()=>y1,assertNonNull:()=>Bc,assertShapesMatch:()=>nr,bytesFromStringArray:()=>L6,bytesPerElement:()=>m1,checkConversionForErrors:()=>z6,clamp:()=>gd,computeStrides:()=>Ko,createScalarValue:()=>uj,createShuffledIndices:()=>BU,decodeString:()=>ff,distSquared:()=>zU,encodeString:()=>cf,fetch:()=>hj,fingerPrint64:()=>lj,flatten:()=>yd,getArrayFromDType:()=>_6,getTypedArrayFromDType:()=>jU,hasEncodingLoss:()=>HU,hexToLong:()=>fh,indexToLoc:()=>KU,inferDtype:()=>Uc,inferFromImplicitShape:()=>UU,isBoolean:()=>W6,isFunction:()=>jc,isInt:()=>mn,isNumber:()=>B6,isPromise:()=>A1,isScalarShape:()=>PU,isString:()=>Vc,isTypedArray:()=>ar,isValidDtype:()=>P6,locToIndex:()=>qU,makeOnesTypedArray:()=>g1,makeZerosNestedTypedArray:()=>GU,makeZerosTypedArray:()=>Gc,nearestDivisor:()=>Hc,nearestLargerEven:()=>OU,now:()=>mh,parseAxisParam:()=>Ha,randUniform:()=>_U,repeatedTry:()=>VU,rightPad:()=>Ad,shuffle:()=>O6,shuffleCombo:()=>FU,sizeFromShape:()=>on,sizeToSquarishShape:()=>WU,squeezeShape:()=>D6,sum:()=>DU,tanh:()=>LU,toNestedArray:()=>Xo,toTypedArray:()=>pf});var X6=qr(D3()),Wi=X6.default||X6;function fh(e){return Wi.fromString(e,!0,16)}var Z6=fh("c3a5c85c97cb3127"),Bi=fh("b492b66fbe98f273"),zn=fh("9ae16a3b2f90404f");function oA(e){return e.xor(e.shru(47))}function Y6(e,t,n){let a=e.slice(t,t+n);return Wi.fromBytes(Array.from(a),!0,!0)}function Nt(e,t){return Y6(e,t,8)}function J6(e,t){return Y6(e,t,4)}function gn(e,t){return t===0?e:e.shru(t).or(e.shl(64-t))}function Ds(e,t,n=fh("9ddfea08eb382d69")){let a=e.xor(t).mul(n);a=a.xor(a.shru(47));let r=t.xor(a).mul(n);return r=r.xor(r.shru(47)),r=r.mul(n),r}function rj(e,t,n,a,r,s){r=r.add(e),s=gn(s.add(r).add(a),21);let i=r;return r=r.add(t),r=r.add(n),s=s.add(gn(r,44)),[r.add(a),s.add(i)]}function hf(e,t,n,a){return rj(Nt(e,t),Nt(e,t+8),Nt(e,t+16),Nt(e,t+24),n,a)}function sj(e,t=e.length){if(t>=8){let n=zn.add(t*2),a=Nt(e,0).add(zn),r=Nt(e,t-8),s=gn(r,37).mul(n).add(a),i=gn(a,25).add(r).mul(n);return Ds(s,i,n)}if(t>=4){let n=zn.add(t*2),a=J6(e,0);return Ds(a.shl(3).add(t),J6(e,t-4),n)}if(t>0){let n=e[0],a=e[t>>1],r=e[t-1],s=n+(a<<8),i=t+(r<<2);return oA(zn.mul(s).xor(Z6.mul(i))).mul(zn)}return zn}function ij(e,t=e.length){let n=zn.add(t*2),a=Nt(e,0).mul(Bi),r=Nt(e,8),s=Nt(e,t-8).mul(n),i=Nt(e,t-16).mul(zn);return Ds(gn(a.add(r),43).add(gn(s,30)).add(i),a.add(gn(r.add(zn),18)).add(s),n)}function oj(e,t=e.length){let n=zn.add(t*2),a=Nt(e,0).mul(zn),r=Nt(e,8),s=Nt(e,t-8).mul(n),i=Nt(e,t-16).mul(zn),o=gn(a.add(r),43).add(gn(s,30)).add(i),l=Ds(o,a.add(gn(r.add(zn),18)).add(s),n),u=Nt(e,16).mul(n),d=Nt(e,24),h=o.add(Nt(e,t-32)).mul(n),p=l.add(Nt(e,t-24)).mul(n);return Ds(gn(u.add(d),43).add(gn(h,30)).add(p),u.add(gn(d.add(a),18)).add(h),n)}function lj(e,t=e.length){let n=Wi.fromNumber(81,!0);if(t<=32)return t<=16?sj(e,t):ij(e,t);if(t<=64)return oj(e,t);let a=n,r=n.mul(Bi).add(113),s=oA(r.mul(zn).add(113)).mul(zn),i=[Wi.UZERO,Wi.UZERO],o=[Wi.UZERO,Wi.UZERO];a=a.mul(zn).add(Nt(e,0));let l=0,u=(t-1>>6)*64,d=u+(t-1&63)-63;do a=gn(a.add(r).add(i[0]).add(Nt(e,l+8)),37).mul(Bi),r=gn(r.add(i[1]).add(Nt(e,l+48)),42).mul(Bi),a=a.xor(o[1]),r=r.add(i[0]).add(Nt(e,l+40)),s=gn(s.add(o[0]),33).mul(Bi),i=hf(e,l,i[1].mul(Bi),a.add(o[0])),o=hf(e,l+32,s.add(o[1]),r.add(Nt(e,l+16))),[s,a]=[a,s],l+=64;while(l!==u);let h=Bi.add(s.and(255).shl(1));return l=d,o[0]=o[0].add(t-1&63),i[0]=i[0].add(o[0]),o[0]=o[0].add(i[0]),a=gn(a.add(r).add(i[0]).add(Nt(e,l+8)),37).mul(h),r=gn(r.add(i[1]).add(Nt(e,l+48)),42).mul(h),a=a.xor(o[1].mul(9)),r=r.add(i[0].mul(9).add(Nt(e,l+40))),s=gn(s.add(o[0]),33).mul(h),i=hf(e,l,i[1].mul(h),a.add(o[0])),o=hf(e,l+32,s.add(o[1]),r.add(Nt(e,l+16))),[s,a]=[a,s],Ds(Ds(i[0],o[0],h).add(oA(r).mul(Z6)).add(s),Ds(i[1],o[1],h).add(a),h)}function uj(e,t){return t==="string"?cf(e):pf([e],t)}function dj(e,t){return e instanceof Float32Array&&t==="float32"||e instanceof Int32Array&&t==="int32"||e instanceof Uint8Array&&t==="bool"}function pf(e,t){if(t==="string")throw new Error("Cannot convert a string[] to a TypedArray");if(Array.isArray(e)&&(e=yd(e)),se().getBool("DEBUG")&&z6(e,t),dj(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 a=0;a{a=n()},s,i=mh();if(this.backendTimer.timerAvailable())s=this.backendTimer.time(r);else{r();for(let o of a)o.dataSync();s=Promise.resolve({kernelMs:mh()-i})}if(se().getBool("CHECK_COMPUTATION_FOR_ERRORS"))for(let o=0;o{cj(u,l.dtype,e)})}return{kernelName:e,outputs:a,inputs:t,timeMs:s.then(o=>o.kernelMs),extraInfo:s.then(o=>o.getExtraProfileInfo!=null?o.getExtraProfileInfo():"")}}logKernelProfile(e){let{kernelName:t,outputs:n,timeMs:a,inputs:r,extraInfo:s}=e;n.forEach(i=>{Promise.all([i.data(),a,s]).then(o=>{this.logger.logKernelProfile(t,i,o[0],o[1],r,o[2])})})}};function cj(e,t,n){if(t!=="float32")return!1;for(let a=0;a0?m:""} `}}console.log(`%c${o} %c${i} %c${l}D ${d} %c${u} %c${h} %c${s}`,"font-weight:bold","color:red","color:blue","color: orange","color: green","color: steelblue")}};function mj(e,t,n){let a={},r={};for(let l=0;la[f.id]=!0),c=!0,r[u.id]=!0;break}if(c)break}}let s={};s[n.id]=!0;let i={};for(let l=e.length-1;l>=0;l--){let u=e[l],d=u.inputs;for(let h=0;h=0;r--){let s=t[r],i=[];if(s.outputs.forEach(l=>{let u=e[l.id];u!=null?i.push(u):i.push(null)}),s.gradient==null)throw new Error(`Cannot compute gradient: gradient function not found for ${s.kernelName}.`);let o=s.gradient(i);for(let l in s.inputs){if(!(l in o))throw new Error(`Cannot backprop through input ${l}. Available gradients found: ${Object.keys(o)}.`);let u=n(()=>o[l]());if(u.dtype!=="float32")throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input ${l} must have 'float32' dtype, but has '${u.dtype}'`);let d=s.inputs[l];if(!Fs(u.shape,d.shape))throw new Error(`Error in gradient for op ${s.kernelName}. The gradient of input '${l}' has shape '${u.shape}', which does not match the shape of the input '${d.shape}'`);if(e[d.id]==null)e[d.id]=u;else{let h=e[d.id];e[d.id]=a(h,u),h.dispose()}}}}var Q6=20,gh=3,lA=7;function yj(e,t,n,a){let r=Ko(t),s=Aj(e,t,n,r),i=t.length,o=mf(e,t,n,r,s),l=["Tensor"];return a&&(l.push(` dtype: ${n}`),l.push(` rank: ${i}`),l.push(` shape: [${t}]`),l.push(" values:")),l.push(o.map(u=>" "+u).join(` `)),l.join(` `)}function Aj(e,t,n,a){let r=on(t),s=a[a.length-1],i=new Array(s).fill(0),o=t.length,l=n==="complex64"?Ah(e):e;if(o>1)for(let u=0;uQ6){let g=gh*i,y=Array.from(e.slice(0,g)),A=Array.from(e.slice((o-gh)*i,o*i));return n==="complex64"&&(y=Ah(y),A=Ah(A)),["["+y.map((x,v)=>yh(x,r[v],n)).join(", ")+", ..., "+A.map((x,v)=>yh(x,r[o-gh+v],n)).join(", ")+"]"]}let f=n==="complex64"?Ah(e):Array.from(e);return["["+f.map((g,y)=>yh(g,r[y],n)).join(", ")+"]"]}let u=t.slice(1),d=a.slice(1),h=a[0]*i,p=[];if(o>Q6){for(let f=0;f`Length of values '${a}' does not match the size inferred by the shape '${this.size}'.`)}if(t==="complex64")throw new Error("complex64 dtype TensorBuffers are not supported. Please create a TensorBuffer for the real and imaginary parts separately and call tf.complex(real, imag).");this.values=n||_6(t,this.size),this.strides=Ko(e)}set(e,...t){t.length===0&&(t=[0]),P(t.length===this.rank,()=>`The number of provided coordinates (${t.length}) must match the rank (${this.rank})`);let n=this.locToIndex(t);this.values[n]=e}get(...e){e.length===0&&(e=[0]);let t=0;for(let a of e){if(a<0||a>=this.shape[t]){let r=`Requested out of range element at ${e}. Buffer shape=${this.shape}`;throw new Error(r)}t++}let n=e[e.length-1];for(let a=0;aff(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}dataSync(){this.throwIfDisposed();let e=Tr().readSync(this.dataId);if(this.dtype==="string")try{return e.map(t=>ff(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 Tr().read(this.dataId);return this.dtype==="string"?e:new Uint8Array(e.buffer)}dispose(){this.isDisposed||(Tr().disposeTensor(this),this.isDisposedInternal=!0)}get isDisposed(){return this.isDisposedInternal}throwIfDisposed(){if(this.isDisposed)throw new Error("Tensor is disposed.")}print(e=!1){return Vl.print(this,e)}clone(){return this.throwIfDisposed(),Vl.clone(this)}toString(e=!1){let t=this.dataSync();return yj(t,this.shape,this.dtype,e)}cast(e){return this.throwIfDisposed(),Vl.cast(this,e)}variable(e=!0,t,n){return this.throwIfDisposed(),Tr().makeVariable(this,e,t,n)}};Object.defineProperty(Tt,Symbol.hasInstance,{value:e=>!!e&&e.data!=null&&e.dataSync!=null&&e.throwIfDisposed!=null});function re(){return b1("Tensor",()=>Tt)}re();var gf=class extends Tt{constructor(e,t,n,a){super(e.shape,e.dtype,e.dataId,a);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(!Fs(e.shape,this.shape))throw new Error(`shape of the new value (${e.shape}) and previous value (${this.shape}) must match`);Tr().disposeTensor(this),this.dataId=e.dataId,Tr().incRef(this,null)}dispose(){Tr().disposeVariable(this),this.isDisposedInternal=!0}};Object.defineProperty(gf,Symbol.hasInstance,{value:e=>e instanceof Tt&&e.assign!=null&&e.assign instanceof Function});var Er={};$e(Er,{assertTypesMatch:()=>n4,getTensorsInContainer:()=>fA,isTensorInList:()=>Ij,makeTypesMatch:()=>Ut});var t4;(function(e){e.R0="R0",e.R1="R1",e.R2="R2",e.R3="R3",e.R4="R4",e.R5="R5",e.R6="R6"})(t4||(t4={}));var uA;(function(e){e.float32="float32",e.int32="int32",e.bool="int32",e.complex64="complex64"})(uA||(uA={}));var dA;(function(e){e.float32="float32",e.int32="int32",e.bool="bool",e.complex64="complex64"})(dA||(dA={}));var hA;(function(e){e.float32="float32",e.int32="float32",e.bool="float32",e.complex64="complex64"})(hA||(hA={}));var pA;(function(e){e.float32="complex64",e.int32="complex64",e.bool="complex64",e.complex64="complex64"})(pA||(pA={}));var kj={float32:hA,int32:uA,bool:dA,complex64:pA};function Ga(e,t){if(e==="string"||t==="string"){if(e==="string"&&t==="string")return"string";throw new Error(`Can not upcast ${e} with ${t}`)}return kj[e][t]}function cA(e){return Ga(e,"int32")}function Ut(e,t){if(e.dtype===t.dtype)return[e,t];let n=Ga(e.dtype,t.dtype);return[e.cast(n),t.cast(n)]}function n4(e,t){P(e.dtype===t.dtype,()=>`The dtypes of the first(${e.dtype}) and second(${t.dtype}) input must match`)}function Ij(e,t){return t.some(n=>n.id===e.id)}function fA(e){let t=[],n=new Set;return a4(e,t,n),t}function a4(e,t,n){if(e==null)return;if(e instanceof Tt){t.push(e);return}if(!Sj(e))return;let a=e;for(let r in a){let s=a[r];n.has(s)||(n.add(s),a4(s,t,n))}}function Sj(e){return Array.isArray(e)||typeof e=="object"}function mA(e){return e.kernelName!=null}var r4=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()}},xh=class{constructor(e){this.ENV=e,this.registry={},this.registryFactory={},this.pendingBackendInitId=0,this.state=new r4}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.setupFunc!=null&&e.setupFunc(this.backendInstance)})}disposeRegisteredKernels(e){q6(e).forEach(t=>{t.disposeFunc!=null&&t.disposeFunc(this.registry[e])})}initializeBackend(e){let t=this.registryFactory[e];if(t==null)throw new Error(`Cannot initialize backend ${e}, no registration found.`);try{let n=t.factory();if(n&&!(n instanceof Wc)&&typeof n.then=="function"){let a=++this.pendingBackendInitId,r=n.then(s=>a(athis.registryFactory[t].priority-this.registryFactory[e].priority)}initializeBackendsAndReturnBest(){let e=this.getSortedBackends();for(let t=0;tthis.startScope(n),()=>this.endScope(a),()=>(a=t(),a instanceof Promise&&console.error("Cannot return a Promise inside of tidy."),a))}scopedRun(e,t,n){e();try{let a=n();return t(),a}catch(a){throw t(),a}}nextTensorId(){return xh.nextTensorId++}nextVariableId(){return xh.nextVariableId++}clone(e){let t=j.runKernel(pl,{x:e}),n={x:e},a=s=>({x:()=>{let i="float32",o={x:s},l={dtype:i};return j.runKernel(el,o,l)}}),r=[];return this.addTapeNode(this.state.activeScope.name,n,[t],a,r,{}),t}runKernel(e,t,n){if(sA(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 a=this.backend.numDataIds(),r=0;n.forEach(o=>{r+=o.dtype==="complex64"?3:1});let s=this.state.numDataMovesStack[this.state.numDataMovesStack.length-1],i=a-t-r-s;if(i>0)throw new Error(`Backend '${this.backendName}' has an internal memory leak (${i} data ids) after running '${e}'`)}runKernelFunc(e){let t,n=[],a=this.isTapeOn(),r=this.state.numBytes,s=this.state.numTensors;this.shouldCheckForMemLeaks()&&this.state.numDataMovesStack.push(0);let i;this.backendName==null&&this.backend;let o,l=mA(e)?e.kernelName:this.state.activeScope!=null?this.state.activeScope.name:"";if(mA(e)){let{kernelName:c,inputs:m,attrs:f}=e;this.backendName==null&&this.backend;let g=sA(c,this.backendName);P(g!=null,()=>`Cannot find registered kernel '${c}' for backend '${this.backendName}'`),i=()=>{let y=this.backend.numDataIds();o=g.kernelFunc({inputs:m,attrs:f,backend:this.backend});let A=Array.isArray(o)?o:[o];this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(c,y,A);let x=A.map(v=>{if(v.rank!=null)return v;let{dataId:b,shape:w,dtype:I}=v;return this.makeTensorFromDataId(b,w,I)});if(a){let v=this.getTensorsForGradient(c,m,x);n=this.saveTensorsForBackwardMode(v)}return x}}else{let{forwardFunc:c}=e,m=f=>{!a||(n=f.map(g=>this.keep(this.clone(g))))};i=()=>{let f=this.backend.numDataIds();o=this.tidy(()=>c(this.backend,m));let g=Array.isArray(o)?o:[o];return this.shouldCheckForMemLeaks()&&this.checkKernelForMemLeak(l,f,g),g}}let{inputs:u,attrs:d}=e,h=mA(e)?null:e.backwardsFunc,p;return this.scopedRun(()=>this.state.kernelDepth++,()=>this.state.kernelDepth--,()=>{!this.ENV.getBool("DEBUG")&&!this.state.profiling?t=i():(p=this.profiler.profileKernel(l,u,()=>i()),this.ENV.getBool("DEBUG")&&this.profiler.logKernelProfile(p),t=p.outputs)}),a&&this.addTapeNode(l,u,t,h,n,d),this.state.profiling&&this.state.activeProfile.kernels.push({name:l,bytesAdded:this.state.numBytes-r,totalBytesSnapshot:this.state.numBytes,tensorsAdded:this.state.numTensors-s,totalTensorsSnapshot:this.state.numTensors,inputShapes:Object.keys(u).map(c=>u[c]!=null?u[c].shape:null),outputShapes:t.map(c=>c.shape),kernelTimeMs:p.timeMs,extraInfo:p.extraInfo}),Array.isArray(o)?t:t[0]}saveTensorsForBackwardMode(e){return e.map(t=>this.keep(this.clone(t)))}getTensorsForGradient(e,t,n){let a=G6(e);if(a!=null){let r=a.inputsToSave||[],s=a.outputsToSave||[],i;a.saveAllInputs?(P(Array.isArray(t),()=>"saveAllInputs is true, expected inputs to be an array."),i=Object.keys(t).map(l=>t[l])):i=r.map(l=>t[l]);let o=n.filter((l,u)=>s[u]);return i.concat(o)}return[]}makeTensor(e,t,n,a){if(e==null)throw new Error("Values passed to engine.makeTensor() are null");n=n||"float32",a=a||this.backend;let r=e;n==="string"&&Vc(e[0])&&(r=e.map(o=>cf(o)));let s=a.write(r,t,n),i=new Tt(t,n,s,this.nextTensorId());if(this.trackTensor(i,a),n==="string"){let o=this.state.tensorInfo.get(s),l=L6(r);this.state.numBytes+=l-o.bytes,o.bytes=l}return i}makeTensorFromDataId(e,t,n,a){n=n||"float32";let r=new Tt(t,n,e,this.nextTensorId());return this.trackTensor(r,a),r}makeVariable(e,t=!0,n,a){n=n||this.nextVariableId().toString(),a!=null&&a!==e.dtype&&(e=e.cast(a));let r=new gf(e,t,n,this.nextTensorId());if(this.state.registeredVariables[r.name]!=null)throw new Error(`Variable with name ${r.name} was already registered`);return this.state.registeredVariables[r.name]=r,this.incRef(r,this.backend),r}trackTensor(e,t){this.state.numTensors++,e.dtype==="string"&&this.state.numStringTensors++;let n=0;e.dtype!=="complex64"&&e.dtype!=="string"&&(n=e.size*m1(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 gf||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*m1(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(a=>a.totalBytesSnapshot)),this.state.activeProfile.newBytes=this.state.numBytes-t,this.state.activeProfile.newTensors=this.state.numTensors-n;for(let a of this.state.activeProfile.kernels)a.kernelTimeMs=await a.kernelTimeMs,a.extraInfo=await a.extraInfo;return this.state.activeProfile}isTapeOn(){return this.state.gradientDepth>0&&this.state.kernelDepth===0}addTapeNode(e,t,n,a,r,s){let i={id:this.state.nextTapeNodeId++,kernelName:e,inputs:t,outputs:n,saved:r},o=G6(e);o!=null&&(a=o.gradFunc),a!=null&&(i.gradient=l=>(l=l.map((u,d)=>{if(u==null){let h=n[d],p=Gc(h.size,h.dtype);return this.makeTensor(p,h.shape,h.dtype)}return u}),a(l.length>1?l:l[0],r,s))),this.state.activeTape.push(i)}keep(e){return e.kept=!0,e}startTape(){this.state.gradientDepth===0&&(this.state.activeTape=[]),this.state.gradientDepth++}endTape(){this.state.gradientDepth--}startScope(e){let t={track:[],name:"unnamed scope",id:this.state.nextScopeId++};e&&(t.name=e),this.state.scopeStack.push(t),this.state.activeScope=t}endScope(e){let t=fA(e),n=new Set(t.map(r=>r.id));for(let r=0;r{!r.kept&&r.scopeId===a.id&&this.track(r)})}gradients(e,t,n,a=!1){if(P(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 r=this.scopedRun(()=>this.startTape(),()=>this.endTape(),()=>this.tidy("forward",e));P(r instanceof Tt,()=>"The result y returned by f() must be a tensor.");let s=mj(this.state.activeTape,t,r);if(!a&&s.length===0&&t.length>0)throw new Error("Cannot compute gradient of y=f(x) with respect to x. Make sure that the f you passed encloses all operations that lead from x to y.");return this.tidy("backward",()=>{let i={};i[r.id]=n==null?Nj(r.shape):n,gj(i,s,l=>this.tidy(l),Tj);let o=t.map(l=>i[l.id]);return this.state.gradientDepth===0&&(this.state.activeTape.forEach(l=>{for(let u of l.saved)u.dispose()}),this.state.activeTape=null),{value:r,grads:o}})}customGrad(e){return P(jc(e),()=>"The f passed in customGrad(f) must be a function."),(...t)=>{P(t.every(i=>i instanceof Tt),()=>"The args passed in customGrad(f)(x1, x2,...) must all be tensors");let n,a={};t.forEach((i,o)=>{a[o]=i});let r=(i,o)=>(n=e(...t,o),P(n.value instanceof Tt,()=>"The function f passed in customGrad(f) must return an object where `obj.value` is a tensor"),P(jc(n.gradFunc),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function."),n.value),s=(i,o)=>{let l=n.gradFunc(i,o),u=Array.isArray(l)?l:[l];P(u.length===t.length,()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns the same number of tensors as inputs passed to f(...)."),P(u.every(h=>h instanceof Tt),()=>"The function f passed in customGrad(f) must return an object where `obj.gradFunc` is a function that returns a list of only tensors.");let d={};return u.forEach((h,p)=>{d[p]=()=>h}),d};return this.runKernelFunc({forwardFunc:r,backwardsFunc:s,inputs:a})}}readSync(e){return this.state.tensorInfo.get(e).backend.readSync(e)}read(e){return this.state.tensorInfo.get(e).backend.read(e)}async time(e){let t=mh(),n=await this.backend.time(e);return n.wallMs=mh()-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 r4;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}};xh.nextTensorId=0;xh.nextVariableId=0;function Nj(e){let t=g1(on(e),"float32");return j.makeTensor(t,e,"float32")}function s4(){let e=H6();if(e._tfengine==null){let t=new XU(e);e._tfengine=new xh(t)}return QU(e._tfengine.ENV),bj(()=>e._tfengine),e._tfengine}var j=s4();function Tj(e,t){let n={a:e,b:t};return j.runKernel(Os,n)}var yf={};$e(yf,{isBrowser:()=>i4,isMobile:()=>Cj});function Ej(){return typeof navigator!="undefined"&&navigator!=null}function Cj(e){if(e||Ej()){if(e||(e=navigator),e.product==="ReactNative")return!0;let t=e.userAgent||e.vendor||window.opera;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 i4(){return typeof window!="undefined"&&window.document!=null||typeof WorkerGlobalScope!="undefined"}var rr=se();rr.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.")});rr.registerFlag("IS_BROWSER",()=>i4());rr.registerFlag("IS_NODE",()=>typeof process!="undefined"&&typeof process.versions!="undefined"&&typeof process.versions.node!="undefined");rr.registerFlag("IS_CHROME",()=>typeof navigator!="undefined"&&navigator!=null&&navigator.userAgent!=null&&/Chrome/.test(navigator.userAgent)&&/Google Inc/.test(navigator.vendor));rr.registerFlag("PROD",()=>!1);rr.registerFlag("TENSORLIKE_CHECK_SHAPE_CONSISTENCY",()=>rr.getBool("DEBUG"));rr.registerFlag("DEPRECATION_WARNINGS_ENABLED",()=>!0);rr.registerFlag("IS_TEST",()=>!1);rr.registerFlag("CHECK_COMPUTATION_FOR_ERRORS",()=>!0);rr.registerFlag("WRAP_TO_IMAGEBITMAP",()=>!1);function bh(e,t){let n=e;if(ar(e))return t==="string"?[]:[e.length];if(!Array.isArray(e))return[];let a=[];for(;Array.isArray(n)||ar(n)&&t!=="string";)a.push(n.length),n=n[0];return Array.isArray(e)&&se().getBool("TENSORLIKE_CHECK_SHAPE_CONSISTENCY")&&o4(e,a,[]),a}function o4(e,t,n){if(n=n||[],!Array.isArray(e)&&!ar(e)){P(t.length===0,()=>`Element arr[${n.join("][")}] is a primitive, but should be an array/TypedArray of ${t[0]} elements`);return}P(t.length>0,()=>`Element arr[${n.join("][")}] should be a primitive, but is an array of ${e.length} elements`),P(e.length===t[0],()=>`Element arr[${n.join("][")}] should have ${t[0]} elements, but has ${e.length} elements`);let a=t.slice(1);for(let r=0;r=0&&(r=a),l4(a,r,t,n),e==null||!ar(e)&&!Array.isArray(e)&&typeof e!="number"&&typeof e!="boolean"&&typeof e!="string"){let o=e==null?"null":e.constructor.name;throw new Error(`Argument '${t}' passed to '${n}' must be a Tensor or TensorLike, but got '${o}'`)}let s=bh(e,r);!ar(e)&&!Array.isArray(e)&&(e=[e]);let i=r!=="string"?pf(e,r):yd(e,[],!0);return j.makeTensor(i,s,r)}function Af(e,t,n,a="numeric"){if(!Array.isArray(e))throw new Error(`Argument ${t} passed to ${n} must be a \`Tensor[]\` or \`TensorLike[]\``);return e.map((r,s)=>F(r,`${t}[${s}]`,n,a))}var Mj="__op";function B(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],a=e[n];n.endsWith("_")&&(n=n.substring(0,n.length-1)),n=n+Mj;let r=(...s)=>{j.startScope(n);try{let i=a(...s);return A1(i)&&console.error("Cannot return a Promise inside of tidy."),j.endScope(i),i}catch(i){throw j.endScope(null),i}};return Object.defineProperty(r,"name",{value:n,configurable:!0}),r}function $j(e,t){let n=F(e,"real","complex"),a=F(t,"imag","complex");nr(n.shape,a.shape,`real and imag shapes, ${n.shape} and ${a.shape}, must match in call to tf.complex().`);let r={real:n,imag:a};return j.runKernel(I1,r)}var Vi=B({complex_:$j});function vh(e,t,n,a){if(a==null&&(a=Uc(e)),a==="complex64")throw new Error("Cannot construct a complex64 tensor directly. Please use tf.complex(real, imag).");if(!ar(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){y1(t);let r=on(t),s=on(n);P(r===s,()=>`Based on the provided shape, [${t}], the tensor should have ${r} values but has ${s}`);for(let i=0;i`Error creating a new Tensor. Inferred shape (${n}) does not match the provided shape (${t}). `)}}return!ar(e)&&!Array.isArray(e)&&(e=[e]),t=t||n,e=a!=="string"?pf(e,a):yd(e,[],!0),j.makeTensor(e,t,a)}function Cr(e,t,n){let a=bh(e,n);return vh(e,t,a,n)}var gA={float32:4,float16:2,int32:4,uint16:2,uint8:1,bool:1,complex64:8},xf=4;async function Rj(e,t){let n=[],a=[],r=Array.isArray(e)?e.map(i=>i.name):Object.keys(e);for(let i=0;i{let p=await l.bytes(),c=p.reduce((g,y)=>g+y.length,0)+xf*p.length,m=new Uint8Array(c),f=0;for(let g=0;g{if(t+=s.byteLength,n.push(s.byteLength===s.buffer.byteLength?s:new s.constructor(s)),!(s instanceof Float32Array||s instanceof Int32Array||s instanceof Uint8Array))throw new Error(`Unsupported TypedArray subtype: ${s.constructor.name}`)});let a=new Uint8Array(t),r=0;return n.forEach(s=>{a.set(new Uint8Array(s.buffer),r),r+=s.byteLength}),a.buffer}var yA=typeof Buffer!="undefined"&&(typeof Blob=="undefined"||typeof atob=="undefined"||typeof btoa=="undefined");function d4(e){return yA?Buffer.byteLength(e):new Blob([e]).size}function Oj(e){if(yA)return Buffer.from(e).toString("base64");let t=new Uint8Array(e),n="";for(let a=0,r=t.length;a{t+=r.byteLength});let n=new Uint8Array(t),a=0;return e.forEach(r=>{n.set(new Uint8Array(r),a),a+=r.byteLength}),n.buffer}function h4(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 wh(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:d4(JSON.stringify(e.modelTopology)),weightSpecsBytes:e.weightSpecs==null?0:d4(JSON.stringify(e.weightSpecs)),weightDataBytes:e.weightData==null?0:e.weightData.byteLength}}function _j(){let e=n=>{let a=n<<13,r=0;for(;(a&8388608)==0;)r-=8388608,a<<=1;return a&=~8388608,r+=947912704,a|r},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 zj(){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 Pj(){let e=new Uint32Array(64);for(let t=0;t<64;t++)e[t]=1024;return e[0]=e[32]=0,e}function Lj(){let e=_j(),t=zj(),n=Pj();return a=>{let r=new ArrayBuffer(4*a.length),s=new Uint32Array(r);for(let i=0;i>10]+(o&1023)]+t[o>>10];s[i]=l}return new Float32Array(r)}}var qt=class{constructor(){this.saveRouters=[],this.loadRouters=[]}static getInstance(){return qt.instance==null&&(qt.instance=new qt),qt.instance}static registerSaveRouter(e){qt.getInstance().saveRouters.push(e)}static registerLoadRouter(e){qt.getInstance().loadRouters.push(e)}static getSaveHandlers(e){return qt.getHandlers(e,"save")}static getLoadHandlers(e,t){return qt.getHandlers(e,"load",t)}static getHandlers(e,t,n){let a=[];return(t==="load"?qt.getInstance().loadRouters:qt.getInstance().saveRouters).forEach(r=>{let s=r(e,n);s!==null&&a.push(s)}),a}},Wj=e=>qt.registerSaveRouter(e),Bj=e=>qt.registerLoadRouter(e),Vj=e=>qt.getSaveHandlers(e),Uj=(e,t)=>qt.getLoadHandlers(e,t),xA="tensorflowjs",bA=1,Ui="models_store",_s="model_info_store";function p4(){if(!se().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 vA(e){let t=e.result;t.createObjectStore(Ui,{keyPath:"modelPath"}),t.createObjectStore(_s,{keyPath:"modelPath"})}var ji=class{constructor(e){if(this.indexedDB=p4(),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,a)=>{let r=this.indexedDB.open(xA,bA);r.onupgradeneeded=()=>vA(r),r.onsuccess=()=>{let s=r.result;if(t==null){let i=s.transaction(Ui,"readonly"),o=i.objectStore(Ui).get(this.modelPath);o.onsuccess=()=>{if(o.result==null)return s.close(),a(new Error(`Cannot find model with path '${this.modelPath}' in IndexedDB.`));n(o.result.modelArtifacts)},o.onerror=l=>(s.close(),a(o.error)),i.oncomplete=()=>s.close()}else{let i=wh(t),o=s.transaction(_s,"readwrite"),l=o.objectStore(_s),u=l.put({modelPath:this.modelPath,modelArtifactsInfo:i}),d;u.onsuccess=()=>{d=s.transaction(Ui,"readwrite");let h=d.objectStore(Ui).put({modelPath:this.modelPath,modelArtifacts:t,modelArtifactsInfo:i});h.onsuccess=()=>n({modelArtifactsInfo:i}),h.onerror=p=>{l=o.objectStore(_s);let c=l.delete(this.modelPath);c.onsuccess=()=>(s.close(),a(h.error)),c.onerror=m=>(s.close(),a(h.error))}},u.onerror=h=>(s.close(),a(u.error)),o.oncomplete=()=>{d==null?s.close():d.oncomplete=()=>s.close()}}},r.onerror=s=>a(r.error)})}};ji.URL_SCHEME="indexeddb://";var c4=e=>se().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(ji.URL_SCHEME)?jj(e.slice(ji.URL_SCHEME.length)):null;qt.registerSaveRouter(c4);qt.registerLoadRouter(c4);function jj(e){return new ji(e)}function Hj(e){return e.startsWith(ji.URL_SCHEME)?e.slice(ji.URL_SCHEME.length):e}var Gj=class{constructor(){this.indexedDB=p4()}async listModels(){return new Promise((e,t)=>{let n=this.indexedDB.open(xA,bA);n.onupgradeneeded=()=>vA(n),n.onsuccess=()=>{let a=n.result,r=a.transaction(_s,"readonly"),s=r.objectStore(_s).getAll();s.onsuccess=()=>{let i={};for(let o of s.result)i[o.modelPath]=o.modelArtifactsInfo;e(i)},s.onerror=i=>(a.close(),t(s.error)),r.oncomplete=()=>a.close()},n.onerror=a=>t(n.error)})}async removeModel(e){return e=Hj(e),new Promise((t,n)=>{let a=this.indexedDB.open(xA,bA);a.onupgradeneeded=()=>vA(a),a.onsuccess=()=>{let r=a.result,s=r.transaction(_s,"readwrite"),i=s.objectStore(_s),o=i.get(e),l;o.onsuccess=()=>{if(o.result==null)return r.close(),n(new Error(`Cannot find model with path '${e}' in IndexedDB.`));{let u=i.delete(e),d=()=>{l=r.transaction(Ui,"readwrite");let h=l.objectStore(Ui).delete(e);h.onsuccess=()=>t(o.result.modelArtifactsInfo),h.onerror=p=>n(o.error)};u.onsuccess=d,u.onerror=h=>(d(),r.close(),n(o.error))}},o.onerror=u=>(r.close(),n(o.error)),s.oncomplete=()=>{l==null?r.close():l.oncomplete=()=>r.close()}},a.onerror=r=>n(a.error)})}},rs="/",Ul="tensorflowjs_models",f4="info",qj="model_topology",Kj="weight_specs",Xj="weight_data",Zj="model_metadata";function m4(e){return{info:[Ul,e,f4].join(rs),topology:[Ul,e,qj].join(rs),weightSpecs:[Ul,e,Kj].join(rs),weightData:[Ul,e,Xj].join(rs),modelMetadata:[Ul,e,Zj].join(rs)}}function Yj(e){let t=e.split(rs);if(t.length<3)throw new Error(`Invalid key format: ${e}`);return t.slice(1,t.length-1).join(rs)}function Jj(e){return e.startsWith(Hi.URL_SCHEME)?e.slice(Hi.URL_SCHEME.length):e}var Hi=class{constructor(e){if(!se().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=m4(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),a=wh(e);try{this.LS.setItem(this.keys.info,JSON.stringify(a)),this.LS.setItem(this.keys.topology,t),this.LS.setItem(this.keys.weightSpecs,n),this.LS.setItem(this.keys.weightData,Oj(e.weightData));let r={format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy};return e.signature!=null&&(r.signature=e.signature),e.userDefinedMetadata!=null&&(r.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(r.modelInitializer=e.modelInitializer),this.LS.setItem(this.keys.modelMetadata,JSON.stringify(r)),{modelArtifactsInfo:a}}catch(r){throw this.LS.removeItem(this.keys.info),this.LS.removeItem(this.keys.topology),this.LS.removeItem(this.keys.weightSpecs),this.LS.removeItem(this.keys.weightData),this.LS.removeItem(this.keys.modelMetadata),new Error(`Failed to save model '${this.modelPath}' to local storage: size quota being exceeded is a possible cause of this failure: modelTopologyBytes=${a.modelTopologyBytes}, weightSpecsBytes=${a.weightSpecsBytes}, weightDataBytes=${a.weightDataBytes}.`)}}}async load(){let e=JSON.parse(this.LS.getItem(this.keys.info));if(e==null)throw new Error(`In local storage, there is no model with name '${this.modelPath}'`);if(e.modelTopologyType!=="JSON")throw new Error("BrowserLocalStorage does not support loading non-JSON model topology yet.");let t={},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 a=JSON.parse(this.LS.getItem(this.keys.weightSpecs));if(a==null)throw new Error(`In local storage, the weight specs of model '${this.modelPath}' are missing.`);t.weightSpecs=a;let r=this.LS.getItem(this.keys.modelMetadata);if(r!=null){let i=JSON.parse(r);t.format=i.format,t.generatedBy=i.generatedBy,t.convertedBy=i.convertedBy,i.signature!=null&&(t.signature=i.signature),i.userDefinedMetadata!=null&&(t.userDefinedMetadata=i.userDefinedMetadata),i.modelInitializer!=null&&(t.modelInitializer=i.modelInitializer)}let s=this.LS.getItem(this.keys.weightData);if(s==null)throw new Error(`In local storage, the binary weight values of model '${this.modelPath}' are missing.`);return t.weightData=Dj(s),t}};Hi.URL_SCHEME="localstorage://";var g4=e=>se().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Hi.URL_SCHEME)?Qj(e.slice(Hi.URL_SCHEME.length)):null;qt.registerSaveRouter(g4);qt.registerLoadRouter(g4);function Qj(e){return new Hi(e)}var eH=class{constructor(){P(se().getBool("IS_BROWSER"),()=>"Current environment is not a web browser"),P(typeof window=="undefined"||typeof window.localStorage!="undefined",()=>"Current browser does not appear to support localStorage"),this.LS=window.localStorage}async listModels(){let e={},t=Ul+rs,n=rs+f4;for(let a=0;a"scheme must not be undefined or null."),e.endsWith(jl)&&(e=e.slice(0,e.indexOf(jl))),P(e.length>0,()=>"scheme must not be an empty string.");let n=Ta.getInstance();P(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 bf(e){if(e.indexOf(jl)===-1)throw new Error(`The url string provided does not contain a scheme. Supported schemes are: ${Ta.getSchemes().join(",")}`);return{scheme:e.split(jl)[0],path:e.split(jl)[1]}}async function y4(e,t,n=!1){P(e!==t,()=>`Old path and new path are the same: '${e}'`);let a=qt.getLoadHandlers(e);P(a.length>0,()=>`Copying failed because no load handler is found for source URL ${e}.`),P(a.length<2,()=>`Copying failed because more than one (${a.length}) load handlers for source URL ${e}.`);let r=a[0],s=qt.getSaveHandlers(t);P(s.length>0,()=>`Copying failed because no save handler is found for destination URL ${t}.`),P(s.length<2,()=>`Copying failed because more than one (${a.length}) save handlers for destination URL ${t}.`);let i=s[0],o=bf(e).scheme,l=bf(e).path,u=o===bf(e).scheme,d=await r.load();n&&u&&await Ta.getManager(o).removeModel(l);let h=await i.save(d);return n&&!u&&await Ta.getManager(o).removeModel(l),h.modelArtifactsInfo}async function tH(){let e=Ta.getSchemes(),t={};for(let n of e){let a=await Ta.getManager(n).listModels();for(let r in a){let s=n+jl+r;t[s]=a[r]}}return t}async function nH(e){let t=bf(e);return Ta.getManager(t.scheme).removeModel(t.path)}async function aH(e,t){return y4(e,t,!1)}async function rH(e,t){return y4(e,t,!0)}var sH=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(se().get("IS_BROWSER")){se().setPlatform("browser",new sH);try{Ta.registerManager(Hi.URL_SCHEME,new eH)}catch(e){}try{Ta.registerManager(ji.URL_SCHEME,new Gj)}catch(e){}}var iH={importFetch:()=>_3()},wA,oH=class{constructor(){this.util=di("util"),this.textEncoder=new this.util.TextEncoder}fetch(e,t){return se().global.fetch!=null?se().global.fetch(e,t):(wA==null&&(wA=iH.importFetch()),wA(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)}};se().get("IS_NODE")&&se().setPlatform("node",new oH);function Pe(e,t="float32",n){return t=t||"float32",y1(e),new Qt(e,t,n)}function lH(e,t){let n=F(e,"x","cast");if(!P6(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 a={x:n},r={dtype:t};return j.runKernel(el,a,r)}var we=B({cast_:lH});function uH(e){let t={x:F(e,"x","clone","string_or_numeric")};return j.runKernel(pl,t)}var Gi=B({clone_:uH});function dH(e,t=!1){console.log(e.toString(t))}s4();var hH={buffer:Pe,cast:we,clone:Gi,print:dH};vj(hH);var la={};$e(la,{browserFiles:()=>AH,browserHTTPRequest:()=>kH,concatenateArrayBuffers:()=>AA,copyModel:()=>aH,decodeWeights:()=>u4,encodeWeights:()=>Rj,fromMemory:()=>SH,getLoadHandlers:()=>Uj,getModelArtifactsInfoForJSON:()=>wh,getSaveHandlers:()=>Vj,http:()=>SA,isHTTPScheme:()=>IA,listModels:()=>tH,loadWeights:()=>xH,moveModel:()=>rH,registerLoadRouter:()=>Bj,registerSaveRouter:()=>Wj,removeModel:()=>nH,weightsLoaderFactory:()=>v4,withSaveHandler:()=>NH});var pH="model",cH=".json",fH=".weights.bin";function A4(e){return new Promise(t=>setTimeout(t)).then(e)}var Hl=class{constructor(e){if(!se().getBool("IS_BROWSER"))throw new Error("browserDownloads() cannot proceed because the current environment is not a browser.");e.startsWith(Hl.URL_SCHEME)&&(e=e.slice(Hl.URL_SCHEME.length)),(e==null||e.length===0)&&(e=pH),this.modelTopologyFileName=e+cH,this.weightDataFileName=e+fH}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}],a={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:n};e.signature!=null&&(a.signature=e.signature),e.userDefinedMetadata!=null&&(a.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(a.modelInitializer=e.modelInitializer);let r=window.URL.createObjectURL(new Blob([JSON.stringify(a)],{type:"application/json"})),s=this.jsonAnchor==null?document.createElement("a"):this.jsonAnchor;if(s.download=this.modelTopologyFileName,s.href=r,await A4(()=>s.dispatchEvent(new MouseEvent("click"))),e.weightData!=null){let i=this.weightDataAnchor==null?document.createElement("a"):this.weightDataAnchor;i.download=this.weightDataFileName,i.href=t,await A4(()=>i.dispatchEvent(new MouseEvent("click")))}return{modelArtifactsInfo:wh(e)}}}};Hl.URL_SCHEME="downloads://";var mH=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.files=e}async load(){let e=this.files[0],t=this.files.slice(1);return new Promise((n,a)=>{let r=new FileReader;r.onload=s=>{let i=JSON.parse(s.target.result),o=i.modelTopology;if(o==null){a(new Error(`modelTopology field is missing from file ${e.name}`));return}t.length===0&&n({modelTopology:o});let l=i.weightsManifest;if(l==null){a(new Error(`weightManifest field is missing from file ${e.name}`));return}let u;try{u=this.checkManifestAndWeightFiles(l,t)}catch(c){a(c);return}let d=[],h=[],p=[];l.forEach(c=>{c.paths.forEach(m=>{h.push(m),p.push(null)}),d.push(...c.weights)}),l.forEach(c=>{c.paths.forEach(m=>{let f=new FileReader;f.onload=g=>{let y=g.target.result,A=h.indexOf(m);if(p[A]=y,p.indexOf(null)===-1){let x={modelTopology:o,weightSpecs:d,weightData:AA(p),format:i.format,generatedBy:i.generatedBy,convertedBy:i.convertedBy};i.signature!=null&&(x.signature=i.signature),i.userDefinedMetadata!=null&&(x.userDefinedMetadata=i.userDefinedMetadata),i.modelInitializer!=null&&(x.modelInitializer=i.modelInitializer),n(x)}},f.onerror=g=>a(`Failed to weights data from file of path '${m}'.`),f.readAsArrayBuffer(u[m])})})},r.onerror=s=>a(`Failed to read model topology and weights manifest JSON from file '${e.name}'. BrowserFiles supports loading Keras-style tf.Model artifacts only.`),r.readAsText(e)})}checkManifestAndWeightFiles(e,t){let n=[],a=t.map(s=>h4(s.name)),r={};for(let s of e)s.paths.forEach(i=>{let o=h4(i);if(n.indexOf(o)!==-1)throw new Error(`Duplicate file basename found in weights manifest: '${o}'`);if(n.push(o),a.indexOf(o)===-1)throw new Error(`Weight file with basename '${o}' is not provided.`);r[i]=t[a.indexOf(o)]});if(n.length!==t.length)throw new Error(`Mismatch in the number of files in weights manifest (${n.length}) and the number of weight files provided (${t.length}).`);return r}},gH=e=>se().getBool("IS_BROWSER")&&!Array.isArray(e)&&e.startsWith(Hl.URL_SCHEME)?yH(e.slice(Hl.URL_SCHEME.length)):null;qt.registerSaveRouter(gH);function yH(e="model"){return new Hl(e)}function AH(e){return new mH(e)}function x4(e,t,n,a){i(e),n=n==null?0:n,a=a==null?1:a,o(n,a);let r=0,s=l=>(l.then(u=>{let d=n+ ++r/e.length*(a-n);return t(d),u}),l);function i(l){P(l!=null&&Array.isArray(l)&&l.length>0,()=>"promises must be a none empty array")}function o(l,u){P(l>=0&&l<=1,()=>`Progress fraction must be in range [0, 1], but got startFraction ${l}`),P(u>=0&&u<=1,()=>`Progress fraction must be in range [0, 1], but got endFraction ${u}`),P(u>=l,()=>`startFraction must be no more than endFraction, but got startFraction ${l} and endFraction ${u}`)}return Promise.all(e.map(s))}async function b4(e,t){t==null&&(t={});let n=t.fetchFunc==null?se().platform.fetch:t.fetchFunc,a=e.map(u=>n(u,t.requestInit,{isBinary:!0})),r=0,s=.5,i=(t.onProgress==null?await Promise.all(a):await x4(a,t.onProgress,r,s)).map(u=>u.arrayBuffer()),o=.5,l=1;return t.onProgress==null?await Promise.all(i):await x4(i,t.onProgress,o,l)}async function xH(e,t="",n,a){return v4(r=>b4(r,{requestInit:a}))(e,t,n)}function v4(e){return async(t,n="",a)=>{let r=t.map(()=>!1),s={},i=a!=null?a.map(()=>!1):[],o=[];if(t.forEach((c,m)=>{let f=0;c.weights.forEach(g=>{let y="quantization"in g?g.quantization.dtype:g.dtype,A=gA[y]*on(g.shape),x=()=>{r[m]=!0,s[m]==null&&(s[m]=[]),s[m].push({manifestEntry:g,groupOffset:f,sizeBytes:A})};a!=null?a.forEach((v,b)=>{v===g.name&&(x(),i[b]=!0)}):x(),o.push(g.name),f+=A})}),!i.every(c=>c)){let c=a.filter((m,f)=>!i[f]);throw new Error(`Could not find weights in manifest with names: ${c.join(", ")}. Manifest JSON has weights with names: ${o.join(", ")}.`)}let l=r.reduce((c,m,f)=>(m&&c.push(f),c),[]),u=[];l.forEach(c=>{t[c].paths.forEach(m=>{let f=n+(n.endsWith("/")?"":"/")+m;u.push(f)})});let d=await e(u),h={},p=0;return l.forEach(c=>{let m=t[c].paths.length,f=0;for(let x=0;x{let v=g.slice(x.groupOffset,x.groupOffset+x.sizeBytes),b=u4(v,[x.manifestEntry]);for(let w in b)h[w]=b[w]}),p+=m}),h}}var bH="application/octet-stream",vH="application/json",kA=class{constructor(e,t){if(this.DEFAULT_METHOD="POST",t==null&&(t={}),this.weightPathPrefix=t.weightPathPrefix,this.onProgress=t.onProgress,this.weightUrlConverter=t.weightUrlConverter,t.fetchFunc!=null?(P(typeof t.fetchFunc=="function",()=>"Must pass a function that matches the signature of `fetch` (see https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API)"),this.fetch=t.fetchFunc):this.fetch=se().platform.fetch,P(e!=null&&e.length>0,()=>"URL path for http must not be null, undefined or empty."),Array.isArray(e)&&P(e.length===2,()=>`URL paths for http must have a length of 2, (actual length is ${e.length}).`),this.path=e,t.requestInit!=null&&t.requestInit.body!=null)throw new Error("requestInit is expected to have no pre-existing body, but has one.");this.requestInit=t.requestInit||{}}async save(e){if(e.modelTopology instanceof ArrayBuffer)throw new Error("BrowserHTTPRequest.save() does not support saving model topology in binary formats yet.");let t=Object.assign({method:this.DEFAULT_METHOD},this.requestInit);t.body=new FormData;let n=[{paths:["./model.weights.bin"],weights:e.weightSpecs}],a={modelTopology:e.modelTopology,format:e.format,generatedBy:e.generatedBy,convertedBy:e.convertedBy,weightsManifest:n};e.signature!=null&&(a.signature=e.signature),e.userDefinedMetadata!=null&&(a.userDefinedMetadata=e.userDefinedMetadata),e.modelInitializer!=null&&(a.modelInitializer=e.modelInitializer),t.body.append("model.json",new Blob([JSON.stringify(a)],{type:vH}),"model.json"),e.weightData!=null&&t.body.append("model.weights.bin",new Blob([e.weightData],{type:bH}),"model.weights.bin");let r=await this.fetch(this.path,t);if(r.ok)return{modelArtifactsInfo:wh(e),responses:[r]};throw new Error(`BrowserHTTPRequest.save() failed due to HTTP response status ${r.status}.`)}async load(){let e=await this.fetch(this.path,this.requestInit);if(!e.ok)throw new Error(`Request to ${this.path} failed with status code ${e.status}. Please verify this URL points to the model JSON of the model to load.`);let t;try{t=await e.json()}catch(c){let m=`Failed to parse model JSON of response from ${this.path}.`;throw this.path.endsWith(".pb")?m+=" 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.":m+=" Please make sure the server is serving valid JSON for this request.",new Error(m)}let n=t.modelTopology,a=t.weightsManifest,r=t.generatedBy,s=t.convertedBy,i=t.format,o=t.signature,l=t.userDefinedMetadata;if(n==null&&a==null)throw new Error(`The JSON from HTTP path ${this.path} contains neither model topology or manifest for weights.`);let u,d;a!=null&&([u,d]=await this.loadWeights(a));let h={modelTopology:n,weightSpecs:u,weightData:d,generatedBy:r,convertedBy:s,format:i};o!=null&&(h.signature=o),l!=null&&(h.userDefinedMetadata=l);let p=t.modelInitializer;return p&&(h.modelInitializer=p),h}async loadWeights(e){let t=Array.isArray(this.path)?this.path[1]:this.path,[n,a]=wH(t),r=this.weightPathPrefix||n,s=[];for(let u of e)s.push(...u.weights);let i=[],o=[];for(let u of e)for(let d of u.paths)this.weightUrlConverter!=null?o.push(this.weightUrlConverter(d)):i.push(r+d+a);this.weightUrlConverter&&i.push(...await Promise.all(o));let l=await b4(i,{requestInit:this.requestInit,fetchFunc:this.fetch,onProgress:this.onProgress});return[s,AA(l)]}};kA.URL_SCHEME_REGEX=/^https?:\/\//;function wH(e){let t=e.lastIndexOf("/"),n=e.lastIndexOf("?"),a=e.substring(0,t),r=n>t?e.substring(n):"";return[a+"/",r]}function IA(e){return e.match(kA.URL_SCHEME_REGEX)!=null}var w4=(e,t)=>{if(typeof fetch=="undefined"&&(t==null||t.fetchFunc==null))return null;{let n=!0;if(Array.isArray(e)?n=e.every(a=>IA(a)):n=IA(e),n)return SA(e,t)}return null};qt.registerSaveRouter(w4);qt.registerLoadRouter(w4);function SA(e,t){return new kA(e,t)}function kH(e,t){return SA(e,t)}var NA=class{constructor(e){this.modelArtifacts=e}async load(){return this.modelArtifacts}},IH=class{constructor(e){this.saveHandler=e}async save(e){return this.saveHandler(e)}};function SH(e,t,n,a){return arguments.length===1?e.modelTopology!=null||e.weightSpecs!=null?new NA(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 NA({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 NA({modelTopology:e,weightSpecs:t,weightData:n,trainingConfig:a}))}function NH(e){return new IH(e)}function TH(e,t,n=!1,a=!1){let r=F(e,"a","matMul"),s=F(t,"b","matMul");[r,s]=Ut(r,s);let i={a:r,b:s},o={transposeA:n,transposeB:a};return j.runKernel(Qo,i,o)}var it=B({matMul_:TH});function EH(e,t,n=1,a=0){if(t<2)throw new Error(`Error in oneHot: depth must be >=2, but it is ${t}`);let r={indices:F(e,"indices","oneHot","int32")},s={depth:t,onValue:n,offValue:a};return j.runKernel(wl,r,s)}var kh=B({oneHot_:EH});function CH(e,t){let n=F(e,"x","transpose");if(t==null&&(t=n.shape.map((s,i)=>i).reverse()),P(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of perm ${t}.`),t.forEach(s=>{P(s>=0&&s`All entries in 'perm' must be between 0 and ${n.rank-1} but got ${t}`)}),n.rank<=1)return n.clone();let a={x:n},r={perm:t};return j.runKernel(Pl,a,r)}var ct=B({transpose_:CH});function MH(e,t,n){let a=F(e,"labels","confusionMatrix"),r=F(t,"predictions","confusionMatrix");P(n==null||n>0&&Number.isInteger(n),()=>`If provided, numClasses must be a positive integer, but got ${n}`),P(a.rank===1,()=>`Expected the rank of labels to be 1, but got ${a.rank}`),P(r.rank===1,()=>`Expected the rank of predictions to be 1, but got ${r.rank}`),P(a.shape[0]===r.shape[0],()=>`Mismatch in the number of examples: ${a.shape[0]} vs. ${r.shape[0]}. Labels and predictions should have the same number of elements.`),P(n>0&&Number.isInteger(n),()=>`numClasses is required to be a positive integer, but got ${n}`);let s=kh(we(a,"int32"),n),i=kh(we(r,"int32"),n),o=ct(s),l=it(o,i);return we(l,"int32")}var gwe=B({confusionMatrix_:MH}),k4={};$e(k4,{fromPixels:()=>PH,fromPixelsAsync:()=>_H,toPixels:()=>zH});function $H(e,t,n){if(Bc(e),t!=null&&t.length!==3)throw new Error("tensor3d() requires shape to have three numbers");let a=bh(e,n);if(a.length!==3&&a.length!==1)throw new Error("tensor3d() requires values to be number[][][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor3d() requires shape to be provided when `values` are a flat array");return vh(e,t,a,n)}var Gl;function I4(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,a=!1,r=!1,s=!1,i=!1,o=!1;if(e.data instanceof Uint8Array)n=!0;else if(typeof ImageData!="undefined"&&e instanceof ImageData)a=!0;else if(typeof HTMLVideoElement!="undefined"&&e instanceof HTMLVideoElement)r=!0;else if(typeof HTMLImageElement!="undefined"&&e instanceof HTMLImageElement)s=!0;else if(e.getContext!=null)i=!0;else if(typeof ImageBitmap!="undefined"&&e instanceof ImageBitmap)o=!0;else throw new Error(`pixels passed to tf.browser.fromPixels() must be either an HTMLVideoElement, HTMLImageElement, HTMLCanvasElement, ImageData in browser, or OffscreenCanvas, ImageData in webworker or {data: Uint32Array, width: number, height: number}, but was ${e.constructor.name}`);if(r){let p=2;if(r&&e.readyState element.")}if(sA(aA,j.backendName)!=null){let p={pixels:e},c={numChannels:t};return j.runKernel(aA,p,c)}let[l,u]=r?[e.videoWidth,e.videoHeight]:[e.width,e.height],d;i?d=e.getContext("2d").getImageData(0,0,l,u).data:a||n?d=e.data:(s||r||o)&&(Gl==null&&(Gl=document.createElement("canvas").getContext("2d")),Gl.canvas.width=l,Gl.canvas.height=u,Gl.drawImage(e,0,0,l,u),d=Gl.getImageData(0,0,l,u).data);let h;if(t===4)h=new Int32Array(d);else{let p=l*u;h=new Int32Array(p*t);for(let c=0;c4||s===2)throw new Error(`toPixels only supports depth of size 1, 3 or 4 but got ${s}`);if(n.dtype!=="float32"&&n.dtype!=="int32")throw new Error(`Unsupported type for toPixels: ${n.dtype}. Please use float32 or int32 tensors.`);let i=await n.data(),o=n.dtype==="float32"?255:1,l=new Uint8ClampedArray(r*a*4);for(let u=0;u1)throw new Error(`Tensor values for a float32 Tensor must be in the range [0 - 1] but encountered ${c}.`)}else if(n.dtype==="int32"&&(c<0||c>255))throw new Error(`Tensor values for a int32 Tensor must be in the range [0 - 255] but encountered ${c}.`);s===1?(d[0]=c*o,d[1]=c*o,d[2]=c*o):d[p]=c*o}let h=u*4;l[h+0]=Math.round(d[0]),l[h+1]=Math.round(d[1]),l[h+2]=Math.round(d[2]),l[h+3]=Math.round(d[3])}if(t!=null){t.width=r,t.height=a;let u=t.getContext("2d"),d=new ImageData(l,r,a);u.putImageData(d,0,0)}return n!==e&&n.dispose(),l}var PH=B({fromPixels_:I4}),S4={};$e(S4,{prepareAndValidate:()=>N4});function N4(e,t){let n=e.shape.length,a=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(a<1)throw new Error(`tf.gatherND() expects the indices to be rank 1 or higher, but the rank was ${a}.`);if(t.dtype!=="int32")throw new Error(`tf.gatherND() expects the indices to be int32 type, but the dtype was ${t.dtype}.`);if(t.shape[a-1]>n)throw new Error(`index innermost dimension length must be <= tensor rank; saw: ${t.shape[a-1]} vs. ${n}`);if(on(e.shape)===0)throw new Error(`Requested more than 0 entries, but input is empty. Input shape: ${e.shape}.`);let r=t.shape,s=r[r.length-1],i=1;for(let h=0;hh/u),1].slice(0,s);return[l,i,u,d]}var T4={};$e(T4,{calculateShapes:()=>E4,validateInput:()=>EA,validateUpdateShape:()=>TA});function TA(e,t,n){let a=t.rank>1?t.shape[t.rank-1]:1,r=t.rank>1?t.rank-1:1,s=`Must have updates.shape = indices.shape[:batchDim] + shape[sliceDim:], got updates.shape: ${n.shape}, indices.shape: ${t.shape}, shape: ${e}, sliceDim: ${a}, and batchDim: ${r}.`;if(n.rank1?t.shape[a-1]:1,s=n.length,i=1;for(let h=r;hLH,computeFlatOffset:()=>BH,computeOutShape:()=>C4,getNormalizedAxes:()=>F4,isSliceContinous:()=>WH,maskToAxes:()=>vf,parseSliceParams:()=>L4,sliceInfo:()=>VH,startForAxis:()=>z4,startIndicesWithElidedDims:()=>O4,stopForAxis:()=>P4,stopIndicesWithElidedDims:()=>D4,stridesForAxis:()=>_4,stridesWithElidedDims:()=>M4});function LH(e,t,n){let a=e.shape.length;P(a===t.length,()=>`Error in slice${a}D: Length of begin ${t} must match the rank of the array (${a}).`),P(a===n.length,()=>`Error in slice${a}D: Length of size ${n} must match the rank of the array (${a}).`);for(let r=0;r`Error in slice${a}D: begin[${r}] + size[${r}] (${t[r]+n[r]}) would overflow input.shape[${r}] (${e.shape[r]})`)}function vf(e){let t=[],n=0;for(;e>0;)e&1&&t.push(n),e/=2,n++;return t}function C4(e,t,n){let a=[];for(let r=0;r0){let c=t[0],m=n+1;d=O4(i,c,m,a,e),h=D4(o,c,m,r,e),p=M4(s,c,m,e)}else for(let c=0;c-1)s[o]=0;else{let l=$4(t,n,o),u=a[l];e&1<-1)s[o]=Number.MAX_SAFE_INTEGER;else{let l=$4(t,n,o),u=a[l];e&1<0?i=Number.MIN_SAFE_INTEGER:i=Number.MAX_SAFE_INTEGER);let l=a[r];return i<0&&(i+=l),i=gd(0,i,l-1),i}function P4(e,t,n,a,r,s){let i=t[r],o=n[r]||1;(e&1<0?i=Number.MAX_SAFE_INTEGER:i=Number.MIN_SAFE_INTEGER);let l=a[r];return i<0&&(i+=l),o>0?i=gd(0,i,l):i=gd(-1,i,l-1),i}function WH(e,t,n){let a=n.length;for(let r=0;r1){a=r;break}for(let r=a+1;r0||n[r]!==e[r])return!1;return!0}function BH(e,t){let n=e.length>0?e[e.length-1]:1;for(let a=0;a{P(i!==-1,()=>"slice() does not support negative begin indexing.")});let s;return n==null?s=new Array(r).fill(-1):typeof n=="number"?s=[n,...new Array(r-1).fill(-1)]:n.lengthi>=0?i:(P(i===-1,()=>`Negative size values should be exactly -1 but got ${i} for the slice() size at index ${o}.`),e.shape[o]-a[o])),[a,s]}function VH(e,t,n,a,r,s,i,o,l){let u=t.slice(),d=n.slice(),h=a;a==null&&(h=new Array(u.length));let p=vf(i);if(p.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(i!==0&&o!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(i!==0&&l!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");let c=e.length-u.length,m=vf(o),f=e.slice();m.forEach(w=>{u[w]=0,d[w]=1,f.splice(w,0,1)});let{begin:g,end:y,strides:A}=F4(f,p,c,u,d,h,r,s,i);u=g,d=y,h=A;let x=vf(l);x.forEach(w=>{d[w]=u[w]+1,h[w]=1});let v=C4(u,d,h),b=v.filter((w,I)=>x.indexOf(I)===-1);return{nonStrided:h.every(w=>w===1),$begin:u,$end:d,$strides:h,size:v,newShape:f,outShape:b}}var ue={};$e(ue,{Serializable:()=>W4,SerializationMap:()=>qi,registerClass:()=>zs});var W4=class{getClassName(){return this.constructor.className}static fromConfig(e,t){return new e(t)}},qi=class{constructor(){this.classNameMap={}}static getMap(){return qi.instance==null&&(qi.instance=new qi),qi.instance}static register(e){qi.getMap().classNameMap[e.className]=[e,e.fromConfig]}};function zs(e){P(e.className!=null,()=>"Class being registered does not have the static className property defined."),P(typeof e.className=="string",()=>"className is required to be a string, but got type "+typeof e.className),P(e.className.length>0,()=>"Class being registered has an empty-string as its className, which is disallowed."),qi.register(e)}function B4(e){se().getBool("DEPRECATION_WARNINGS_ENABLED")&&console.warn(e+" You can disable deprecation warnings with tf.disableDeprecationWarnings().")}wj(B4);function Ps(){return j}function CA(){return j.memory()}function Z(e,t){return j.tidy(e,t)}function Ge(e){fA(e).forEach(t=>t.dispose())}function Sn(e){return j.keep(e)}function MA(e,t,n=1){return j.registerBackend(e,t,n)}function UH(){return j.backend}function jH(e,t){let n=F(e,"a","add"),a=F(t,"b","add");[n,a]=Ut(n,a);let r={a:n,b:a};return j.runKernel(Os,r)}var pe=B({add_:jH});function HH(e,t){let n=F(e,"a","floorDiv"),a=F(t,"b","floorDiv");[n,a]=Ut(n,a);let r={a:n,b:a};return j.runKernel(ul,r)}var $A=B({floorDiv_:HH});function GH(e,t){let n=F(e,"a","div"),a=F(t,"b","div");if([n,a]=Ut(n,a),n.dtype==="int32"&&a.dtype==="int32")return $A(n,a);let r={a:n,b:a},s={};return j.runKernel(il,r,s)}var Me=B({div_:GH});function qH(e,t){let n=F(e,"a","mul"),a=F(t,"b","mul");[n,a]=Ut(n,a);let r={a:n,b:a};return j.runKernel(Oi,r)}var K=B({mul_:qH});function KH(e){let t=F(e,"x","abs");if(t.dtype==="complex64"){let n={x:t};return j.runKernel(Zc,n)}else{let n={x:t};return j.runKernel(xd,n)}}var yn=B({abs_:KH});function XH(e){let t={x:F(e,"x","acos")};return j.runKernel(bd,t)}var V4=B({acos_:XH});function ZH(e){let t={x:F(e,"x","acosh")};return j.runKernel(vd,t)}var U4=B({acosh_:ZH});function YH(e){P(Array.isArray(e),()=>"The argument passed to tf.addN() must be a list of tensors"),P(e.length>=1,()=>`Must pass at least one tensor to tf.addN(), but got ${e.length}`);let t=e.map((r,s)=>F(r,`tensors${s}`,"addN")),n=t[0];t.forEach(r=>{if(r.dtype!==n.dtype)throw new Error("All tensors passed to tf.addN() must have the same dtype")}),t.forEach(r=>{if(!Fs(r.shape,n.shape))throw new Error("All tensors passed to tf.addN() must have the same shape")});let a=t;return j.runKernel(Zo,a)}var JH=B({addN_:YH});function QH(e,t=null,n=!1){let a={x:F(e,"x","all","bool")},r={axis:t,keepDims:n};return j.runKernel(wd,a,r)}var RA=B({all_:QH});function eG(e,t=null,n=!1){let a={x:F(e,"x","any","bool")},r={axis:t,keepDims:n};return j.runKernel(kd,a,r)}var wf=B({any_:eG});function tG(e,t=0){let n={x:F(e,"x","argMax")},a={axis:t};return j.runKernel(Yo,n,a)}var kf=B({argMax_:tG});function nG(e,t=0){let n={x:F(e,"x","argMin")},a={axis:t};return j.runKernel(qc,n,a)}var j4=B({argMin_:nG});function aG(e){let t={x:F(e,"x","asin")};return j.runKernel(Id,t)}var H4=B({asin_:aG});function rG(e){let t={x:F(e,"x","asinh")};return j.runKernel(Sd,t)}var G4=B({asinh_:rG});function sG(e){let t={x:F(e,"x","atan")};return j.runKernel(Nd,t)}var q4=B({atan_:sG});function iG(e,t){let n=F(e,"a","atan2"),a=F(t,"b","atan2");[n,a]=Ut(n,a);let r={a:n,b:a};return j.runKernel(Ed,r)}var K4=B({atan2_:iG});function oG(e){let t={x:F(e,"x","atanh")};return j.runKernel(Td,t)}var X4=B({atanh_:oG});function lG(e,t,n,a,r="NHWC",s){let i=e[3],o=[...t,i],l=J4(r);return Ih(e,o,n,s,a,null,null,l)}function Z4(e,t,n,a,r,s,i="channelsLast"){let[o,l]=If(t),u;if(i==="channelsLast")u=[o,l,e[3],e[3]];else if(i==="channelsFirst")u=[o,l,e[1],e[1]];else throw new Error(`Unknown dataFormat ${i}`);return Ih(e,u,n,a,r,s,!1,i)}function uG(e,t,n,a,r,s,i="NDHWC"){let[o,l,u]=OA(t),d,h;if(i==="NDHWC")h="channelsLast",d=[o,l,u,e[4],e[4]];else if(i==="NCDHW")h="channelsFirst",d=[o,l,u,e[1],e[1]];else throw new Error(`Unknown dataFormat ${i}`);return Y4(e,d,n,a,r,!1,h,s)}function Ih(e,t,n,a,r,s,i=!1,o="channelsLast"){let[l,u,d,h]=[-1,-1,-1,-1];if(o==="channelsLast")[l,u,d,h]=e;else if(o==="channelsFirst")[l,h,u,d]=e;else throw new Error(`Unknown dataFormat ${o}`);let[p,c,,m]=t,[f,g]=If(n),[y,A]=If(a),x=ql(p,y),v=ql(c,A),{padInfo:b,outHeight:w,outWidth:I}=pG(r,u,d,f,g,x,v,s,o),T=i?m*h:m,C;return o==="channelsFirst"?C=[l,T,w,I]:o==="channelsLast"&&(C=[l,w,I,T]),{batchSize:l,dataFormat:o,inHeight:u,inWidth:d,inChannels:h,outHeight:w,outWidth:I,outChannels:T,padInfo:b,strideHeight:f,strideWidth:g,filterHeight:p,filterWidth:c,effectiveFilterHeight:x,effectiveFilterWidth:v,dilationHeight:y,dilationWidth:A,inShape:e,outShape:C,filterShape:t}}function Y4(e,t,n,a,r,s=!1,i="channelsLast",o){let[l,u,d,h,p]=[-1,-1,-1,-1,-1];if(i==="channelsLast")[l,u,d,h,p]=e;else if(i==="channelsFirst")[l,p,u,d,h]=e;else throw new Error(`Unknown dataFormat ${i}`);let[c,m,f,,g]=t,[y,A,x]=OA(n),[v,b,w]=OA(a),I=ql(c,v),T=ql(m,b),C=ql(f,w),{padInfo:z,outDepth:$,outHeight:S,outWidth:D}=cG(r,u,d,h,y,A,x,I,T,C,o),_=s?g*p:g,W;return i==="channelsFirst"?W=[l,_,$,S,D]:i==="channelsLast"&&(W=[l,$,S,D,_]),{batchSize:l,dataFormat:i,inDepth:u,inHeight:d,inWidth:h,inChannels:p,outDepth:$,outHeight:S,outWidth:D,outChannels:_,padInfo:z,strideDepth:y,strideHeight:A,strideWidth:x,filterDepth:c,filterHeight:m,filterWidth:f,effectiveFilterDepth:I,effectiveFilterHeight:T,effectiveFilterWidth:C,dilationDepth:v,dilationHeight:b,dilationWidth:w,inShape:e,outShape:W,filterShape:t}}function dG(e,t,n,a,r){a==null&&(a=FA(e,t,n));let s=e[0],i=e[1],o=Ki((s-t+2*a)/n+1,r),l=Ki((i-t+2*a)/n+1,r);return[o,l]}function hG(e,t,n,a,r,s){r==null&&(r=FA(e,t,a));let i=e[0],o=e[1],l=e[2],u=Ki((i-t+2*r)/a+1,s),d=Ki((o-t+2*r)/a+1,s),h=Ki((l-t+2*r)/a+1,s);return[u,d,h,n]}function FA(e,t,n,a=1){let r=ql(t,a);return Math.floor((e[0]*(n-1)-n+r)/2)}function If(e){return typeof e=="number"?[e,e,e]:e.length===2?[e[0],e[1],1]:e}function OA(e){return typeof e=="number"?[e,e,e]:e}function ql(e,t){return t<=1?e:e+(e-1)*(t-1)}function pG(e,t,n,a,r,s,i,o,l){let u,d,h;if(typeof e=="number"){u={top:e,bottom:e,left:e,right:e,type:e===0?"VALID":"NUMBER"};let p=dG([t,n],s,a,e,o);d=p[0],h=p[1]}else if(e==="same"){d=Math.ceil(t/a),h=Math.ceil(n/r);let p=Math.max(0,(d-1)*a+s-t),c=Math.max(0,(h-1)*r+i-n),m=Math.floor(p/2),f=p-m,g=Math.floor(c/2),y=c-g;u={top:m,bottom:f,left:g,right:y,type:"SAME"}}else if(e==="valid")u={top:0,bottom:0,left:0,right:0,type:"VALID"},d=Math.ceil((t-s+1)/a),h=Math.ceil((n-i+1)/r);else if(typeof e=="object"){let p=l==="channelsLast"?e[1][0]:e[2][0],c=l==="channelsLast"?e[1][1]:e[2][1],m=l==="channelsLast"?e[2][0]:e[3][0],f=l==="channelsLast"?e[2][1]:e[3][1];u={top:p,bottom:c,left:m,right:f,type:p===0&&c===0&&m===0&&f===0?"VALID":"EXPLICIT"},d=Ki((t-s+p+c)/a+1,o),h=Ki((n-i+m+f)/r+1,o)}else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:u,outHeight:d,outWidth:h}}function cG(e,t,n,a,r,s,i,o,l,u,d){let h,p,c,m;if(typeof e=="number"){h={top:e,bottom:e,left:e,right:e,front:e,back:e,type:e===0?"VALID":"NUMBER"};let f=hG([t,n,a,1],o,1,r,e,d);p=f[0],c=f[1],m=f[2]}else if(e==="same"){p=Math.ceil(t/r),c=Math.ceil(n/s),m=Math.ceil(a/i);let f=(p-1)*r+o-t,g=(c-1)*s+l-n,y=(m-1)*i+u-a,A=Math.floor(f/2),x=f-A,v=Math.floor(g/2),b=g-v,w=Math.floor(y/2),I=y-w;h={top:v,bottom:b,left:w,right:I,front:A,back:x,type:"SAME"}}else if(e==="valid")h={top:0,bottom:0,left:0,right:0,front:0,back:0,type:"VALID"},p=Math.ceil((t-o+1)/r),c=Math.ceil((n-l+1)/s),m=Math.ceil((a-u+1)/i);else throw Error(`Unknown padding parameter: ${e}`);return{padInfo:h,outDepth:p,outHeight:c,outWidth:m}}function Ki(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 Ls(e){let[t,n,a]=If(e);return t===1&&n===1&&a===1}function Mr(e,t){return Ls(e)||Ls(t)}function J4(e){if(e==="NHWC")return"channelsLast";if(e==="NCHW")return"channelsFirst";throw new Error(`Unknown dataFormat ${e}`)}function fG(e,t){let n={x:F(e,"x","reshape","string_or_numeric")},a={shape:t};return j.runKernel(Qd,n,a)}var Y=B({reshape_:fG});function mG(e,t,n,a,r){let s=F(e,"x","avgPool","float32"),i=1;P(Mr(n,i),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`);let o=s,l=!1;s.rank===3&&(l=!0,o=Y(s,[1,s.shape[0],s.shape[1],s.shape[2]])),P(o.rank===4,()=>`Error in avgPool: x must be rank 4 but got rank ${o.rank}.`),r!=null&&P(mn(a),()=>`Error in avgPool: pad must be an integer when using, dimRoundingMode ${r} but got pad ${a}.`);let u={x:o},d={filterSize:t,strides:n,pad:a,dimRoundingMode:r},h=j.runKernel(Jo,u,d);return h=we(h,s.dtype),l?Y(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var Sf=B({avgPool_:mG});function gG(e,t,n,a,r,s="NDHWC"){let i=F(e,"x","avgPool3d","float32"),o=i,l=!1;i.rank===4&&(l=!0,o=Y(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),P(o.rank===5,()=>`Error in avgPool3d: x must be rank 5 but got rank ${o.rank}.`),P(s==="NDHWC",()=>`Error in avgPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),r!=null&&P(mn(a),()=>`Error in avgPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${a}.`);let u={x:o},d={filterSize:t,strides:n,pad:a,dimRoundingMode:r,dataFormat:s},h=j.runKernel(Kc,u,d);return h=we(h,o.dtype),l?Y(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var Q4=B({avgPool3d_:gG});function yG(e,t=0){P(e.length>=1,()=>"Pass at least one tensor to concat");let n=Af(e,"tensors","concat","string_or_numeric");if(n[0].dtype==="complex64"&&n.forEach(s=>{if(s.dtype!=="complex64")throw new Error(`Cannot concatenate complex64 tensors with a tensor with dtype ${s.dtype}. `)}),n.length===1)return Gi(n[0]);let a=n,r={axis:t};return j.runKernel(Cd,a,r)}var en=B({concat_:yG});function AG(e){let t={x:F(e,"x","sigmoid")};return j.runKernel(Rl,t)}var $r=B({sigmoid_:AG});function xG(e,t,n){let a=F(e,"x","slice","string_or_numeric");if(a.rank===0)throw new Error("Slicing scalar is not possible");let r={x:a},s={begin:t,size:n};return j.runKernel(ah,r,s)}var nt=B({slice_:xG});function bG(e){let t={x:F(e,"x","tanh")};return j.runKernel(zl,t)}var Kl=B({tanh_:bG});function vG(e,t,n,a,r,s){let i=F(e,"forgetBias","basicLSTMCell"),o=F(t,"lstmKernel","basicLSTMCell"),l=F(n,"lstmBias","basicLSTMCell"),u=F(a,"data","basicLSTMCell"),d=F(r,"c","basicLSTMCell"),h=F(s,"h","basicLSTMCell"),p=en([u,h],1),c=it(p,o),m=pe(c,l),f=m.shape[0],g=m.shape[1]/4,y=[f,g],A=nt(m,[0,0],y),x=nt(m,[0,g],y),v=nt(m,[0,g*2],y),b=nt(m,[0,g*3],y),w=pe(K($r(A),Kl(x)),K(d,$r(pe(i,v)))),I=K(Kl(w),$r(b));return[w,I]}var ywe=B({basicLSTMCell_:vG});function wG(e,t,n){let a=F(e,"x","batchToSpaceND"),r=t.reduce((o,l)=>o*l);P(a.rank>=1+t.length,()=>`input rank is ${a.rank} but should be > than blockShape.length ${t.length}`),P(n.length===t.length,()=>`crops.length is ${n.length} but should be equal to blockShape.length ${t.length}`),P(a.shape[0]%r==0,()=>`input tensor batch is ${a.shape[0]} but is not divisible by the product of the elements of blockShape ${t.join(" * ")} === ${r}`);let s={x:a},i={blockShape:t,crops:n};return j.runKernel(Xc,s,i)}var Nf=B({batchToSpaceND_:wG});function kG(e){let t;return e.rank===0||e.rank===1?t=Y(e,[1,1,1,e.size]):e.rank===2?t=Y(e,[1,1,e.shape[0],e.shape[1]]):e.rank===3?t=Y(e,[1,e.shape[0],e.shape[1],e.shape[2]]):t=e,t}function IG(e,t,n,a,r,s){s==null&&(s=.001);let i=F(e,"x","batchNorm"),o=F(t,"mean","batchNorm"),l=F(n,"variance","batchNorm"),u;r!=null&&(u=F(r,"scale","batchNorm"));let d;a!=null&&(d=F(a,"offset","batchNorm")),P(o.rank===l.rank,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),P(d==null||o.rank===d.rank,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),P(u==null||o.rank===u.rank,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let h={x:kG(i),scale:u,offset:d,mean:o,variance:l},p={varianceEpsilon:s},c=j.runKernel(dl,h,p);return Y(c,i.shape)}var Xl=B({batchNorm_:IG});function SG(e,t,n,a,r,s){let i=F(e,"x","batchNorm"),o=F(t,"mean","batchNorm"),l=F(n,"variance","batchNorm"),u;r!=null&&(u=F(r,"scale","batchNorm"));let d;return a!=null&&(d=F(a,"offset","batchNorm")),P(i.rank===2,()=>`Error in batchNorm2D: x must be rank 2 but got rank ${i.rank}.`),P(o.rank===2||o.rank===1,()=>`Error in batchNorm2D: mean must be rank 2 or rank 1 but got rank ${o.rank}.`),P(l.rank===2||l.rank===1,()=>`Error in batchNorm2D: variance must be rank 2 or rank 1 but got rank ${l.rank}.`),u!=null&&P(u.rank===2||u.rank===1,()=>`Error in batchNorm2D: scale must be rank 2 or rank 1 but got rank ${u.rank}.`),d!=null&&P(d.rank===2||d.rank===1,()=>`Error in batchNorm2D: offset must be rank 2 or rank 1 but got rank ${d.rank}.`),Xl(i,o,l,d,u,s)}var NG=B({batchNorm2d_:SG});function TG(e,t,n,a,r,s){let i=F(e,"x","batchNorm"),o=F(t,"mean","batchNorm"),l=F(n,"variance","batchNorm"),u;r!=null&&(u=F(r,"scale","batchNorm"));let d;return a!=null&&(d=F(a,"offset","batchNorm")),P(i.rank===3,()=>`Error in batchNorm3D: x must be rank 3 but got rank ${i.rank}.`),P(o.rank===3||o.rank===1,()=>`Error in batchNorm3D: mean must be rank 3 or rank 1 but got rank ${o.rank}.`),P(l.rank===3||l.rank===1,()=>`Error in batchNorm3D: variance must be rank 3 or rank 1 but got rank ${l.rank}.`),u!=null&&P(u.rank===3||u.rank===1,()=>`Error in batchNorm3D: scale must be rank 3 or rank 1 but got rank ${u.rank}.`),d!=null&&P(d.rank===3||d.rank===1,()=>`Error in batchNorm3D: offset must be rank 3 or rank 1 but got rank ${d.rank}.`),Xl(i,o,l,d,u,s)}var EG=B({batchNorm3d_:TG});function CG(e,t,n,a,r,s){let i=F(e,"x","batchNorm"),o=F(t,"mean","batchNorm"),l=F(n,"variance","batchNorm"),u;r!=null&&(u=F(r,"scale","batchNorm"));let d;return a!=null&&(d=F(a,"offset","batchNorm")),P(i.rank===4,()=>`Error in batchNorm4D: x must be rank 4 but got rank ${i.rank}.`),P(o.rank===4||o.rank===1,()=>`Error in batchNorm4D: mean must be rank 4 or rank 1 but got rank ${o.rank}.`),P(l.rank===4||l.rank===1,()=>`Error in batchNorm4D: variance must be rank 4 or rank 1 but got rank ${l.rank}.`),u!=null&&P(u.rank===4||u.rank===1,()=>`Error in batchNorm4D: scale must be rank 4 or rank 1 but got rank ${u.rank}.`),d!=null&&P(d.rank===4||d.rank===1,()=>`Error in batchNorm4D: offset must be rank 4 or rank 1 but got rank ${d.rank}.`),Xl(i,o,l,d,u,s)}var MG=B({batchNorm4d_:CG});function $G(e,t,n){let a=F(e,"x","bincount"),r=F(t,"weights","bincount");P(a.dtype==="int32",()=>`Error in bincount: input dtype must be int32, but got ${a.dtype}`),P(n>=0,()=>`size must be non-negative, but got ${n}.`),P(r.size===a.size||r.size===0,()=>`Error in bincount: weights must have the same size as input or0-length, but got input shape: ${a.shape}, weights shape: ${r.shape}.`);let s={x:a,weights:r},i={size:n};return j.runKernel(k1,s,i)}var e8=B({bincount_:$G});function RG(e,t){let n=F(e,"broadcastTo","x"),a=n.shape;if(t.some(l=>!(l>0)||l%1!=0))throw new Error(`broadcastTo(): Invalid broadcast shape [${t}].`);if(t.lengthn.rank){let l=n.shape.slice();for(;l.length=0;l--)if(r[l]===t[l])s[l]=1;else if(n.shape[l]!==1)throw new Error(`broadcastTo(): [${a}] cannot be broadcast to [${t}].`);if(s.map((l,u)=>l>1?u:-1).filter(l=>l>=0).length===0)return Gi(n);let i={x:n},o={reps:s};return j.runKernel(Pi,i,o)}var Sh=B({broadcastTo_:RG});function FG(e){let t={x:F(e,"x","ceil")};return j.runKernel(Ni,t)}var t8=B({ceil_:FG});function OG(e,t,n){let a=F(e,"x","clipByValue");P(t<=n,()=>`Error in clip: min (${t}) must be less than or equal to max (${n}).`);let r={x:a},s={clipValueMin:t,clipValueMax:n};return j.runKernel(Ti,r,s)}var ua=B({clipByValue_:OG});function DG(e){return en(e,0)}var _G=B({concat1d_:DG});function zG(e,t){return en(e,t)}var PG=B({concat2d_:zG});function LG(e,t){return en(e,t)}var WG=B({concat3d_:LG});function BG(e,t){return en(e,t)}var VG=B({concat4d_:BG});function UG(e,t,n,a,r="NHWC",s=[1,1],i){let o=F(e,"x","conv2d"),l=F(t,"filter","conv2d"),u=o,d=!1;o.rank===3&&(d=!0,u=Y(o,[1,o.shape[0],o.shape[1],o.shape[2]])),P(u.rank===4,()=>`Error in conv2d: input must be rank 4, but got rank ${u.rank}.`),P(l.rank===4,()=>`Error in conv2d: filter must be rank 4, but got rank ${l.rank}.`),i!=null&&P(mn(a),()=>`Error in conv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${a}.`);let h=r==="NHWC"?u.shape[3]:u.shape[1];P(h===l.shape[2],()=>`Error in conv2d: depth of input (${h}) must match input depth for filter ${l.shape[2]}.`),P(Mr(n,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`);let p={x:u,filter:l},c={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i},m=j.runKernel(tl,p,c);return d?Y(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var Ws=B({conv2d_:UG});function jG(e,t,n,a,r="NWC",s=1,i){let o=F(e,"x","conv1d"),l=F(t,"filter","conv1d"),u=o,d=!1;o.rank===2&&(d=!0,u=Y(o,[1,o.shape[0],o.shape[1]])),P(u.rank===3,()=>`Error in conv1d: input must be rank 3, but got rank ${u.rank}.`),P(l.rank===3,()=>`Error in conv1d: filter must be rank 3, but got rank ${l.rank}.`),i!=null&&P(mn(a),()=>`Error in conv1d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${a}.`),P(u.shape[2]===l.shape[1],()=>`Error in conv1d: depth of input (${u.shape[2]}) must match input depth for filter ${l.shape[1]}.`),P(Mr(n,s),()=>`Error in conv1D: Either stride or dilation must be 1. Got stride ${n} and dilation '${s}'`),P(r==="NWC",()=>`Error in conv1d: got dataFormat of ${r} but only NWC is currently supported.`);let h=Y(l,[1,l.shape[0],l.shape[1],l.shape[2]]),p=Y(u,[u.shape[0],1,u.shape[1],u.shape[2]]),c=Ws(p,h,[1,n],a,"NHWC",[1,s],i);return d?Y(c,[c.shape[2],c.shape[3]]):Y(c,[c.shape[0],c.shape[2],c.shape[3]])}var DA=B({conv1d_:jG});function HG(e,t,n,a,r,s="NHWC",i){P(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let o=e,l=t,u=!1;t.rank===3&&(u=!0,l=Y(t,[1,t.shape[0],t.shape[1],t.shape[2]]),o=[1,e[0],e[1],e[2]]),P(o.length===4,()=>`Error in conv2dDerInput: inShape must be length 4, but got length ${o.length}.`),P(l.rank===4,()=>`Error in conv2dDerInput: dy must be rank 4, but got rank ${l.rank}`),P(n.rank===4,()=>`Error in conv2dDerInput: filter must be rank 4, but got rank ${n.rank}`);let d=s==="NHWC"?o[3]:o[1],h=s==="NHWC"?l.shape[3]:l.shape[1];P(d===n.shape[2],()=>`Error in conv2dDerInput: depth of input (${d}) must match input depth for filter ${n.shape[2]}.`),P(h===n.shape[3],()=>`Error in conv2dDerInput: depth of output (${h}) must match output depth for filter ${n.shape[3]}.`),i!=null&&P(mn(r),()=>`Error in conv2dDerInput: pad must be an integer when using, dimRoundingMode ${i} but got pad ${r}.`);let p={dy:l,filter:n},c={strides:a,pad:r,dataFormat:s,dimRoundingMode:i,inputShape:o},m=j.runKernel(nl,p,c);return u?Y(m,[m.shape[1],m.shape[2],m.shape[3]]):m}var _A=B({conv2DBackpropInput_:HG});function GG(e,t,n,a,r,s){let i=F(e,"x","conv2dTranspose"),o=F(t,"filter","conv2dTranspose");return _A(n,i,o,a,r,"NHWC",s)}var zA=B({conv2dTranspose_:GG});function qG(e,t,n,a,r="NDHWC",s=[1,1,1]){let i=F(e,"x","conv3d"),o=F(t,"filter","conv3d"),l=i,u=!1;i.rank===4&&(u=!0,l=Y(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),P(l.rank===5,()=>`Error in conv3d: input must be rank 5, but got rank ${l.rank}.`),P(o.rank===5,()=>`Error in conv3d: filter must be rank 5, but got rank ${o.rank}.`),P(l.shape[4]===o.shape[3],()=>`Error in conv3d: depth of input (${l.shape[4]}) must match input depth for filter ${o.shape[3]}.`),P(Mr(n,s),()=>`Error in conv3D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),P(r==="NDHWC",()=>`Error in conv3d: got dataFormat of ${r} but only NDHWC is currently supported.`);let d={x:l,filter:o},h={strides:n,pad:a,dataFormat:r,dilations:s},p=j.runKernel(Yc,d,h);return u?Y(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var n8=B({conv3d_:qG});function KG(e,t,n,a,r){P(e.length===t.rank,()=>`Length of inShape (${e.length}) and rank of dy (${t.rank}) must match`);let s=e,i=t,o=!1;t.rank===4&&(o=!0,i=Y(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]]),s=[1,e[0],e[1],e[2],e[3]]);let l=s[4],u=i.shape[4];P(s.length===5,()=>`Error in conv3dDerInput: inShape must be length 5, but got length ${s.length}.`),P(i.rank===5,()=>`Error in conv3dDerInput: dy must be rank 5, but got rank ${i.rank}`),P(n.rank===5,()=>`Error in conv3dDerInput: filter must be rank 5, but got rank ${n.rank}`),P(l===n.shape[3],()=>`Error in conv3dDerInput: depth of input (${l}) must match input depth for filter ${n.shape[3]}.`),P(u===n.shape[4],()=>`Error in conv3dDerInput: depth of output (${u}) must match output depth for filter ${n.shape[4]}.`);let d={dy:i,filter:n},h={pad:r,strides:a,inputShape:s},p=j.runKernel(T1,d,h);return o?Y(p,[p.shape[1],p.shape[2],p.shape[3],p.shape[4]]):p}var a8=B({conv3DBackpropInput_:KG});function XG(e,t,n,a,r){let s=F(e,"x","conv3dTranspose"),i=F(t,"filter","conv3dTranspose");return a8(n,s,i,a,r)}var ZG=B({conv3dTranspose_:XG});function YG(e){let t={x:F(e,"x","cos")};return j.runKernel(al,t)}var Tf=B({cos_:YG});function JG(e){let t={x:F(e,"x","cosh")};return j.runKernel(Md,t)}var PA=B({cosh_:JG});function QG(e,t=0,n=!1,a=!1){let r={x:F(e,"x","cumsum")},s={axis:t,exclusive:n,reverse:a};return j.runKernel(rl,r,s)}var LA=B({cumsum_:QG});function eq(e,t,n,a=!1){let r=F(e,"x","denseBincount"),s=F(t,"weights","denseBincount");P(r.dtype==="int32",()=>`Error in denseBincount: input dtype must be int32, but got ${r.dtype}`),P(r.rank<=2,()=>`Error in denseBincount: input must be at most rank 2, but got rank ${r.rank}.`),P(n>=0,()=>`size must be non-negative, but got ${n}.`),P(s.size===r.size||s.size===0,()=>`Error in denseBincount: weights must have the same shape as x or 0-length, but got x shape: ${r.shape}, weights shape: ${s.shape}.`);let i={x:r,weights:s},o={size:n,binaryOutput:a};return j.runKernel(E1,i,o)}var tq=B({denseBincount_:eq});function nq(e,t,n="NHWC"){let a=F(e,"x","depthToSpace"),r=n==="NHWC"?a.shape[1]:a.shape[2],s=n==="NHWC"?a.shape[2]:a.shape[3],i=n==="NHWC"?a.shape[3]:a.shape[1];P(r*t>=0,()=>`Negative dimension size caused by overflow when multiplying ${r} and ${t} for depthToSpace with input shape ${a.shape}`),P(s*t>=0,()=>`Negative dimension size caused by overflow when multiplying ${s} and ${t} for depthToSpace with input shape ${a.shape}`),P(i%(t*t)==0,()=>`Dimension size must be evenly divisible by ${t*t} but is ${i} for depthToSpace with input shape ${a.shape}`);let o={x:a},l={blockSize:t,dataFormat:n};return j.runKernel(Rd,o,l)}var r8=B({depthToSpace_:nq});function aq(e,t,n,a,r="NHWC",s=[1,1],i){let o=F(e,"x","depthwiseConv2d"),l=F(t,"filter","depthwiseConv2d"),u=o,d=!1;o.rank===3&&(d=!0,u=Y(o,[1,o.shape[0],o.shape[1],o.shape[2]])),P(u.rank===4,()=>`Error in depthwiseConv2d: input must be rank 4, but got rank ${u.rank}.`),P(l.rank===4,()=>`Error in depthwiseConv2d: filter must be rank 4, but got rank ${l.rank}.`),P(u.shape[3]===l.shape[2],()=>`Error in depthwiseConv2d: number of input channels (${u.shape[3]}) must match the inChannels dimension in filter ${l.shape[2]}.`),i!=null&&P(mn(a),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${a}.`);let h={x:u,filter:l},p={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i},c=j.runKernel(sl,h,p);return d?Y(c,[c.shape[1],c.shape[2],c.shape[3]]):c}var Nh=B({depthwiseConv2d_:aq});function rq(e){let t={x:F(e,"x","diag")};return j.runKernel($1,t)}var Awe=B({diag_:rq});function sq(e,t,n,a,r=[1,1],s="NHWC"){let i=F(e,"x","dilation2d"),o=F(t,"filter","dilation2d");P(i.rank===3||i.rank===4,()=>`Error in dilation2d: input must be rank 3 or 4, but got rank ${i.rank}.`),P(o.rank===3,()=>`Error in dilation2d: filter must be rank 3, but got rank ${o.rank}.`),P(s==="NHWC",()=>`Error in dilation2d: Only NHWC is currently supported, but got dataFormat of ${s}`);let l=i,u=!1;i.rank===3&&(l=Y(i,[1,i.shape[0],i.shape[1],i.shape[2]]),u=!0);let d={x:l,filter:o},h={strides:n,pad:a,dilations:r},p=j.runKernel(Jc,d,h);return u?Y(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var s8=B({dilation2d_:sq});function iq(e,t){let n=e.length,a=[];for(let r=0;r1&&i===1&&a.unshift(s)}return a}function ln(e,t){let n=[];for(let a=0;a1)&&n.unshift(s)}return n}function Rt(e,t){let n=[],a=Math.max(e.length,t.length);for(let r=0;r`Error in dot: inputs must all be rank 1 or 2, but got ranks ${n.rank} and ${a.rank}.`);let r=n.rank===1?n.size:n.shape[1],s=a.rank===1?a.size:a.shape[0];if(P(r===s,()=>`Error in dot: inner dimensions of inputs must match, but got ${r} and ${s}.`),n.rank===1&&a.rank===1){let i=Y(n,[1,-1]),o=Y(a,[-1,1]),l=it(i,o);return Y(l,[])}else if(n.rank===1&&a.rank===2){let i=Y(n,[1,-1]),o=Y(a,[a.shape[0],a.shape[1]]),l=it(i,o);return Y(l,[l.size])}else if(n.rank===2&&a.rank===1){let i=Y(a,[-1,1]),o=it(n,i);return Y(o,[o.size])}else{let i=Y(a,[a.shape[0],a.shape[1]]);return it(n,i)}}var pq=B({dot_:hq});function cq(e,...t){let n=t.map((r,s)=>F(r,`tensors${s}`,"einsum")),a={equation:e};return j.runKernel(O1,n,a)}var fq=B({einsum_:cq});function mq(e){let t={x:F(e,"x","elu")};return j.runKernel(Fd,t)}var Th=B({elu_:mq});function gq(e){let t=F(e,"x","erf");P(t.dtype==="int32"||t.dtype==="float32",()=>"Input dtype must be `int32` or `float32`."),t.dtype==="int32"&&(t=we(t,"float32"));let n={x:t};return j.runKernel(Od,n)}var o8=B({erf_:gq});function yq(e){let t={x:F(e,"x","exp")};return j.runKernel(Ei,t)}var qa=B({exp_:yq});function Aq(e,t=0){let n=F(e,"x","expandDims","string_or_numeric");P(t<=n.rank,()=>"Axis must be <= rank of the tensor");let a={input:n},r={dim:t};return j.runKernel(Dd,a,r)}var Ea=B({expandDims_:Aq});function xq(e){let t={x:F(e,"x","expm1")};return j.runKernel(ll,t)}var l8=B({expm1_:xq});function bq(e,t){let n=F(e,"x","tile","string_or_numeric");P(n.rank===t.length,()=>`Error in transpose: rank of input ${n.rank} must match length of reps ${t}.`);let a={x:n},r={reps:t};return j.runKernel(Pi,a,r)}var Zi=B({tile_:bq});function vq(e,t,n,a="float32"){t==null&&(t=e);let r=Pe([e,t],a),s=e<=t?e:t;for(let o=0;o`Error in localResponseNormalization: x must be rank 3 or 4 but got rank ${s.rank}.`),P(mn(t),()=>`Error in localResponseNormalization: depthRadius must be an integer but got depthRadius ${t}.`);let i=s,o=!1;s.rank===3&&(o=!0,i=Y(s,[1,s.shape[0],s.shape[1],s.shape[2]]));let l={x:i},u={depthRadius:t,bias:n,alpha:a,beta:r},d=j.runKernel(nf,l,u);return o?Y(d,[d.shape[1],d.shape[2],d.shape[3]]):d}var h8=B({localResponseNormalization_:_q});function zq(e){let t={x:F(e,"x","log")};return j.runKernel($i,t)}var Ma=B({log_:zq});function Pq(e){let t={x:F(e,"x","log1p")};return j.runKernel(Vd,t)}var VA=B({log1p_:Pq});function Lq(e,t){P(jc(e),()=>"The f passed in variableGrads(f) must be a function"),P(t==null||Array.isArray(t)&&t.every(u=>u instanceof gf),()=>"The varList passed in variableGrads(f, varList) must be an array of variables");let n=t!=null;if(!n){t=[];for(let u in j.registeredVariables)t.push(j.registeredVariables[u])}let a=n?t.filter(u=>!u.trainable):null,r=t.length;t=t.filter(u=>u.trainable),P(t.length>0,()=>`variableGrads() expects at least one of the input variables to be trainable, but none of the ${r} variables is trainable.`);let s=!0,{value:i,grads:o}=j.gradients(e,t,null,s);P(o.some(u=>u!=null),()=>"Cannot find a connection between any variable and the result of the loss function y=f(x). Please make sure the operations that use variables are inside the function f passed to minimize()."),P(i.rank===0,()=>`The f passed in variableGrads(f) must return a scalar, but it returned a rank-${i.rank} tensor`);let l={};return t.forEach((u,d)=>{o[d]!=null&&(l[u.name]=o[d])}),a!=null&&a.forEach(u=>l[u.name]=null),{value:i,grads:l}}function ss(e){return j.customGrad(e)}function Wq(e){let t={x:F(e,"x","neg")};return j.runKernel(Hd,t)}var Kt=B({neg_:Wq});function Bq(e){let t={x:F(e,"x","softplus")};return j.runKernel(ih,t)}var Zl=B({softplus_:Bq});function Vq(e){let t=F(e,"x","logSigmoid");return ss(n=>({value:Kt(Zl(Kt(n))),gradFunc:a=>K(a,$r(Kt(n)))}))(t)}var Uq=B({logSigmoid_:Vq});function jq(e,t=null,n=!1){let a={x:F(e,"x","max")},r={reductionIndices:t,keepDims:n};return j.runKernel(gl,a,r)}var sr=B({max_:jq});function Hq(e,t){let n=F(e,"a","sub"),a=F(t,"b","sub");[n,a]=Ut(n,a);let r={a:n,b:a};return j.runKernel(zi,r)}var Ne=B({sub_:Hq});function Gq(e,t=null,n=!1){let a=F(e,"x","sum");a.dtype==="bool"&&(a=we(a,"int32"));let r={x:a},s={axis:t,keepDims:n};return j.runKernel(Ol,r,s)}var Ce=B({sum_:Gq});function qq(e,t=-1){let n=F(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 ss((a,r)=>{let s=!0,i=sr(a,t,!0),o=Ne(a,i),l=Ne(we(o,"float32"),Ma(Ce(qa(o),t,s)));return r([l]),{value:l,gradFunc:(u,d)=>{let[h]=d,p=!0,c=qa(h);return Ne(u,K(Ce(u,t,p),c))}}})(n)}var UA=B({logSoftmax_:qq});function jA(e,t){for(let n=0;ne[s]);return[n,r]}function Qi(e,t){let n=t.map(a=>1);return p8(e,n,t)}function Kq(e,t,n){P(jA(t,n),()=>`${e} supports only inner-most axes for now. Got axes ${t} and rank-${n} input.`)}function f8(e,t){if(jA(e,t))return null;let n=[];for(let a=0;an.push(a)),n}function HA(e){return e.map((t,n)=>[n,t]).sort((t,n)=>t[1]-n[1]).map(t=>t[0])}function Xq(e,t){let n=[];for(let a=t-e;a`Error in maxPool: input must be rank 4 but got rank ${o.rank}.`),P(Mr(n,i),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${n} and dilations '${i}'`),r!=null&&P(mn(a),()=>`Error in maxPool: pad must be an integer when using, dimRoundingMode ${r} but got pad ${a}.`);let u={x:o},d={filterSize:t,strides:n,pad:a,dimRoundingMode:r},h=j.runKernel(yl,u,d);return l?Y(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var Mf=B({maxPool_:nK});function aK(e,t=[1,1,1],n,a,r,s="NDHWC"){let i=F(e,"x","maxPool3d"),o=i,l=!1;i.rank===4&&(l=!0,o=Y(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]])),P(o.rank===5,()=>`Error in maxPool3d: x must be rank 5 but got rank ${o.rank}.`),P(s==="NDHWC",()=>`Error in maxPool3d: Only NDHWC is currently supported, but got dataFormat of ${s}`),r!=null&&P(mn(a),()=>`Error in maxPool3d: pad must be an integer when using, dimRoundingMode ${r} but got pad ${a}.`);let u={x:o},d={filterSize:t,strides:n,pad:a,dimRoundingMode:r,dataFormat:s},h=j.runKernel(af,u,d);return l?Y(h,[h.shape[1],h.shape[2],h.shape[3],h.shape[4]]):h}var g8=B({maxPool3d_:aK});function rK(e,t,n,a,r=!1){let s={x:F(e,"x","maxPoolWithArgmax")},i={filterSize:t,strides:n,pad:a,includeBatchInIndex:r},o=j.runKernel(U1,s,i);return{result:o[0],indexes:o[1]}}var sK=B({maxPoolWithArgmax_:rK});function iK(e,t){let n=F(e,"a","maximum"),a=F(t,"b","maximum");[n,a]=Ut(n,a),n.dtype==="bool"&&(n=we(n,"int32"),a=we(a,"int32")),Rt(n.shape,a.shape);let r={a:n,b:a};return j.runKernel(Ri,r)}var is=B({maximum_:iK});function oK(e,t=null,n=!1){let a={x:F(e,"x","mean")},r={axis:t,keepDims:n};return j.runKernel(Al,a,r)}var Xt=B({mean_:oK});function un(e,t="float32"){if(t==="complex64"){let a=un(e,"float32"),r=un(e,"float32");return Vi(a,r)}let n=Gc(on(e),t);return j.makeTensor(n,e,t)}function os(e,t="float32"){if(t==="complex64"){let a=os(e,"float32"),r=un(e,"float32");return Vi(a,r)}let n=g1(on(e),t);return j.makeTensor(n,e,t)}function lK(e,t=null,n=!1){let a={x:F(e,"x","min")},r={axis:t,keepDims:n};return j.runKernel(xl,a,r)}var $f=B({min_:lK});function uK(e,t){let n=F(e,"a","minimum"),a=F(t,"b","minimum");[n,a]=Ut(n,a),n.dtype==="bool"&&(n=we(n,"int32"),a=we(a,"int32")),Rt(n.shape,a.shape);let r={a:n,b:a};return j.runKernel(Fi,r)}var $h=B({minimum_:uK});function dK(e,t,n){P(n==="reflect"||n==="symmetric",()=>`Invalid mode. Mode must be either reflect or symmetric. Got ${n}.`);let a=F(e,"x","mirrorPad");if(a.rank===0)throw new Error("mirrorPad(scalar) is not defined. Pass non-scalar to mirrorPad");P(t.length===a.rank,()=>`Padding doesn't match input. Must be ${a.rank}. Got ${t.length}.`);let r=n==="reflect"?1:0;for(let o=0;o"Invalid number of paddings. Must be length of 2 each."),P(t[o][0]>=0&&t[o][0]<=a.shape[o]-r&&t[o][1]>=0&&t[o][1]<=a.shape[o]-r,()=>`Padding in dimension ${o} cannot be greater than or equal to ${a.shape[o]-r} or less than 0 for input of shape ${a.shape}`);let s={paddings:t,mode:n},i={x:a};return j.runKernel(bl,i,s)}var y8=B({mirrorPad_:dK});function hK(e,t){let n=F(e,"a","mod"),a=F(t,"b","mod");[n,a]=Ut(n,a);let r={a:n,b:a};return j.runKernel(jd,r)}var A8=B({mod_:hK});function pK(e){let t=F(e,"x","square"),n={};return j.runKernel("Square",{x:t},n)}var vt=B({square_:pK});function cK(e,t=null,n=!1){e=F(e,"x","moments");let a=Ha(t,e.shape),r=Xt(e,a,n),s=r.shape;n||(s=Qi(r.shape,a));let i=vt(Ne(we(e,"float32"),Y(r,s))),o=Xt(i,a,n);return{mean:r,variance:o}}var qA=B({moments_:cK});function fK(e,t,n,a){let r=F(t,"data","multiRNNCell"),s=Af(n,"c","multiRNNCell"),i=Af(a,"h","multiRNNCell"),o=r,l=[];for(let h=0;h2)throw new Error(`Rank of probabilities must be 1 or 2, but is ${i}`);n=n||Math.random();let o={logits:i===1?Y(r,[1,-1]):r},l={numSamples:t,seed:n,normalized:a},u=j.runKernel(j1,o,l);return i===1?Y(u,[u.size]):u}var gK=B({multinomial_:mK});function yK(e,t){let n=F(e,"a","notEqual","string_or_numeric"),a=F(t,"b","notEqual","string_or_numeric");[n,a]=Ut(n,a),Rt(n.shape,a.shape);let r={a:n,b:a};return j.runKernel(vl,r)}var Yl=B({notEqual_:yK});function AK(e){let t={x:F(e,"x","onesLike")};return j.runKernel(Xd,t)}var $a=B({onesLike_:AK});function xK(e,t){let n=F(e,"v1","outerProduct"),a=F(t,"v2","outerProduct");P(n.rank===1&&a.rank===1,()=>`Error in outerProduct: inputs must be rank 1, but got ranks ${n.rank} and ${a.rank}.`);let r=Y(n,[-1,1]),s=Y(a,[1,-1]);return it(r,s)}var bwe=B({outerProduct_:xK});function bK(e,t,n=0){let a=F(e,"x","pad");if(a.rank===0)throw new Error("pad(scalar) is not defined. Pass non-scalar to pad");let r={paddings:t,constantValue:n},s={x:a};return j.runKernel(kl,s,r)}var Bs=B({pad_:bK});function vK(e,t,n=0){return P(t.length===2,()=>"Invalid number of paddings. Must be length of 2."),Bs(e,[t],n)}var vwe=B({pad1d_:vK});function wK(e,t,n=0){return P(t.length===2&&t[0].length===2&&t[1].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Bs(e,t,n)}var wwe=B({pad2d_:wK});function kK(e,t,n=0){return P(t.length===3&&t[0].length===2&&t[1].length===2&&t[2].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Bs(e,t,n)}var kwe=B({pad3d_:kK});function IK(e,t,n=0){return P(t.length===4&&t[0].length===2&&t[1].length===2&&t[2].length===2&&t[3].length===2,()=>"Invalid number of paddings. Must be length of 2 each."),Bs(e,t,n)}var Iwe=B({pad4d_:IK});function SK(e,t,n){let a=F(e,"x","spaceToBatchND");P(a.rank>=1+t.length,()=>`input rank ${a.rank} should be > than [blockShape] ${t.length}`),P(n.length===t.length,()=>`paddings.shape[0] ${n.length} must be equal to [blockShape] ${t.length}`),P(a.shape.reduce((i,o,l)=>l>0&&l<=t.length?i&&(o+n[l-1][0]+n[l-1][1])%t[l-1]==0:i,!0),()=>`input spatial dimensions ${a.shape.slice(1)} with paddings ${n.toString()} must be divisible by blockShapes ${t.toString()}`);let r={x:a},s={blockShape:t,paddings:n};return j.runKernel(of,r,s)}var Rf=B({spaceToBatchND_:SK});function NK(e,t,n,a,r,s){r==null&&(r=[1,1]),s==null&&(s=1),a===0&&(a="valid");let i=F(e,"x","maxPool"),o=i,l=!1;i.rank===3&&(l=!0,o=Y(i,[1,i.shape[0],i.shape[1],i.shape[2]])),P(Mr(s,r),()=>`Error in pool: Either strides or dilations must be 1. Got strides ${s} and dilations '${r}'`);let u=Z4(o.shape,t,s,r,a),d=[u.dilationHeight,u.dilationWidth],h;a==="same"?h=EK([u.filterHeight,u.filterWidth],d):h=[[0,0],[0,0]];let p=d[0]===1&&d[1]===1,[c,m]=TK([u.inHeight,u.inWidth],d,h),f=p?a:"valid",g=p?o:Rf(o,d,c),y=(n==="avg"?()=>Sf(g,t,s,f):()=>Mf(g,t,s,f))(),A=p?y:Nf(y,d,m);return l?Y(A,[A.shape[1],A.shape[2],A.shape[3]]):A}function TK(e,t,n){let a=n.map(d=>d[0]),r=n.map(d=>d[1]),s=e.concat(a,r),i=t.map((d,h)=>(d-s[h]%d)%d),o=r.map((d,h)=>d+i[h]),l=t.map((d,h)=>[a[h],o[h]]),u=t.map((d,h)=>[0,i[h]]);return[l,u]}function EK(e,t){let n=e.map((s,i)=>s+(s-1)*(t[i]-1)).map(s=>s-1),a=n.map(s=>Math.floor(s/2)),r=n.map((s,i)=>s-a[i]);return n.map((s,i)=>[a[i],r[i]])}var CK=B({pool_:NK});function MK(e,t){let n=F(e,"base","pow"),a=F(t,"exp","pow");[n,a]=Ut(n,a);let r={a:n,b:a};return j.runKernel(Il,r)}var Vs=B({pow_:MK});function $K(e,t){let n=F(e,"x","prelu"),a=F(t,"alpha","prelu"),r={x:n,alpha:a};return j.runKernel(Sl,r)}var Ff=B({prelu_:$K});function RK(e,t=null,n=!1){let a=F(e,"x","prod");a.dtype==="bool"&&(a=we(a,"int32"));let r={x:a},s={axis:t,keepDims:n};return j.runKernel(Yd,r,s)}var KA=B({prod_:RK});function FK(e,t,n){let a=on(e),r=null;if(n==null||n==="float32")r=new Float32Array(a);else if(n==="int32")r=new Int32Array(a);else if(n==="bool")r=new Uint8Array(a);else throw new Error(`Unknown data type ${n}`);for(let s=0;s=1||s===0);let i=Math.sqrt(-2*Math.log(s)/s);e=this.mean+this.stdDev*a*i,t=this.mean+this.stdDev*r*i,(!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}},OK=class{constructor(e,t,n,a){this.alpha=e,this.beta=1/t,this.dtype=n;let r=a||Math.random();this.randu=XA.alea(r.toString()),this.randn=new ZA(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,a,r,s;for(;;){do a=this.randn.nextValue(),s=1+this.c*a;while(s<=0);if(s*=s*s,e=a*a,t=1-.331*e*e,n=.5*e+this.d*(1-s+Math.log(s)),r=this.randu(),rthis.dtype==null||this.dtype==="float32",this.min=e,this.range=t-e,this.dtype=n,a==null&&(a=Math.random()),typeof a=="number"&&(a=a.toString()),!this.canReturnFloat()&&this.range<=1)throw new Error(`The difference between ${e} - ${t} <= 1 and dtype is not float`);this.random=XA.alea(a)}convertValue(e){return this.canReturnFloat()?e:Math.round(e)}nextValue(){return this.convertValue(this.min+this.range*this.random())}};function _K(e,t,n=1,a="float32",r){if(n==null&&(n=1),a==null&&(a="float32"),a!=="float32"&&a!=="int32")throw new Error(`Unsupported data type ${a}`);let s=new OK(t,n,a,r),i=Pe(e,a);for(let o=0;o`Error in reverse1D: x must be rank 1 but got rank ${t.rank}.`),Ra(t,0)}var Twe=B({reverse1d_:HK});function GK(e,t){let n=F(e,"x","reverse");return P(n.rank===2,()=>`Error in reverse2D: x must be rank 2 but got rank ${n.rank}.`),Ra(n,t)}var Ewe=B({reverse2d_:GK});function qK(e,t){let n=F(e,"x","reverse");return P(n.rank===3,()=>`Error in reverse3D: x must be rank 3 but got rank ${n.rank}.`),Ra(n,t)}var Cwe=B({reverse3d_:qK});function KK(e,t){let n=F(e,"x","reverse");return P(n.rank===4,()=>`Error in reverse4D: x must be rank 4 but got rank ${n.rank}.`),Ra(n,t)}var Mwe=B({reverse4d_:KK});function XK(e){let t={x:F(e,"x","round")};return j.runKernel(Ml,t)}var JA=B({round_:XK});function ZK(e){let t={x:F(e,"x","rsqrt")};return j.runKernel(Di,t)}var QA=B({rsqrt_:ZK});function Re(e,t){if((ar(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"&&ar(e)&&!(e instanceof Uint8Array))throw new Error("When making a scalar from encoded string, the value must be `Uint8Array`.");return vh(e,[],[],t)}function YK(e){let t={x:F(e,"x","selu")};return j.runKernel(nh,t)}var e2=B({selu_:YK});function JK(e,t,n,a,r,s=[1,1],i="NHWC"){let o=F(e,"x","separableConv2d"),l=F(t,"depthwiseFilter","separableConv2d"),u=F(n,"pointwiseFilter","separableConv2d"),d=o,h=!1;if(o.rank===3&&(h=!0,d=Y(o,[1,o.shape[0],o.shape[1],o.shape[2]])),i==="NCHW")throw new Error("separableConv2d currently does not support dataFormat NCHW; only NHWC is supported");P(d.rank===4,()=>`Error in separableConv2d: input must be rank 4, but got rank ${d.rank}.`),P(l.rank===4,()=>`Error in separableConv2d: depthwise filter must be rank 4, but got rank ${l.rank}.`),P(u.rank===4,()=>`Error in separableConv2d: pointwise filter must be rank 4, but got rank ${l.rank}.`),P(u.shape[0]===1,()=>`Error in separableConv2d: the first dimension of pointwise filter must be 1, but got ${u.shape[0]}.`),P(u.shape[1]===1,()=>`Error in separableConv2d: the second dimension of pointwise filter must be 1, but got ${u.shape[1]}.`);let p=l.shape[2],c=l.shape[3];P(u.shape[2]===p*c,()=>`Error in separableConv2d: the third dimension of pointwise filter must be ${p*c}, but got ${u.shape[2]}.`);let m=Nh(d,l,a,r,i,s),f=Ws(m,u,1,"valid",i);return h?Y(f,[f.shape[1],f.shape[2],f.shape[3]]):f}var b8=B({separableConv2d_:JK});async function QK(e,t){let n=F(e,"x","setdiff1d"),a=F(t,"y","setdiff1d");P(n.dtype===a.dtype,()=>`x and y should have the same dtype, but got x (${n.dtype}) and y (${a.dtype}).`),P(n.rank===1,()=>`x should be 1D tensor, but got x (${n.shape}).`),P(a.rank===1,()=>`y should be 1D tensor, but got y (${a.shape}).`);let r=await n.data(),s=await a.data(),i=new Set(s),o=0;for(let d=0;d`slice1d expects a rank-1 tensor, but got a rank-${a.rank} tensor`),nt(a,[t],[n])}var a2=B({slice1d_:rX});function sX(e,t,n){let a=F(e,"x","slice2d");return P(a.rank===2,()=>`slice2d expects a rank-2 tensor, but got a rank-${a.rank} tensor`),nt(a,t,n)}var w8=B({slice2d_:sX});function iX(e,t,n){let a=F(e,"x","slice3d");return P(a.rank===3,()=>`slice3d expects a rank-3 tensor, but got a rank-${a.rank} tensor`),nt(a,t,n)}var r2=B({slice3d_:iX});function oX(e,t,n){let a=F(e,"x","slice4d");return P(a.rank===4,()=>`slice4d expects a rank-4 tensor, but got a rank-${a.rank} tensor`),nt(a,t,n)}var Df=B({slice4d_:oX});function lX(e,t=-1){let n=F(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 a={logits:n},r={dim:t};return j.runKernel(Dl,a,r)}var _f=B({softmax_:lX});function uX(e){P(e.dtype==="complex64",()=>`The dtype for tf.spectral.fft() must be complex64 but got ${e.dtype}.`);let t={input:e};return j.runKernel(_1,t)}var s2=B({fft_:uX});function dX(e){P(e.dtype==="complex64",()=>`The dtype for tf.spectral.ifft() must be complex64 but got ${e.dtype}.`);let t={input:e};return j.runKernel(z1,t)}var zf=B({ifft_:dX});function hX(e){let t=e.shape[e.shape.length-1],n=e.size/t,a;if(t<=2){let r=Y(e,[n,t]);a=zf(r)}else{let r=[n,2*(t-1)],s=Y(Of(e),[n,t]),i=Y(WA(e),[n,t]),o=Ra(nt(s,[0,1],[n,t-2]),1),l=K(Ra(nt(i,[0,1],[n,t-2]),1),Re(-1)),u=en([s,o],1),d=en([i,l],1),h=Y(Vi(u,d),[r[0],r[1]]);a=zf(h)}if(a=Of(a),e.rank===3&&e.shape[0]!==0){let r=a,s=e.shape[0];a=Y(a,[s,a.shape[0]/s,a.shape[1]]),r.dispose()}return a}var k8=B({irfft_:hX});function pX(e,t,n=0){let a={x:F(e,"x","split")},r={numOrSizeSplits:t,axis:n};return j.runKernel(oh,a,r)}var da=B({split_:pX});function cX(e,t){P(e.dtype==="float32",()=>`The dtype for rfft() must be real value but got ${e.dtype}`);let n=e.shape[e.shape.length-1],a=e.size/n,r;if(t!=null&&t0),f=e.shape.map(g=>g);f[e.shape.length-1]=t,r=nt(e,m,f),n=t}else if(t!=null&&t>n){let m=e.shape.map(f=>f);m[e.shape.length-1]=t-n,r=en([e,un(m)],e.shape.length-1),n=t}else r=e;let s=at(r),i=Y(Vi(r,s),[a,n]),o=s2(i),l=Math.floor(n/2)+1,u=Of(o),d=WA(o),h=da(u,[l,n-l],u.shape.length-1),p=da(d,[l,n-l],d.shape.length-1),c=r.shape.slice();return c[r.shape.length-1]=l,Y(Vi(h[0],p[0]),c)}var i2=B({rfft_:cX});function fX(e){let t={x:F(e,"x","sqrt")};return j.runKernel(Fl,t)}var Mn=B({sqrt_:fX});function mX(e,t){let n=F(e,"a","squaredDifference"),a=F(t,"b","squaredDifference");[n,a]=Ut(n,a),Rt(n.shape,a.shape);let r={a:n,b:a},s={};return j.runKernel(_i,r,s)}var o2=B({squaredDifference_:mX});function gX(e,t){let n=F(e,"x","squeeze");return Y(n,D6(n.shape,t).newShape)}var Jl=B({squeeze_:gX});function yX(e,t=0){let n=Af(e,"tensors","stack","string_or_numeric");P(n.length>=1,()=>"Pass at least one tensor to tf.stack"),n.length>0&&P(t<=n[0].rank,()=>"Axis must be <= rank of the tensor");let a=n,r={axis:t};return j.runKernel(Zd,a,r)}var Fa=B({stack_:yX});function AX(e,t=0){let n={x:F(e,"x","step")},a={alpha:t};return j.runKernel(Li,n,a)}var Oh=B({step_:AX});function xX(e,t,n,a,r=0,s=0,i=0,o=0,l=0){let u={x:F(e,"x","stridedSlice","string_or_numeric")},d={begin:t,end:n,strides:a,beginMask:r,endMask:s,ellipsisMask:i,newAxisMask:o,shrinkAxisMask:l};return j.runKernel(lh,u,d)}var I8=B({stridedSlice_:xX});function bX(e){let t={x:F(e,"x","tan")};return j.runKernel(_l,t)}var S8=B({tan_:bX});function $n(e,t){Bc(e);let n=bh(e,t);if(n.length!==1)throw new Error("tensor1d() requires values to be a flat/TypedArray");return vh(e,null,n,t)}function Ql(e,t,n){if(Bc(e),t!=null&&t.length!==2)throw new Error("tensor2d() requires shape to have two numbers");let a=bh(e,n);if(a.length!==2&&a.length!==1)throw new Error("tensor2d() requires values to be number[][] or flat/TypedArray");if(a.length===1&&t==null)throw new Error("tensor2d() requires shape to be provided when `values` are a flat/TypedArray");return vh(e,t,a,n)}function vX(e,t=1,n=!0){let a=F(e,"x","topk");if(a.rank===0)throw new Error("topk() expects the input to be of rank 1 or higher");let r=a.shape[a.shape.length-1];if(t>r)throw new Error(`'k' passed to topk() must be <= the last dimension (${r}) but got ${t}`);let s={x:a},i={k:t,sorted:n},[o,l]=j.runKernel(uh,s,i);return{values:o,indices:l}}var N8=B({topk_:vX});function wX(e,t=0,n=1,a,r){if(a!=null&&a==="bool")throw new Error("Unsupported data type $ { dtype }");let s=new ZA(t,n,a,!0,r),i=Pe(e,a);for(let o=0;o0,()=>"The input tensor must be at least 1D");let a={x:n},r={axis:t},[s,i]=j.runKernel(nA,a,r);return{values:s,indices:i}}var u2=B({unique_:kX});function IX(e,t,n){let a=F(e,"x","unsortedSegmentSum"),r=F(t,"segmentIds","unsortedSegmentSum","int32");P(mn(n),()=>"numSegments must be of dtype int");let s={x:a,segmentIds:r},i={numSegments:n};return j.runKernel(uf,s,i)}var T8=B({unsortedSegmentSum_:IX});function SX(e,t=0){let n=F(e,"x","unstack","string_or_numeric");P(t>=-n.shape.length&&t`Axis = ${t} is not in [-${n.shape.length}, ${n.shape.length})`);let a={value:n},r={axis:t};return j.runKernel(hh,a,r)}var or=B({unstack_:SX});function NX(e,t=!0,n,a){return j.makeVariable(e,t,n,a)}function E8(e,t){let n=[];for(let s=0;s"Shape mismatch in v and x");let l=Re(1),u=Ne(l,o),d=K(Ne(i,s),u);if(r){P(a!=null,()=>"When using zeroDebias: true, step is required.");let h=F(a,"step","movingAverage");d=Me(d,Ne(l,Vs(o,h)))}return pe(s,d)}var $we=B({movingAverage_:MX});function $X(e,t,n){let a=F(e,"indices","scatterND","int32"),r=F(t,"updates","scatterND");EA(r,a,n);let s={indices:a,updates:r},i={shape:n};return j.runKernel(eh,s,i)}var RX=B({scatterND_:$X});function FX(e,t,n,a){if(e.dtype!=="int32")throw new Error(`tf.sparseToDense() expects the indices to be int32 type, but the dtype was ${e.dtype}.`);if(e.rank>2)throw new Error(`sparseIndices should be a scalar, vector, or matrix, but got shape ${e.shape}.`);let r=e.rank>0?e.shape[0]:1,s=e.rank>1?e.shape[1]:1;if(n.length!==s)throw new Error(`outputShape has incorrect number of elements:, ${n.length}, should be: ${s}.`);let i=t.size;if(!(t.rank===0||t.rank===1&&i===r))throw new Error(`sparseValues has incorrect shape ${t.shape}, should be [] or [${r}]`);if(t.dtype!==a.dtype)throw new Error("sparseValues.dtype must match defaultValues.dtype")}function OX(e,t,n,a=0){let r=F(e,"sparseIndices","sparseToDense","int32"),s=F(t,"sparseValues","sparseToDense"),i=F(a,"defaultValue","sparseToDense",s.dtype);FX(r,s,n,i);let o={sparseIndices:r,sparseValues:s,defaultValue:i},l={outputShape:n};return j.runKernel(J1,o,l)}var M8=B({sparseToDense_:OX});function DX(e,t){let n=F(t,"indices","gatherND","int32"),a={params:F(e,"x","gatherND","string_or_numeric"),indices:n};return j.runKernel(Pd,a)}var _X=B({gatherND_:DX});function zX(e,t){if(t==null)return e.shape.slice();if(Fs(e.shape,t))return t;if(e.shape.length===t.length){let n=[];for(let a=0;a`x has to be a floating point tensor since it's going to be scaled, but got a ${r.dtype} tensor instead.`),P(t>=0&&t<1,()=>`rate must be a float in the range [0, 1), but got ${t}.`),t===0)return e instanceof Tt?r.clone():r;let s=zX(r,n),i=1-t,o=Me(Ch(pe(Rh(s,0,1,"float32",a),i)),i);return K(r,o)}var LX=B({dropout_:PX});function WX(e){return Math.floor(Math.pow(2,Math.ceil(Math.log(e)/Math.log(2))))}function $8(e,t,n){let a=1-e%2,r=new Float32Array(e);for(let s=0;sUX,depthwiseConv2d:()=>qX,matMul:()=>XX});function BX(e,t,n,a,r,s="NHWC",i){let o=e;e.rank===3&&(o=Y(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=Y(t,[1,t.shape[0],t.shape[1],t.shape[2]])),P(o.rank===4,()=>`Error in conv2dDerFilter: input must be rank 4, but got shape ${o.shape}.`),P(l.rank===4,()=>`Error in conv2dDerFilter: dy must be rank 4, but got shape ${l.shape}.`),P(n.length===4,()=>`Error in conv2dDerFilter: filterShape must be length 4, but got ${n}.`);let u=s==="NHWC"?o.shape[3]:o.shape[1],d=s==="NHWC"?l.shape[3]:l.shape[1];P(u===n[2],()=>`Error in conv2dDerFilter: depth of input ${u}) must match input depth in filter (${n[2]}.`),P(d===n[3],()=>`Error in conv2dDerFilter: depth of dy (${d}) must match output depth for filter (${n[3]}).`),i!=null&&P(mn(r),()=>`Error in conv2dDerFilter: pad must be an integer when using, dimRoundingMode ${i} but got pad ${r}.`);let h={x:o,dy:l},p={strides:a,pad:r,dataFormat:s,dimRoundingMode:i,filterShape:n};return j.runKernel(S1,h,p)}var h2=B({conv2DBackpropFilter_:BX});function Pf(e,t,n){if(n==null||n==="linear")return e;if(n==="relu")return K(e,Oh(t));throw new Error(`Cannot compute gradient for fused activation ${n}.`)}function Lf(e,t){let n=t,a=ln(e.shape,t.shape);return a.length>0&&(n=Ce(n,a)),Y(n,e.shape)}function Wf(e,t,n,a){if(t==="linear")return e;if(t==="relu")return ls(e);if(t==="elu")return Th(e);if(t==="relu6")return YA(e);if(t==="prelu")return Ff(e,n);if(t==="leakyrelu")return Ef(e,a);if(t==="sigmoid")return $r(e);throw new Error(`Unknown fused activation ${t}.`)}var Bf=(e,t)=>!(e>0)||t==="linear";function VX({x:e,filter:t,strides:n,pad:a,dataFormat:r="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:d}){if(l=l||"linear",Bf(j.state.gradientDepth,l)===!1){let b=Ws(e,t,n,a,r,s,i);return o!=null&&(b=pe(b,o)),Wf(b,l,u,d)}let h=F(e,"x","conv2d"),p=F(t,"filter","conv2d"),c=h,m=!1;h.rank===3&&(m=!0,c=Y(h,[1,h.shape[0],h.shape[1],h.shape[2]])),P(c.rank===4,()=>`Error in fused conv2d: input must be rank 4, but got rank ${c.rank}.`),P(p.rank===4,()=>`Error in fused conv2d: filter must be rank 4, but got rank ${p.rank}.`),i!=null&&P(mn(a),()=>`Error in fused conv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${a}.`),P(c.shape[3]===p.shape[2],()=>`Error in conv2d: depth of input (${c.shape[3]}) must match input depth for filter ${p.shape[2]}.`),P(Mr(n,s),()=>`Error in conv2D: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),P(r==="NHWC",()=>`Error in conv2d: got dataFormat of ${r} but only NHWC is currently supported.`);let f=Ih(c.shape,p.shape,n,s,a,i),g;o!=null&&(g=F(o,"bias","fused conv2d"),[g]=Ut(g,h),Rt(f.outShape,g.shape));let y;u!=null&&(y=F(u,"prelu weights","fused conv2d"));let A=(b,w)=>{let[I,T,C,z]=w,$=Pf(b,C,l);P(Ls(s),()=>`Error in gradient of fused conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`);let S=_A(T.shape,$,I,n,a),D=h2(T,$,I.shape,n,a),_=[S,D];if(z!=null){let W=Lf(z,$);_.push(W)}return _},x={x:c,filter:p,bias:g,preluActivationWeights:y},v={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:d};return o==null?ss((b,w,I)=>{let T=j.runKernel(Wl,x,v);return I([w,b,T]),m&&(T=Y(T,[T.shape[1],T.shape[2],T.shape[3]])),{value:T,gradFunc:A}})(c,p):ss((b,w,I,T)=>{let C=j.runKernel(Wl,x,v);return T([w,b,C,I]),m&&(C=Y(C,[C.shape[1],C.shape[2],C.shape[3]])),{value:C,gradFunc:A}})(c,p,g)}var UX=B({fusedConv2d_:VX});function jX(e,t,n,a,r,s=[1,1],i){let o=e;e.rank===3&&(o=Y(e,[1,e.shape[0],e.shape[1],e.shape[2]]));let l=t;l.rank===3&&(l=Y(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let u={x:o,dy:l},d={strides:a,pad:r,dimRoundingMode:i,dilations:s,filterShape:n};return j.runKernel(C1,u,d)}var R8=B({depthwiseConv2dNativeBackpropFilter_:jX});function HX(e,t,n,a,r,s=[1,1],i){let o=t,l=!1;t.rank===3&&(l=!0,o=Y(t,[1,t.shape[0],t.shape[1],t.shape[2]]));let u={dy:o,filter:n},d={strides:a,pad:r,dimRoundingMode:i,dilations:s,inputShape:e},h=j.runKernel(M1,u,d);return l?Y(h,[h.shape[1],h.shape[2],h.shape[3]]):h}var F8=B({depthwiseConv2dNativeBackpropInput_:HX});function GX({x:e,filter:t,strides:n,pad:a,dataFormat:r="NHWC",dilations:s=[1,1],dimRoundingMode:i,bias:o,activation:l="linear",preluActivationWeights:u,leakyreluAlpha:d}){if(Bf(j.state.gradientDepth,l)===!1){let b=Nh(e,t,n,a,r,s,i);return o!=null&&(b=pe(b,o)),Wf(b,l,u,d)}let h=F(e,"x","depthwiseConv2d"),p=F(t,"filter","depthwiseConv2d"),c=h,m=!1;h.rank===3&&(m=!0,c=Y(h,[1,h.shape[0],h.shape[1],h.shape[2]])),P(c.rank===4,()=>`Error in fused depthwiseConv2d: input must be rank 4, but got rank ${c.rank}.`),P(p.rank===4,()=>`Error in fused depthwiseConv2d: filter must be rank 4, but got rank ${p.rank}.`),P(c.shape[3]===p.shape[2],()=>`Error in fused depthwiseConv2d: number of input channels (${c.shape[3]}) must match the inChannels dimension in filter ${p.shape[2]}.`),s==null&&(s=[1,1]),P(Mr(n,s),()=>`Error in fused depthwiseConv2d: Either strides or dilations must be 1. Got strides ${n} and dilations '${s}'`),i!=null&&P(mn(a),()=>`Error in fused depthwiseConv2d: pad must be an integer when using dimRoundingMode ${i} but got pad ${a}.`);let f=Ih(c.shape,p.shape,n,s,a,i,!0),g;o!=null&&(g=F(o,"bias","fused conv2d"),[g]=Ut(g,h),Rt(f.outShape,g.shape));let y;u!=null&&(y=F(u,"prelu weights","fused depthwiseConv2d"));let A=(b,w)=>{P(Ls(s),()=>`Error in gradient of fused depthwiseConv2d: dilation rates greater than 1 are not yet supported. Got dilations '${s}'`);let[I,T,C,z]=w,$=Pf(b,C,l),S=F8(T.shape,$,I,n,a,s,i),D=R8(T,$,I.shape,n,a,s,i);if(z!=null){let _=Lf(g,$);return[S,D,_]}return[S,D]},x={x:c,filter:p,bias:g,preluActivationWeights:y},v={strides:n,pad:a,dataFormat:r,dilations:s,dimRoundingMode:i,activation:l,leakyreluAlpha:d};return o==null?ss((b,w,I)=>{let T=j.runKernel(Bl,x,v);return I([w,b,T]),m&&(T=Y(T,[T.shape[1],T.shape[2],T.shape[3]])),{value:T,gradFunc:A}})(c,p):ss((b,w,I,T)=>{let C=j.runKernel(Bl,x,v);return T([w,b,C,I]),m&&(C=Y(C,[C.shape[1],C.shape[2],C.shape[3]])),{value:C,gradFunc:A}})(c,p,g)}var qX=B({fusedDepthwiseConv2d_:GX});function KX({a:e,b:t,transposeA:n=!1,transposeB:a=!1,bias:r,activation:s="linear",preluActivationWeights:i,leakyreluAlpha:o}){if(Bf(j.state.gradientDepth,s)===!1){let z=it(e,t,n,a);return r!=null&&(z=pe(z,r)),Wf(z,s,i,o)}let l=F(e,"a","fused matMul"),u=F(t,"b","fused matMul");[l,u]=Ut(l,u);let d=n?l.shape[l.rank-2]:l.shape[l.rank-1],h=a?u.shape[u.rank-1]:u.shape[u.rank-2],p=n?l.shape[l.rank-1]:l.shape[l.rank-2],c=a?u.shape[u.rank-2]:u.shape[u.rank-1],m=l.shape.slice(0,-2),f=u.shape.slice(0,-2),g=on(m),y=on(f);P(l.rank>=2&&u.rank>=2&&l.rank===u.rank,()=>`Error in fused matMul: inputs must have the same rank of at least 2, got ranks ${l.rank} and ${u.rank}.`),P(Fs(m,f),()=>`Error in fused matMul: outer dimensions (${m}) and (${f}) of Tensors with shapes ${l.shape} and ${u.shape} must match.`),P(d===h,()=>`Error in fused matMul: inner shapes (${d}) and (${h}) of Tensors with shapes ${l.shape} and ${u.shape} and transposeA=${n} and transposeB=${a} must match.`);let A=l.shape.slice(0,-2).concat([p,c]),x=n?Y(l,[g,d,p]):Y(l,[g,p,d]),v=a?Y(u,[y,c,h]):Y(u,[y,h,c]),b;r!=null&&(b=F(r,"bias","fused matMul"),[b]=Ut(b,l),Rt(A,b.shape));let w;i!=null&&(w=F(i,"prelu weights","fused matMul"));let I=(z,$)=>{let[S,D,_,W]=$,X=Pf(Y(z,_.shape),_,s),q,Q;if(!n&&!a?(q=it(X,D,!1,!0),Q=it(S,X,!0,!1)):!n&&a?(q=it(X,D,!1,!1),Q=it(X,S,!0,!1)):n&&!a?(q=it(D,X,!1,!0),Q=it(S,X,!1,!1)):(q=it(D,X,!0,!0),Q=it(X,S,!0,!0)),r!=null){let ee=Lf(W,X);return[q,Q,ee]}else return[q,Q]},T={a:x,b:v,bias:b,preluActivationWeights:w},C={transposeA:n,transposeB:a,activation:s,leakyreluAlpha:o};return r==null?ss((z,$,S)=>{let D=j.runKernel(Ll,T,C);return S([z,$,D]),{value:Y(D,A),gradFunc:I}})(x,v):ss((z,$,S,D)=>{let _=j.runKernel(Ll,T,C);return D([z,$,_,S]),{value:Y(_,A),gradFunc:I}})(x,v,b)}var XX=B({fusedMatMul_:KX});function ZX(e){return $8(e,.54,.46)}var Rwe=B({hammingWindow_:ZX});function YX(e){return $8(e,.5,.5)}var JX=B({hannWindow_:YX});function QX(e,t,n,a=!1,r=0){let s=0,i=[];for(;s+t<=e.size;)i.push(nt(e,s,t)),s+=n;if(a)for(;s`Error in cropAndResize: image must be rank 4,but got rank ${i.rank}.`),P(o.rank===2&&o.shape[1]===4,()=>`Error in cropAndResize: boxes must be have size [${u},4] but had shape ${o.shape}.`),P(l.rank===1&&l.shape[0]===u,()=>`Error in cropAndResize: boxInd must be have size [${u}] but had shape ${o.shape}.`),P(a.length===2,()=>`Error in cropAndResize: cropSize must be of length 2, but got length ${a.length}.`),P(a[0]>=1&&a[1]>=1,()=>`cropSize must be atleast [1,1], but was ${a}`),P(r==="bilinear"||r==="nearest",()=>`method must be bilinear or nearest, but was ${r}`);let d={image:i,boxes:o,boxInd:l},h={method:r,extrapolationValue:s,cropSize:a};return j.runKernel($d,d,h)}var aZ=B({cropAndResize_:nZ});function rZ(e){let t=F(e,"image","flipLeftRight","float32");P(t.rank===4,()=>`Error in flipLeftRight: image must be rank 4,but got rank ${t.rank}.`);let n={image:t};return j.runKernel(_d,n,{})}var sZ=B({flipLeftRight_:rZ});function iZ(e,t,n=0,a=.5){let r=F(e,"image","rotateWithOffset","float32");P(r.rank===4,()=>`Error in rotateWithOffset: image must be rank 4,but got rank ${r.rank}.`);let s={image:r},i={radians:t,fillValue:n,center:a};return j.runKernel(ch,s,i)}var oZ=B({rotateWithOffset_:iZ});function eu(e,t,n,a,r,s){a==null&&(a=.5),r==null&&(r=Number.NEGATIVE_INFINITY),s==null&&(s=0);let i=e.shape[0];return n=Math.min(n,i),P(0<=a&&a<=1,()=>`iouThreshold must be in [0, 1], but was '${a}'`),P(e.rank===2,()=>`boxes must be a 2D tensor, but was of rank '${e.rank}'`),P(e.shape[1]===4,()=>`boxes must have 4 columns, but 2nd dimension was ${e.shape[1]}`),P(t.rank===1,()=>"scores must be a 1D tensor"),P(t.shape[0]===i,()=>`scores has incompatible shape with boxes. Expected ${i}, but was ${t.shape[0]}`),P(0<=s&&s<=1,()=>`softNmsSigma must be in [0, 1], but was '${s}'`),{maxOutputSize:n,iouThreshold:a,scoreThreshold:r,softNmsSigma:s}}function lZ(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY){let s=F(e,"boxes","nonMaxSuppression"),i=F(t,"scores","nonMaxSuppression"),o=eu(s,i,n,a,r);n=o.maxOutputSize,a=o.iouThreshold,r=o.scoreThreshold;let l={maxOutputSize:n,iouThreshold:a,scoreThreshold:r};return j.runKernel(Gd,{boxes:s,scores:i},l)}var uZ=B({nonMaxSuppression_:lZ});function dZ(e,t,n){let a=hZ(e,t,n),r=a<0?-(a+1):a;e.splice(r,0,t)}function hZ(e,t,n){return cZ(e,t,n||pZ)}function pZ(e,t){return e>t?1:e>>1);let o=n(t,e[s]);o>0?a=s+1:(r=s,i=!o)}return i?a:-a-1}function O8(e,t,n,a,r){return p2(e,t,n,a,r,0)}function D8(e,t,n,a,r,s){return p2(e,t,n,a,r,0,!1,s,!0)}function _8(e,t,n,a,r,s){return p2(e,t,n,a,r,s,!0)}function p2(e,t,n,a,r,s,i=!1,o=!1,l=!1){let u=[];for(let g=0;gr&&u.push({score:t[g],boxIndex:g,suppressBeginIndex:0});u.sort(z8);let d=s>0?-.5/s:0,h=[],p=[];for(;h.length0;){let g=u.pop(),{score:y,boxIndex:A,suppressBeginIndex:x}=g;if(y=x;--b){let w=fZ(e,A,h[b]);if(w>=a){v=!0;break}if(g.score=g.score*mZ(a,d,w),g.score<=r)break}g.suppressBeginIndex=h.length,v||(g.score===y?(h.push(A),p.push(g.score)):g.score>r&&dZ(u,g,z8))}let c=h.length,m=n-c;o&&m>0&&(h.push(...new Array(m).fill(0)),p.push(...new Array(m).fill(0)));let f={selectedIndices:h};return i&&(f.selectedScores=p),l&&(f.validOutputs=c),f}function fZ(e,t,n){let a=e.subarray(t*4,t*4+4),r=e.subarray(n*4,n*4+4),s=Math.min(a[0],a[2]),i=Math.min(a[1],a[3]),o=Math.max(a[0],a[2]),l=Math.max(a[1],a[3]),u=Math.min(r[0],r[2]),d=Math.min(r[1],r[3]),h=Math.max(r[0],r[2]),p=Math.max(r[1],r[3]),c=(o-s)*(l-i),m=(h-u)*(p-d);if(c<=0||m<=0)return 0;let f=Math.max(s,u),g=Math.max(i,d),y=Math.min(o,h),A=Math.min(l,p),x=Math.max(y-f,0)*Math.max(A-g,0);return x/(c+m-x)}function mZ(e,t,n){let a=Math.exp(t*n*n);return n<=e?a:0}function z8(e,t){return e.score-t.score||e.score===t.score&&t.boxIndex-e.boxIndex}async function gZ(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY){let s=F(e,"boxes","nonMaxSuppressionAsync"),i=F(t,"scores","nonMaxSuppressionAsync"),o=eu(s,i,n,a,r);n=o.maxOutputSize,a=o.iouThreshold,r=o.scoreThreshold;let l=await Promise.all([s.data(),i.data()]),u=l[0],d=l[1],{selectedIndices:h}=O8(u,d,n,a,r);return s!==e&&s.dispose(),i!==t&&i.dispose(),$n(h,"int32")}var yZ=gZ;function AZ(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=0){let i=F(e,"boxes","nonMaxSuppression"),o=F(t,"scores","nonMaxSuppression"),l=eu(i,o,n,a,r,s);n=l.maxOutputSize,a=l.iouThreshold,r=l.scoreThreshold,s=l.softNmsSigma;let u={boxes:i,scores:o},d={maxOutputSize:n,iouThreshold:a,scoreThreshold:r,softNmsSigma:s},h=j.runKernel(Kd,u,d);return{selectedIndices:h[0],selectedScores:h[1]}}var xZ=B({nonMaxSuppressionWithScore_:AZ});async function bZ(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=0){let i=F(e,"boxes","nonMaxSuppressionAsync"),o=F(t,"scores","nonMaxSuppressionAsync"),l=eu(i,o,n,a,r,s);n=l.maxOutputSize,a=l.iouThreshold,r=l.scoreThreshold,s=l.softNmsSigma;let u=await Promise.all([i.data(),o.data()]),d=u[0],h=u[1],{selectedIndices:p,selectedScores:c}=_8(d,h,n,a,r,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:$n(p,"int32"),selectedScores:$n(c)}}var vZ=bZ;function wZ(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=!1){let i=F(e,"boxes","nonMaxSuppression"),o=F(t,"scores","nonMaxSuppression"),l=eu(i,o,n,a,r,null),u=l.maxOutputSize,d=l.iouThreshold,h=l.scoreThreshold,p={boxes:i,scores:o},c={maxOutputSize:u,iouThreshold:d,scoreThreshold:h,padToMaxOutputSize:s},m=j.runKernel(qd,p,c);return{selectedIndices:m[0],validOutputs:m[1]}}var kZ=B({nonMaxSuppressionPadded_:wZ});async function IZ(e,t,n,a=.5,r=Number.NEGATIVE_INFINITY,s=!1){let i=F(e,"boxes","nonMaxSuppressionAsync"),o=F(t,"scores","nonMaxSuppressionAsync"),l=eu(i,o,n,a,r,null),u=l.maxOutputSize,d=l.iouThreshold,h=l.scoreThreshold,[p,c]=await Promise.all([i.data(),o.data()]),{selectedIndices:m,validOutputs:f}=D8(p,c,u,d,h,s);return i!==e&&i.dispose(),o!==t&&o.dispose(),{selectedIndices:$n(m,"int32"),validOutputs:Re(f,"int32")}}var SZ=IZ;function NZ(e,t,n=!1,a=!1){let r=F(e,"images","resizeBilinear");P(r.rank===3||r.rank===4,()=>`Error in resizeBilinear: x must be rank 3 or 4, but got rank ${r.rank}.`),P(t.length===2,()=>`Error in resizeBilinear: new shape must 2D, but got shape ${t}.`),P(a===!1||n===!1,()=>"Error in resizeBilinear: If halfPixelCenters is true, alignCorners must be false.");let s=r,i=!1;r.rank===3&&(i=!0,s=Y(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,o={images:s},l={alignCorners:n,halfPixelCenters:a,size:t},u=j.runKernel(Tl,o,l);return i?Y(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var P8=B({resizeBilinear_:NZ});function TZ(e,t,n=!1,a=!1){let r=F(e,"images","resizeNearestNeighbor");P(r.rank===3||r.rank===4,()=>`Error in resizeNearestNeighbor: x must be rank 3 or 4, but got rank ${r.rank}.`),P(t.length===2,()=>`Error in resizeNearestNeighbor: new shape must 2D, but got shape ${t}.`),P(r.dtype==="float32"||r.dtype==="int32",()=>"`images` must have `int32` or `float32` as dtype"),P(a===!1||n===!1,()=>"Error in resizeNearestNeighbor: If halfPixelCenters is true, alignCorners must be false.");let s=r,i=!1;r.rank===3&&(i=!0,s=Y(r,[1,r.shape[0],r.shape[1],r.shape[2]]));let[]=t,o={images:s},l={alignCorners:n,halfPixelCenters:a,size:t},u=j.runKernel(sf,o,l);return i?Y(u,[u.shape[1],u.shape[2],u.shape[3]]):u}var L8=B({resizeNearestNeighbor_:TZ});function EZ(e,t="binary",n=!1,a=.5){let r=F(e,"image","threshold"),s=.2989,i=.587,o=.114,l=r.shape[0]*r.shape[1],u=K($n([a]),255),d,h,p,c;if(P(r.rank===3,()=>`Error in threshold: image must be rank 3,but got rank ${r.rank}.`),P(r.shape[2]===3||r.shape[2]===1,()=>`Error in threshold: image color channel must be equal to 3 or 1but got ${r.shape[2]}.`),P(r.dtype==="int32"||r.dtype==="float32",()=>`Error in dtype: image dtype must be int32 or float32,but got dtype ${r.dtype}.`),P(t==="otsu"||t==="binary",()=>`Method must be binary or otsu, but was ${t}`),r.shape[2]===3){[d,h,p]=da(r,[1,1,1],-1);let f=K(d,s),g=K(h,i),y=K(p,o);c=pe(pe(f,g),y)}else c=e;if(t==="otsu"){let f=e8(we(JA(c),"int32"),Cr([]),256);u=CZ(f,l)}let m=n?Ji(c,u):Ca(c,u);return we(K(m,255),"int32")}function CZ(e,t){let n=$n([-1]),a=$n([0]),r=$n([0]),s,i,o,l,u,d;for(let h=0;h`Error in transform: image must be rank 4,but got rank ${i.rank}.`),P(o.rank===2&&(o.shape[0]===i.shape[0]||o.shape[0]===1)&&o.shape[1]===8,()=>"Error in transform: Input transform should be batch x 8 or 1 x 8"),P(s==null||s.length===2,()=>`Error in transform: outputShape must be [height, width] or null, but got ${s}.`);let l={image:i,transforms:o},u={interpolation:n,fillMode:a,fillValue:r,outputShape:s};return j.runKernel(dh,l,u)}var RZ=B({transform_:$Z});function FZ(e,t,n){P(t%1==0,()=>`bandPart(): numLower must be an integer, got ${t}.`),P(n%1==0,()=>`bandPart(): numUpper must be an integer, got ${n}.`);let a=F(e,"a","bandPart");P(a.rank>=2,()=>`bandPart(): Rank must be at least 2, got ${a.rank}.`);let r=a.shape,[s,i]=a.shape.slice(-2);if(!(t<=s))throw new Error(`bandPart(): numLower (${t}) must not be greater than the number of rows (${s}).`);if(!(n<=i))throw new Error(`bandPart(): numUpper (${n}) must not be greater than the number of columns (${i}).`);t<0&&(t=s),n<0&&(n=i);let o=Y(Fh(0,s,1,"int32"),[-1,1]),l=Fh(0,i,1,"int32"),u=Ne(o,l),d=ir(Ji(u,Re(+t,"int32")),Yi(u,Re(-n,"int32"))),h=un([s,i],a.dtype);return Y(Fa(or(Y(a,[-1,s,i])).map(p=>Pn(d,p,h))),r)}var OZ=B({bandPart_:FZ});function DZ(e){let t;if(Array.isArray(e)){t=!1,P(e!=null&&e.length>0,()=>"Gram-Schmidt process: input must not be null, undefined, or empty");let r=e[0].shape[0];for(let s=1;s`Gram-Schmidt: Non-unique lengths found in the input vectors: (${e[s].shape[0]} vs. ${r})`)}else t=!0,e=da(e,e.shape[0],0).map(r=>Jl(r,[0]));P(e.length<=e[0].shape[0],()=>`Gram-Schmidt: Number of vectors (${e.length}) exceeds number of dimensions (${e[0].shape[0]}).`);let n=[],a=e;for(let r=0;r{let s=a[r];if(r>0)for(let i=0;i=2,()=>`qr() requires input tensor to have a rank >= 2, but got rank ${e.rank}`),e.rank===2)return W8(e,t);{let n=e.shape.slice(0,e.shape.length-2).reduce((l,u)=>l*u),a=or(Y(e,[n,e.shape[e.shape.length-2],e.shape[e.shape.length-1]]),0),r=[],s=[];a.forEach(l=>{let[u,d]=W8(l,t);r.push(u),s.push(d)});let i=Y(Fa(r,0),e.shape),o=Y(Fa(s,0),e.shape);return[i,o]}}function W8(e,t=!1){return j.tidy(()=>{P(e.shape.length===2,()=>`qr2d() requires a 2D Tensor, but got a ${e.shape.length}D Tensor.`);let n=e.shape[0],a=e.shape[1],r=u8(n),s=Gi(e),i=Ql([[1]],[1,1]),o=Gi(i),l=n>=a?a:n;for(let u=0;u{let c=nt(s,[u,u],[n-u,1]),m=d2(c),f=nt(s,[u,u],[1,1]),g=Pn(Ca(f,0),Ql([[-1]]),Ql([[1]])),y=Ne(f,K(g,m)),A=Me(c,y);A.shape[0]===1?o=Gi(i):o=en([i,nt(A,[1,0],[A.shape[0]-1,A.shape[1]])],0);let x=Kt(Me(it(g,y),m)),v=nt(s,[u,0],[n-u,a]),b=K(x,o),w=ct(o);if(u===0)s=Ne(v,it(b,it(w,v)));else{let C=Ne(v,it(b,it(w,v)));s=en([nt(s,[0,0],[u,a]),C],0)}let I=ct(b),T=nt(r,[0,u],[n,r.shape[1]-u]);if(u===0)r=Ne(T,it(it(T,o),I));else{let C=Ne(T,it(it(T,o),I));r=en([nt(r,[0,0],[n,u]),C],1)}return[o,s,r]}),Ge([d,h,p])}return!t&&n>a&&(r=nt(r,[0,0],[n,a]),s=nt(s,[0,0],[a,a])),[r,s]})}var PZ=B({qr_:zZ}),Jn;(function(e){e[e.NONE=0]="NONE",e[e.MEAN=1]="MEAN",e[e.SUM=2]="SUM",e[e.SUM_BY_NONZERO_WEIGHTS=3]="SUM_BY_NONZERO_WEIGHTS"})(Jn||(Jn={}));function LZ(e,t,n=Jn.SUM_BY_NONZERO_WEIGHTS){let a=F(e,"losses","computeWeightedLoss"),r=null;t!=null&&(r=F(t,"weights","computeWeightedLoss"));let s=r==null?a:K(a,r);if(n===Jn.NONE)return s;if(n===Jn.SUM)return Ce(s);if(n===Jn.MEAN){if(r==null)return Xt(s);{let i=a.size/r.size,o=Me(Ce(s),Ce(r));return i>1?Me(o,Re(i)):o}}if(n===Jn.SUM_BY_NONZERO_WEIGHTS){if(r==null)return Me(Ce(s),Re(a.size));{let i=K(r,os(a.shape)),o=we(Ce(Yl(i,Re(0))),"float32");return Me(Ce(s),o)}}throw Error(`Unknown reduction: ${n}`)}var Us=B({computeWeightedLoss_:LZ});function WZ(e,t,n,a=Jn.SUM_BY_NONZERO_WEIGHTS){let r=F(e,"labels","absoluteDifference"),s=F(t,"predictions","absoluteDifference"),i=null;n!=null&&(i=F(n,"weights","absoluteDifference")),nr(r.shape,s.shape,"Error in absoluteDifference: ");let o=yn(Ne(r,s));return Us(o,i,a)}var Owe=B({absoluteDifference_:WZ});function BZ(e,t,n,a,r=Jn.SUM_BY_NONZERO_WEIGHTS){let s=F(e,"labels","cosineDistance"),i=F(t,"predictions","cosineDistance"),o=null;a!=null&&(o=F(a,"weights","cosineDistance")),nr(s.shape,i.shape,"Error in cosineDistance: ");let l=Re(1),u=Ne(l,Ce(K(s,i),n,!0));return Us(u,o,r)}var Dwe=B({cosineDistance_:BZ});function VZ(e,t,n,a=Jn.SUM_BY_NONZERO_WEIGHTS){let r=F(e,"labels","hingeLoss"),s=F(t,"predictions","hingeLoss"),i=null;n!=null&&(i=F(n,"weights","hingeLoss")),nr(r.shape,s.shape,"Error in hingeLoss: ");let o=Re(1);r=Ne(K(Re(2),r),o);let l=ls(Ne(o,K(r,s)));return Us(l,i,a)}var _we=B({hingeLoss_:VZ});function UZ(e,t,n,a=1,r=Jn.SUM_BY_NONZERO_WEIGHTS){let s=F(e,"labels","huberLoss"),i=F(t,"predictions","huberLoss"),o=null;n!=null&&(o=F(n,"weights","huberLoss")),nr(s.shape,i.shape,"Error in huberLoss: ");let l=Re(a),u=yn(Ne(i,s)),d=$h(u,l),h=Ne(u,d),p=pe(K(Re(.5),vt(d)),K(l,h));return Us(p,o,r)}var zwe=B({huberLoss_:UZ});function jZ(e,t,n,a=1e-7,r=Jn.SUM_BY_NONZERO_WEIGHTS){let s=F(e,"labels","logLoss"),i=F(t,"predictions","logLoss"),o=null;n!=null&&(o=F(n,"weights","logLoss")),nr(s.shape,i.shape,"Error in logLoss: ");let l=Re(1),u=Re(a),d=Kt(K(s,Ma(pe(i,u)))),h=K(Ne(l,s),Ma(pe(Ne(l,i),u))),p=Ne(d,h);return Us(p,o,r)}var Pwe=B({logLoss_:jZ});function HZ(e,t,n,a=Jn.SUM_BY_NONZERO_WEIGHTS){let r=F(e,"labels","meanSquaredError"),s=F(t,"predictions","meanSquaredError"),i=null;n!=null&&(i=F(n,"weights","meanSquaredError")),nr(r.shape,s.shape,"Error in meanSquaredError: ");let o=o2(r,s);return Us(o,i,a)}var Lwe=B({meanSquaredError_:HZ});function GZ(e,t){let n=F(e,"labels","sigmoidCrossEntropyWithLogits"),a=F(t,"logits","sigmoidCrossEntropyWithLogits");nr(n.shape,a.shape,"Error in sigmoidCrossEntropyWithLogits: ");let r=ls(a),s=K(a,n),i=VA(qa(Kt(yn(a))));return pe(Ne(r,s),i)}function qZ(e,t,n,a=0,r=Jn.SUM_BY_NONZERO_WEIGHTS){let s=F(e,"multiClassLabels","sigmoidCrossEntropy"),i=F(t,"logits","sigmoidCrossEntropy"),o=null;if(n!=null&&(o=F(n,"weights","sigmoidCrossEntropy")),nr(s.shape,i.shape,"Error in sigmoidCrossEntropy: "),a>0){let u=Re(a),d=Re(1),h=Re(.5);s=pe(K(s,Ne(d,u)),K(h,u))}let l=GZ(s,i);return Us(l,o,r)}var Wwe=B({sigmoidCrossEntropy_:qZ});function KZ(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 ss((a,r,s)=>{let i=m8(r,[n],!0),o=Ne(we(r,"float32"),i);s([a,o]);let l=Kt(K(o,a));return{value:Ce(l,[n]),gradFunc:(u,d)=>{let[h,p]=d,c=Qi(u.shape,[n]);return[K(Y(u,c),Ne(we(h,"float32"),qa(p))),K(Y(u,c),Ne(qa(p),we(h,"float32")))]}}})(e,t)}function XZ(e,t,n,a=0,r=Jn.SUM_BY_NONZERO_WEIGHTS){let s=F(e,"onehotLabels","softmaxCrossEntropy"),i=F(t,"logits","softmaxCrossEntropy"),o=null;if(n!=null&&(o=F(n,"weights","softmaxCrossEntropy")),nr(s.shape,i.shape,"Error in softmaxCrossEntropy: "),a>0){let u=Re(a),d=Re(1),h=Re(s.shape[1]);s=pe(K(s,Ne(d,u)),Me(u,h))}let l=KZ(s,i);return Us(l,o,r)}var Bwe=B({softmaxCrossEntropy_:XZ});function ZZ(e,t,n,a){let r=F(e,"indices","sparseFillEmptyRows"),s=F(t,"values","sparseFillEmptyRows"),i=F(n,"denseShape","sparseFillEmptyRows"),o=F(a,"defaultValue","sparseFillEmptyRows",s.dtype);if(r.rank!==2)throw new Error(`Indices should be Tensor2D but received shape ${r.shape}`);if(s.rank!==1)throw new Error(`Values should be Tensor1D but received shape ${s.shape}`);if(i.rank!==1)throw new Error(`Dense shape should be Tensor1D but received shape ${i.shape}`);if(o.rank!==0)throw new Error(`Default value should be a scalar but received shape ${o.shape}`);let l={indices:r,values:s,denseShape:i,defaultValue:o},u=j.runKernel(K1,l);return{outputIndices:u[0],outputValues:u[1],emptyRowIndicator:u[2],reverseIndexMap:u[3]}}var YZ=B({sparseFillEmptyRows_:ZZ});function JZ(e,t,n){let a=F(e,"inputIndices","sparseReshape"),r=F(t,"inputShape","sparseReshape"),s=F(n,"newShape","sparseReshape");if(a.rank!==2)throw new Error(`Input indices should be Tensor2D but received shape ${a.shape}`);if(r.rank!==1)throw new Error(`Input shape should be Tensor1D but received shape ${r.shape}`);if(s.rank!==1)throw new Error(`New shape should be Tensor1D but received shape ${s.shape}`);let i={inputIndices:a,inputShape:r,newShape:s},o=j.runKernel(X1,i);return{outputIndices:o[0],outputShape:o[1]}}var QZ=B({sparseReshape_:JZ});function eY(e,t,n){let a=F(e,"data","sparseSegmentMean"),r=F(t,"indices","sparseSegmentMean"),s=F(n,"segmentIds","sparseSegmentMean");if(a.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.rank!==1)throw new Error(`Indices should be Tensor1D but received shape ${r.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape ${s.shape}`);let i={data:a,indices:r,segmentIds:s};return j.runKernel(Z1,i)}var tY=B({sparseSegmentMean_:eY});function nY(e,t,n){let a=F(e,"data","sparseSegmentSum"),r=F(t,"indices","sparseSegmentSum"),s=F(n,"segmentIds","sparseSegmentSum");if(a.rank<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.rank!==1)throw new Error(`Indices should be Tensor1D but received shape ${r.shape}`);if(s.rank!==1)throw new Error(`Segment ids should be Tensor1D but received shape ${s.shape}`);let i={data:a,indices:r,segmentIds:s};return j.runKernel(Y1,i)}var aY=B({sparseSegmentSum_:nY});function rY(e,t,n,a,r,s,i,o){let l=F(e,"data","stringNGrams","string");if(l.dtype!=="string")throw new Error("Data must be of datatype string");if(l.shape.length!==1)throw new Error(`Data must be a vector, saw: ${l.shape}`);let u=F(t,"dataSplits","stringNGrams");if(u.dtype!=="int32")throw new Error("Data splits must be of datatype int32");let d={separator:n,nGramWidths:a,leftPad:r,rightPad:s,padWidth:i,preserveShortSequences:o},h={data:l,dataSplits:u},p=j.runKernel(Q1,h,d);return{nGrams:p[0],nGramsSplits:p[1]}}var sY=B({stringNGrams_:rY});function iY(e,t,n=!0){let a=F(e,"input","stringSplit","string"),r=F(t,"delimiter","stringSplit","string");if(a.rank!==1)throw new Error(`Input should be Tensor1D but received shape ${a.shape}`);if(r.rank!==0)throw new Error(`Delimiter should be a scalar but received shape ${r.shape}`);let s={skipEmpty:n},i={input:a,delimiter:r},o=j.runKernel(eA,i,s);return{indices:o[0],values:o[1],shape:o[2]}}var oY=B({stringSplit_:iY});function lY(e,t){let n=F(e,"input","stringToHashBucketFast","string"),a={numBuckets:t};if(t<=0)throw new Error("Number of buckets must be at least 1");let r={input:n};return j.runKernel(tA,r,a)}var uY=B({stringToHashBucketFast_:lY}),to={flipLeftRight:sZ,resizeNearestNeighbor:L8,resizeBilinear:P8,rotateWithOffset:oZ,cropAndResize:aZ,nonMaxSuppression:uZ,nonMaxSuppressionAsync:yZ,nonMaxSuppressionWithScore:xZ,nonMaxSuppressionWithScoreAsync:vZ,nonMaxSuppressionPadded:kZ,nonMaxSuppressionPaddedAsync:SZ,threshold:MZ,transform:RZ},dY={bandPart:OZ,gramSchmidt:_Z,qr:PZ},Vf={sparseFillEmptyRows:YZ,sparseReshape:QZ,sparseSegmentMean:tY,sparseSegmentSum:aY},c2={stringNGrams:sY,stringSplit:oY,stringToHashBucketFast:uY},js=class extends W4{minimize(e,t=!1,n){let{value:a,grads:r}=this.computeGradients(e,n);if(n!=null){let s=n.map(i=>({name:i.name,tensor:r[i.name]}));this.applyGradients(s)}else this.applyGradients(r);return Ge(r),t?a:(a.dispose(),null)}get iterations(){return this.iterations_==null&&(this.iterations_=0),this.iterations_}incrementIterations(){this.iterations_=this.iterations+1}computeGradients(e,t){return Lq(e,t)}dispose(){this.iterations_!=null&&Ge(this.iterations_)}async saveIterations(){return this.iterations_==null&&(this.iterations_=0),{name:"iter",tensor:Re(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(js,Symbol.hasInstance,{value:e=>e.minimize!=null&&e.computeGradients!=null&&e.applyGradients!=null});var f2=class extends js{constructor(e,t,n=null){super();this.learningRate=e,this.rho=t,this.epsilon=n,this.accumulatedGrads=[],this.accumulatedUpdates=[],n==null&&(this.epsilon=j.backend.epsilon())}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=j.registeredVariables[t],r=!1;this.accumulatedGrads[n]==null&&(this.accumulatedGrads[n]={originalName:`${t}/accum_grad`,variable:Z(()=>at(a).variable(r))}),this.accumulatedUpdates[n]==null&&(this.accumulatedUpdates[n]={originalName:`${t}/accum_var`,variable:Z(()=>at(a).variable(r))});let s=Array.isArray(e)?e[n].tensor:e[t];if(s==null)return;let i=this.accumulatedGrads[n].variable,o=this.accumulatedUpdates[n].variable;Z(()=>{let l=pe(K(i,this.rho),K(vt(s),1-this.rho)),u=K(Me(Mn(pe(o,this.epsilon)),Mn(pe(i,this.epsilon))),s),d=pe(K(o,this.rho),K(vt(u),1-this.rho));i.assign(l),o.assign(d);let h=pe(K(u,-this.learningRate),a);a.assign(h)})}),this.incrementIterations()}dispose(){this.accumulatedUpdates!=null&&(Ge(this.accumulatedGrads.map(e=>e.variable)),Ge(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(a=>({originalName:a.name,variable:a.tensor.variable(n)})),this.accumulatedUpdates=e.slice(t,t*2).map(a=>({originalName:a.name,variable:a.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)}};f2.className="Adadelta";zs(f2);var m2=class extends js{constructor(e,t=.1){super();this.learningRate=e,this.initialAccumulatorValue=t,this.accumulatedGrads=[]}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=j.registeredVariables[t];if(this.accumulatedGrads[n]==null){let i=!1;this.accumulatedGrads[n]={originalName:`${t}/accumulator`,variable:Z(()=>Eh(a.shape,this.initialAccumulatorValue).variable(i))}}let r=Array.isArray(e)?e[n].tensor:e[t];if(r==null)return;let s=this.accumulatedGrads[n].variable;Z(()=>{let i=pe(s,vt(r));s.assign(i);let o=pe(K(Me(r,Mn(pe(i,j.backend.epsilon()))),-this.learningRate),a);a.assign(o)})}),this.incrementIterations()}dispose(){this.accumulatedGrads!=null&&Ge(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)}};m2.className="Adagrad";zs(m2);var g2=class extends js{constructor(e,t,n,a=null){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=a,this.accumulatedFirstMoment=[],this.accumulatedSecondMoment=[],Z(()=>{this.accBeta1=Re(t).variable(),this.accBeta2=Re(n).variable()}),a==null&&(this.epsilon=j.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);Z(()=>{let n=Ne(1,this.accBeta1),a=Ne(1,this.accBeta2);t.forEach((r,s)=>{let i=j.registeredVariables[r],o=!1;this.accumulatedFirstMoment[s]==null&&(this.accumulatedFirstMoment[s]={originalName:`${r}/m`,variable:Z(()=>at(i).variable(o))}),this.accumulatedSecondMoment[s]==null&&(this.accumulatedSecondMoment[s]={originalName:`${r}/v`,variable:Z(()=>at(i).variable(o))});let l=Array.isArray(e)?e[s].tensor:e[r];if(l==null)return;let u=this.accumulatedFirstMoment[s].variable,d=this.accumulatedSecondMoment[s].variable,h=pe(K(u,this.beta1),K(l,1-this.beta1)),p=pe(K(d,this.beta2),K(vt(l),1-this.beta2)),c=Me(h,n),m=Me(p,a);u.assign(h),d.assign(p);let f=pe(K(Me(c,pe(Mn(m),this.epsilon)),-this.learningRate),i);i.assign(f)}),this.accBeta1.assign(K(this.accBeta1,this.beta1)),this.accBeta2.assign(K(this.accBeta2,this.beta2))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.accBeta2.dispose(),this.accumulatedFirstMoment!=null&&Ge(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedSecondMoment!=null&&Ge(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),Z(()=>{this.accBeta1.assign(Vs(this.beta1,this.iterations_+1)),this.accBeta2.assign(Vs(this.beta2,this.iterations_+1))});let t=e.length/2,n=!1;this.accumulatedFirstMoment=e.slice(0,t).map(a=>({originalName:a.name,variable:a.tensor.variable(n)})),this.accumulatedSecondMoment=e.slice(t,t*2).map(a=>({originalName:a.name,variable:a.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)}};g2.className="Adam";zs(g2);var y2=class extends js{constructor(e,t,n,a=null,r=0){super();this.learningRate=e,this.beta1=t,this.beta2=n,this.epsilon=a,this.decay=r,this.accumulatedFirstMoment=[],this.accumulatedWeightedInfNorm=[],Z(()=>{this.iteration=Re(0).variable(),this.accBeta1=Re(t).variable()}),a==null&&(this.epsilon=j.backend.epsilon())}applyGradients(e){let t=Array.isArray(e)?e.map(n=>n.name):Object.keys(e);Z(()=>{let n=Ne(1,this.accBeta1),a=Me(-this.learningRate,pe(K(this.iteration,this.decay),1));t.forEach((r,s)=>{let i=j.registeredVariables[r],o=!1;this.accumulatedFirstMoment[s]==null&&(this.accumulatedFirstMoment[s]={originalName:`${r}/m`,variable:at(i).variable(o)}),this.accumulatedWeightedInfNorm[s]==null&&(this.accumulatedWeightedInfNorm[s]={originalName:`${r}/v`,variable:at(i).variable(o)});let l=Array.isArray(e)?e[s].tensor:e[r];if(l==null)return;let u=this.accumulatedFirstMoment[s].variable,d=this.accumulatedWeightedInfNorm[s].variable,h=pe(K(u,this.beta1),K(l,1-this.beta1)),p=K(d,this.beta2),c=yn(l),m=is(p,c);u.assign(h),d.assign(m);let f=pe(K(Me(a,n),Me(h,pe(m,this.epsilon))),i);i.assign(f)}),this.iteration.assign(pe(this.iteration,1)),this.accBeta1.assign(K(this.accBeta1,this.beta1))}),this.incrementIterations()}dispose(){this.accBeta1.dispose(),this.iteration.dispose(),this.accumulatedFirstMoment!=null&&Ge(this.accumulatedFirstMoment.map(e=>e.variable)),this.accumulatedWeightedInfNorm!=null&&Ge(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)}};y2.className="Adamax";zs(y2);var Uf=class extends js{constructor(e){super();this.learningRate=e,this.setLearningRate(e)}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=Array.isArray(e)?e[n].tensor:e[t];if(a==null)return;let r=j.registeredVariables[t];Z(()=>{let s=pe(K(this.c,a),r);r.assign(s)})}),this.incrementIterations()}setLearningRate(e){this.learningRate=e,this.c!=null&&this.c.dispose(),this.c=Sn(Re(-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)}};Uf.className="SGD";zs(Uf);var A2=class extends Uf{constructor(e,t,n=!1){super(e);this.learningRate=e,this.momentum=t,this.useNesterov=n,this.accumulations=[],this.m=Re(this.momentum)}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=j.registeredVariables[t];if(this.accumulations[n]==null){let i=!1;this.accumulations[n]={originalName:`${t}/momentum`,variable:Z(()=>at(a).variable(i))}}let r=this.accumulations[n].variable,s=Array.isArray(e)?e[n].tensor:e[t];s!=null&&Z(()=>{let i,o=pe(K(this.m,r),s);this.useNesterov?i=pe(K(this.c,pe(s,K(o,this.m))),a):i=pe(K(this.c,o),a),r.assign(o),a.assign(i)})}),this.incrementIterations()}dispose(){this.m.dispose(),this.accumulations!=null&&Ge(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)}};A2.className="Momentum";zs(A2);var x2=class extends js{constructor(e,t=.9,n=0,a=null,r=!1){super();if(this.learningRate=e,this.decay=t,this.momentum=n,this.epsilon=a,this.accumulatedMeanSquares=[],this.accumulatedMoments=[],this.accumulatedMeanGrads=[],this.centered=r,a==null&&(this.epsilon=j.backend.epsilon()),e==null)throw new Error("learningRate for RMSPropOptimizer must be defined.")}applyGradients(e){(Array.isArray(e)?e.map(t=>t.name):Object.keys(e)).forEach((t,n)=>{let a=j.registeredVariables[t],r=!1;this.accumulatedMeanSquares[n]==null&&(this.accumulatedMeanSquares[n]={originalName:`${t}/rms`,variable:Z(()=>at(a).variable(r))}),this.accumulatedMoments[n]==null&&(this.accumulatedMoments[n]={originalName:`${t}/momentum`,variable:Z(()=>at(a).variable(r))}),this.accumulatedMeanGrads[n]==null&&this.centered&&(this.accumulatedMeanGrads[n]={originalName:`${t}/mg`,variable:Z(()=>at(a).variable(r))});let s=Array.isArray(e)?e[n].tensor:e[t];if(s==null)return;let i=this.accumulatedMeanSquares[n].variable,o=this.accumulatedMoments[n].variable;Z(()=>{let l=pe(K(i,this.decay),K(vt(s),1-this.decay));if(this.centered){let u=this.accumulatedMeanGrads[n].variable,d=pe(K(u,this.decay),K(s,1-this.decay)),h=Me(K(s,this.learningRate),Mn(Ne(l,pe(vt(d),this.epsilon)))),p=pe(K(o,this.momentum),h);i.assign(l),u.assign(d),o.assign(p);let c=Ne(a,p);a.assign(c)}else{let u=pe(K(i,this.decay),K(vt(s),1-this.decay)),d=pe(K(o,this.momentum),Me(K(s,this.learningRate),Mn(pe(u,this.epsilon))));i.assign(u),o.assign(d);let h=Ne(a,d);a.assign(h)}})}),this.incrementIterations()}dispose(){this.accumulatedMeanSquares!=null&&Ge(this.accumulatedMeanSquares.map(e=>e.variable)),this.accumulatedMeanGrads!=null&&this.centered&&Ge(this.accumulatedMeanGrads.map(e=>e.variable)),this.accumulatedMoments!=null&&Ge(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(a=>({originalName:a.name,variable:a.tensor.variable(n)})),this.accumulatedMoments=e.slice(t,t*2).map(a=>({originalName:a.name,variable:a.tensor.variable(n)})),this.centered&&(this.accumulatedMeanGrads=e.slice(t*2,t*3).map(a=>({originalName:a.name,variable:a.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)}};x2.className="RMSProp";zs(x2);var no=class{static sgd(e){return new Uf(e)}static momentum(e,t,n=!1){return new A2(e,t,n)}static rmsprop(e,t=.9,n=0,a=null,r=!1){return new x2(e,t,n,a,r)}static adam(e=.001,t=.9,n=.999,a=null){return new g2(e,t,n,a)}static adadelta(e=.001,t=.95,n=null){return new f2(e,t,n)}static adamax(e=.002,t=.9,n=.999,a=null,r=0){return new y2(e,t,n,a,r)}static adagrad(e,t=.1){return new m2(e,t)}},tu={sgd:no.sgd,momentum:no.momentum,adadelta:no.adadelta,adagrad:no.adagrad,rmsprop:no.rmsprop,adamax:no.adamax,adam:no.adam},hY=(()=>typeof requestAnimationFrame!="undefined"?requestAnimationFrame:typeof setImmediate!="undefined"?setImmediate:e=>e())();function b2(){return new Promise(e=>hY(()=>e()))}var M={};$e(M,{ERF_A1:()=>wY,ERF_A2:()=>kY,ERF_A3:()=>IY,ERF_A4:()=>SY,ERF_A5:()=>NY,ERF_P:()=>vY,PARALLELIZE_THRESHOLD:()=>v2,SELU_SCALE:()=>V8,SELU_SCALEALPHA:()=>B8,applyActivation:()=>Wf,assertAndGetBroadcastShape:()=>Rt,assertAxesAreInnerMostDims:()=>Kq,assertParamsConsistent:()=>pY,assignToTypedArray:()=>OY,axesAreInnerMostDims:()=>jA,calculateShapes:()=>E4,checkEinsumDimSizes:()=>WY,combineLocations:()=>p8,complexWithEvenIndex:()=>$Y,complexWithOddIndex:()=>RY,computeConv2DInfo:()=>Ih,computeConv3DInfo:()=>Y4,computeDefaultPad:()=>FA,computeDilation2DInfo:()=>lG,computeOptimalWindowSize:()=>fY,computeOutAndReduceShapes:()=>c8,computeOutShape:()=>cY,computePool2DInfo:()=>Z4,computePool3DInfo:()=>uG,convertConv2DDataFormat:()=>J4,decodeEinsumEquation:()=>PY,eitherStridesOrDilationsAreOne:()=>Mr,expandShapeToKeepDim:()=>Qi,exponent:()=>_Y,exponents:()=>DY,fromStringArrayToUint8:()=>XY,fromUint8ToStringArray:()=>KY,getAxesPermutation:()=>f8,getBroadcastDims:()=>iq,getComplexWithIndex:()=>FY,getEinsumComputePath:()=>BY,getEinsumPermutation:()=>LY,getFusedBiasGradient:()=>Lf,getFusedDyActivation:()=>Pf,getImageCenter:()=>mY,getInnerMostAxes:()=>Xq,getPermuted:()=>yY,getReductionAxes:()=>ln,getReshaped:()=>gY,getReshapedPermuted:()=>AY,getSliceBeginCoords:()=>xY,getSliceSize:()=>bY,getUndoAxesPermutation:()=>HA,isIdentityPermutation:()=>VY,log:()=>EY,mergeRealAndImagArrays:()=>CY,prepareAndValidate:()=>N4,prepareSplitSize:()=>jY,segment_util:()=>H8,shouldFuse:()=>Bf,slice_util:()=>Cn,splitRealAndImagArrays:()=>MY,tupleValuesAreOne:()=>Ls,upcastType:()=>Ga,validateInput:()=>EA,validateUpdateShape:()=>TA,warn:()=>TY});function pY(e,t){let n=e[0].length;e.forEach((r,s)=>{P(r.length===n,()=>`Error in concat${n}D: rank of tensors[${s}] must be the same as the rank of the rest (${n})`)}),P(t>=0&&t`Error in concat${n}D: axis must be between 0 and ${n-1}.`);let a=e[0];e.forEach((r,s)=>{for(let i=0;i`Error in concat${n}D: Shape of tensors[${s}] (${r}) does not match the shape of the rest (${a}) along the non-concatenated axis ${s}.`)})}function cY(e,t){let n=e[0].slice();for(let a=1;a=t*2+1||i%2==1?s.push(i):r.push(i);a.push(...r),a.push(0),a.push(...s)}return a}function AY(e,t,n,a=!0){let r=[];a?r.push(e[0]/n):r.push(e[0]*n);for(let s=1;s/g,U8=",",j8="...";function PY(e,t){e=e.replace(/\s/g,"");let n=(e.length-e.replace(zY,"").length)/w2.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 ("${w2}").`);let[a,r]=e.split(w2);P(a.indexOf(j8)===-1,()=>`The ellipsis notation ("${j8}") is not supported yet.`);let s=a.split(U8),i=s.length;if(t!==i)throw new Error(`Expected ${i} input tensors, received ${t}`);if(i>2)throw new Error("Support for more than 2 input tensors is not implemented yet.");let o=[];for(let p=0;pm.indexOf(c)!==-1))throw new Error(`Output subscripts contain the label ${c} not present in the input subscripts.`);o.indexOf(c)===-1&&o.push(c)}for(let p=0;pr!==-1),{permutationIndices:n,expandDims:a}}function WY(e,t,n){let a=new Array(e);for(let r=0;r`Expected dimension ${a[t[r][i]]} at axis ${i} of input shaped ${JSON.stringify(s)}, but got dimension ${s[i]}`)}}function BY(e,t){let n=e,a=[],r=0;e.length===0&&n.push(-1),r=e.length+1;for(let i=0;it===n)}function UY(e,t){let n=[];for(let a=0;a"Number of splits must evenly divide the axis."),a=new Array(t).fill(e.shape[n]/t);else{let r=t.reduce((i,o)=>(o===-1&&(i+=1),i),0);P(r<=1,()=>"There should be only one negative value in split array.");let s=t.indexOf(-1);if(s!==-1){let i=t.reduce((o,l)=>l>0?o+l:o);t[s]=e.shape[n]-i}P(e.shape[n]===t.reduce((i,o)=>i+o),()=>"The sum of sizes must match the size of the axis dimension."),a=t}return a}var H8={};$e(H8,{collectGatherOpShapeInfo:()=>qY,computeOutShape:()=>GY,segOpComputeOptimalWindowSize:()=>HY});function HY(e,t){let n=!1,a;for(e<=v2?(a=e,n=!0):a=Hc(e,Math.floor(Math.sqrt(e)));!n;)a>t||a===e?n=!0:a=Hc(e,a+1);return a}function GY(e,t,n){let a=[],r=e.length;for(let s=0;sr))throw new Error(`Expect batchDims in the range of [-${r}, ${r}], but got ${a}`);if(a<0&&(a+=r),a>s)throw new Error(`batchDims (${a}) must be less than rank(x) ( ${s}).`);if(nff(t))}catch(t){throw new Error(`Failed to decode encoded string bytes into utf-8, error: ${t}`)}}function XY(e){return e.map(t=>cf(t))}var us={};$e(us,{nonMaxSuppressionV3Impl:()=>O8,nonMaxSuppressionV4Impl:()=>D8,nonMaxSuppressionV5Impl:()=>_8,whereImpl:()=>E8});re().prototype.abs=function(){return this.throwIfDisposed(),yn(this)};re().prototype.acos=function(){return this.throwIfDisposed(),V4(this)};re().prototype.acosh=function(){return this.throwIfDisposed(),U4(this)};re().prototype.add=function(e){return this.throwIfDisposed(),pe(this,e)};re().prototype.all=function(e,t){return this.throwIfDisposed(),RA(this,e,t)};re().prototype.any=function(e,t){return this.throwIfDisposed(),wf(this,e,t)};re().prototype.argMax=function(e){return this.throwIfDisposed(),kf(this,e)};re().prototype.argMin=function(e){return this.throwIfDisposed(),j4(this,e)};re().prototype.asScalar=function(){return this.throwIfDisposed(),P(this.size===1,()=>"The array must have only 1 element."),Y(this,[])};re().prototype.asType=function(e){return this.throwIfDisposed(),we(this,e)};re().prototype.as1D=function(){return this.throwIfDisposed(),Y(this,[this.size])};re().prototype.as2D=function(e,t){return this.throwIfDisposed(),Y(this,[e,t])};re().prototype.as3D=function(e,t,n){return this.throwIfDisposed(),Y(this,[e,t,n])};re().prototype.as4D=function(e,t,n,a){return this.throwIfDisposed(),Y(this,[e,t,n,a])};re().prototype.as5D=function(e,t,n,a,r){return this.throwIfDisposed(),Y(this,[e,t,n,a,r])};re().prototype.asin=function(){return this.throwIfDisposed(),H4(this)};re().prototype.asinh=function(){return this.throwIfDisposed(),G4(this)};re().prototype.atan=function(){return this.throwIfDisposed(),q4(this)};re().prototype.atan2=function(e){return this.throwIfDisposed(),K4(this,e)};re().prototype.atanh=function(){return this.throwIfDisposed(),X4(this)};re().prototype.avgPool=function(e,t,n,a){return this.throwIfDisposed(),Sf(this,e,t,n,a)};re().prototype.batchToSpaceND=function(e,t){return this.throwIfDisposed(),Nf(this,e,t)};re().prototype.batchNorm=function(e,t,n,a,r){return this.throwIfDisposed(),Xl(this,e,t,n,a,r)};re().prototype.broadcastTo=function(e){return this.throwIfDisposed(),Sh(this,e)};re().prototype.cast=function(e){return this.throwIfDisposed(),we(this,e)};re().prototype.ceil=function(){return this.throwIfDisposed(),t8(this)};re().prototype.clipByValue=function(e,t){return this.throwIfDisposed(),ua(this,e,t)};re().prototype.concat=function(e,t){return this.throwIfDisposed(),e instanceof Tt&&(e=[e]),en([this,...e],t)};re().prototype.conv1d=function(e,t,n,a,r,s){return this.throwIfDisposed(),DA(this,e,t,n,a,r,s)};re().prototype.conv2dTranspose=function(e,t,n,a,r){return this.throwIfDisposed(),zA(this,e,t,n,a,r)};re().prototype.conv2d=function(e,t,n,a,r,s){return this.throwIfDisposed(),Ws(this,e,t,n,a,r,s)};re().prototype.cos=function(){return this.throwIfDisposed(),Tf(this)};re().prototype.cosh=function(){return this.throwIfDisposed(),PA(this)};re().prototype.cumsum=function(e,t,n){return this.throwIfDisposed(),LA(this,e,t,n)};re().prototype.depthToSpace=function(e,t){return this.throwIfDisposed(),r8(this,e,t)};re().prototype.depthwiseConv2d=function(e,t,n,a,r,s){return this.throwIfDisposed(),Nh(this,e,t,n,a,r,s)};re().prototype.dilation2d=function(e,t,n,a,r){return this.throwIfDisposed(),s8(this,e,t,n,a,r)};re().prototype.divNoNan=function(e){return this.throwIfDisposed(),i8(this,e)};re().prototype.div=function(e){return this.throwIfDisposed(),Me(this,e)};re().prototype.dot=function(e){return this.throwIfDisposed(),pq(this,e)};re().prototype.elu=function(){return this.throwIfDisposed(),Th(this)};re().prototype.equal=function(e){return this.throwIfDisposed(),Xi(this,e)};re().prototype.erf=function(){return this.throwIfDisposed(),o8(this)};re().prototype.exp=function(){return this.throwIfDisposed(),qa(this)};re().prototype.expandDims=function(e){return this.throwIfDisposed(),Ea(this,e)};re().prototype.expm1=function(){return this.throwIfDisposed(),l8(this)};re().prototype.fft=function(){return this.throwIfDisposed(),s2(this)};re().prototype.flatten=function(){return this.throwIfDisposed(),Y(this,[this.size])};re().prototype.floor=function(){return this.throwIfDisposed(),Ch(this)};re().prototype.floorDiv=function(e){return this.throwIfDisposed(),$A(this,e)};re().prototype.gather=function(e,t){return this.throwIfDisposed(),Mh(this,e,t)};re().prototype.greaterEqual=function(e){return this.throwIfDisposed(),Yi(this,e)};re().prototype.greater=function(e){return this.throwIfDisposed(),Ca(this,e)};re().prototype.ifft=function(){return this.throwIfDisposed(),zf(this)};re().prototype.irfft=function(){return this.throwIfDisposed(),k8(this)};re().prototype.isFinite=function(){return this.throwIfDisposed(),Eq(this)};re().prototype.isInf=function(){return this.throwIfDisposed(),Mq(this)};re().prototype.isNaN=function(){return this.throwIfDisposed(),d8(this)};re().prototype.leakyRelu=function(e){return this.throwIfDisposed(),Ef(this,e)};re().prototype.lessEqual=function(e){return this.throwIfDisposed(),Ji(this,e)};re().prototype.less=function(e){return this.throwIfDisposed(),BA(this,e)};re().prototype.localResponseNormalization=function(e,t,n,a){return this.throwIfDisposed(),h8(this,e,t,n,a)};re().prototype.logSigmoid=function(){return this.throwIfDisposed(),Uq(this)};re().prototype.logSoftmax=function(e){return this.throwIfDisposed(),UA(this,e)};re().prototype.logSumExp=function(e,t){return this.throwIfDisposed(),m8(this,e,t)};re().prototype.log=function(){return this.throwIfDisposed(),Ma(this)};re().prototype.log1p=function(){return this.throwIfDisposed(),VA(this)};re().prototype.logicalAnd=function(e){return this.throwIfDisposed(),ir(this,e)};re().prototype.logicalNot=function(){return this.throwIfDisposed(),Cf(this)};re().prototype.logicalOr=function(e){return this.throwIfDisposed(),GA(this,e)};re().prototype.logicalXor=function(e){return this.throwIfDisposed(),tK(this,e)};re().prototype.matMul=function(e,t,n){return this.throwIfDisposed(),it(this,e,t,n)};re().prototype.maxPool=function(e,t,n,a){return this.throwIfDisposed(),Mf(this,e,t,n,a)};re().prototype.max=function(e,t){return this.throwIfDisposed(),sr(this,e,t)};re().prototype.maximum=function(e){return this.throwIfDisposed(),is(this,e)};re().prototype.mean=function(e,t){return this.throwIfDisposed(),Xt(this,e,t)};re().prototype.min=function(e,t){return this.throwIfDisposed(),$f(this,e,t)};re().prototype.minimum=function(e){return this.throwIfDisposed(),$h(this,e)};re().prototype.mirrorPad=function(e,t){return this.throwIfDisposed(),y8(this,e,t)};re().prototype.mod=function(e){return this.throwIfDisposed(),A8(this,e)};re().prototype.mul=function(e){return this.throwIfDisposed(),K(this,e)};re().prototype.neg=function(){return this.throwIfDisposed(),Kt(this)};re().prototype.norm=function(e,t,n){return this.throwIfDisposed(),d2(this,e,t,n)};re().prototype.notEqual=function(e){return this.throwIfDisposed(),Yl(this,e)};re().prototype.oneHot=function(e,t=1,n=0){return this.throwIfDisposed(),kh(this,e,t,n)};re().prototype.onesLike=function(){return this.throwIfDisposed(),$a(this)};re().prototype.pad=function(e,t){return this.throwIfDisposed(),Bs(this,e,t)};re().prototype.pool=function(e,t,n,a,r){return this.throwIfDisposed(),CK(this,e,t,n,a,r)};re().prototype.pow=function(e){return this.throwIfDisposed(),Vs(this,e)};re().prototype.prelu=function(e){return this.throwIfDisposed(),Ff(this,e)};re().prototype.prod=function(e,t){return this.throwIfDisposed(),KA(this,e,t)};re().prototype.reciprocal=function(){return this.throwIfDisposed(),x8(this)};re().prototype.relu=function(){return this.throwIfDisposed(),ls(this)};re().prototype.relu6=function(){return this.throwIfDisposed(),YA(this)};re().prototype.reshapeAs=function(e){return this.throwIfDisposed(),Y(this,e.shape)};re().prototype.reshape=function(e){return this.throwIfDisposed(),Y(this,e)};re().prototype.resizeBilinear=function(e,t,n){return this.throwIfDisposed(),P8(this,e,t,n)};re().prototype.resizeNearestNeighbor=function(e,t,n){return this.throwIfDisposed(),L8(this,e,t,n)};re().prototype.reverse=function(e){return this.throwIfDisposed(),Ra(this,e)};re().prototype.rfft=function(){return this.throwIfDisposed(),i2(this)};re().prototype.round=function(){return this.throwIfDisposed(),JA(this)};re().prototype.rsqrt=function(){return this.throwIfDisposed(),QA(this)};re().prototype.selu=function(){return this.throwIfDisposed(),e2(this)};re().prototype.separableConv2d=function(e,t,n,a,r,s){return this.throwIfDisposed(),b8(this,e,t,n,a,r,s)};re().prototype.sigmoid=function(){return this.throwIfDisposed(),$r(this)};re().prototype.sign=function(){return this.throwIfDisposed(),v8(this)};re().prototype.sin=function(){return this.throwIfDisposed(),t2(this)};re().prototype.sinh=function(){return this.throwIfDisposed(),n2(this)};re().prototype.slice=function(e,t){return this.throwIfDisposed(),nt(this,e,t)};re().prototype.softmax=function(e){return this.throwIfDisposed(),_f(this,e)};re().prototype.softplus=function(){return this.throwIfDisposed(),Zl(this)};re().prototype.spaceToBatchND=function(e,t){return this.throwIfDisposed(),Rf(this,e,t)};re().prototype.split=function(e,t){return this.throwIfDisposed(),da(this,e,t)};re().prototype.sqrt=function(){return this.throwIfDisposed(),Mn(this)};re().prototype.square=function(){return this.throwIfDisposed(),vt(this)};re().prototype.squaredDifference=function(e){return this.throwIfDisposed(),o2(this,e)};re().prototype.squeeze=function(e){return this.throwIfDisposed(),Jl(this,e)};re().prototype.stack=function(e,t){this.throwIfDisposed();let n=e instanceof Tt?[this,e]:[this,...e];return Fa(n,t)};re().prototype.step=function(e){return this.throwIfDisposed(),Oh(this,e)};re().prototype.stridedSlice=function(e,t,n,a,r,s,i,o){return this.throwIfDisposed(),I8(this,e,t,n,a,r,s,i,o)};re().prototype.sub=function(e){return this.throwIfDisposed(),Ne(this,e)};re().prototype.sum=function(e,t){return this.throwIfDisposed(),Ce(this,e,t)};re().prototype.tan=function(){return this.throwIfDisposed(),S8(this)};re().prototype.tanh=function(){return this.throwIfDisposed(),Kl(this)};re().prototype.tile=function(e){return this.throwIfDisposed(),Zi(this,e)};re().prototype.toBool=function(){return this.throwIfDisposed(),we(this,"bool")};re().prototype.toFloat=function(){return this.throwIfDisposed(),we(this,"float32")};re().prototype.toInt=function(){return this.throwIfDisposed(),we(this,"int32")};re().prototype.topk=function(e,t){return this.throwIfDisposed(),N8(this,e,t)};re().prototype.transpose=function(e){return this.throwIfDisposed(),ct(this,e)};re().prototype.unique=function(e){return this.throwIfDisposed(),u2(this,e)};re().prototype.unsortedSegmentSum=function(e,t){return this.throwIfDisposed(),T8(this,e,t)};re().prototype.unstack=function(e){return this.throwIfDisposed(),or(this,e)};re().prototype.where=function(e,t){return this.throwIfDisposed(),Pn(e,this,t)};re().prototype.zerosLike=function(){return this.throwIfDisposed(),at(this)};var G8={kernelName:xd,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>K(e,Oh(we(n,"float32"),-1))}}},ZY={kernelName:bd,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=vt(we(n,"float32")),r=Mn(Ne(Re(1),a));return Kt(Me(e,r))}}}},YY={kernelName:vd,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=Mn(Ne(vt(we(n,"float32")),1));return Me(e,a)}}}},JY={kernelName:Os,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=Rt(n.shape,a.shape);return{a:()=>{let s=e,i=ln(n.shape,r);return i.length>0&&(s=Ce(s,i)),Y(s,n.shape)},b:()=>{let s=e,i=ln(a.shape,r);return i.length>0&&(s=Ce(s,i)),Y(s,a.shape)}}}},QY={kernelName:Zo,saveAllInputs:!0,gradFunc:(e,t)=>{let n={};return t.forEach((a,r)=>{n[r]=()=>e.clone()}),n}},eJ={kernelName:Yo,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>at(n)}}},tJ={kernelName:qc,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>at(n)}}},nJ={kernelName:Id,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Me(e,Mn(Ne(Re(1),vt(we(n,"float32")))))}}},aJ={kernelName:Sd,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=Mn(pe(Re(1),vt(we(n,"float32"))));return Me(e,a)}}}},rJ={kernelName:Ed,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=Rt(n.shape,a.shape);return{a:()=>{let s=pe(vt(n),vt(a)),i=K(e,Me(a,s)),o=ln(n.shape,r);return o.length>0&&(i=Ce(i,o)),Y(i,n.shape)},b:()=>{let s=pe(vt(n),vt(a)),i=Kt(K(e,Me(n,s))),o=ln(a.shape,r);return o.length>0&&(i=Ce(i,o)),Y(i,a.shape)}}}},sJ={kernelName:Nd,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Me(e,pe(vt(we(n,"float32")),1))}}},iJ={kernelName:Td,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Me(e,Ne(Re(1),vt(we(n,"float32"))))}}};function oJ(e,t,n,a,r,s){let i=F(e,"dy","avgPool3dGrad"),o=F(t,"input","avgPool3dGrad"),l=i,u=o,d=!1;o.rank===4&&(d=!0,l=Y(i,[1,i.shape[0],i.shape[1],i.shape[2],i.shape[3]]),u=Y(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]])),P(l.rank===5,()=>`Error in avgPool3dGrad: dy must be rank 5 but got rank ${l.rank}.`),P(u.rank===5,()=>`Error in avgPool3dGrad: input must be rank 5 but got rank ${u.rank}.`),s!=null&&P(mn(r),()=>`Error in avgPool3dGrad: pad must be an integer when using, dimRoundingMode ${s} but got pad ${r}.`);let h={dy:l,input:u},p={filterSize:n,strides:a,pad:r,dimRoundingMode:s},c=j.runKernel(w1,h,p);return d?Y(c,[c.shape[1],c.shape[2],c.shape[3],c.shape[4]]):c}var lJ=B({avgPool3dGrad_:oJ}),uJ={kernelName:Kc,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{filterSize:r,strides:s,pad:i,dimRoundingMode:o}=n;return{x:()=>lJ(e,a,r,s,i,o)}}};function dJ(e,t,n,a,r){let s=F(e,"dy","avgPoolGrad"),i=F(t,"input","avgPoolGrad");P(i.rank===s.rank,()=>`Rank of input (${i.rank}) does not match rank of dy (${s.rank})`);let o=i,l=s,u=!1;i.rank===3&&(u=!0,o=Y(i,[1,i.shape[0],i.shape[1],i.shape[2]]),l=Y(s,[1,s.shape[0],s.shape[1],s.shape[2]])),P(l.rank===4,()=>`Error in avgPoolGrad: dy must be rank 4 but got rank ${l.rank}.`),P(o.rank===4,()=>`Error in avgPoolGrad: input must be rank 4 but got rank ${o.rank}.`);let d={dy:l,input:o},h={filterSize:n,strides:a,pad:r},p=j.runKernel(v1,d,h);return u?Y(p,[p.shape[1],p.shape[2],p.shape[3]]):p}var hJ=B({avgPoolGrad_:dJ}),pJ={kernelName:Jo,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{filterSize:r,strides:s,pad:i}=n;return{x:()=>hJ(e,a,r,s,i)}}},cJ={kernelName:Qo,inputsToSave:["a","b"],gradFunc:(e,t,n)=>{let[a,r]=t,{transposeA:s,transposeB:i}=n;return!s&&!i?{a:()=>it(e,r,!1,!0),b:()=>it(a,e,!0,!1)}:!s&&i?{a:()=>it(e,r,!1,!1),b:()=>it(e,a,!0,!1)}:s&&!i?{a:()=>it(r,e,!1,!0),b:()=>it(a,e,!1,!1)}:{a:()=>it(r,e,!0,!0),b:()=>it(e,a,!0,!0)}}},fJ={kernelName:Xc,gradFunc:(e,t,n)=>{let{blockShape:a,crops:r}=n;return{x:()=>Rf(e,a,r)}}},mJ={kernelName:tj,gradFunc:(e,t,n)=>{let a=n,r=a.inputShape,s=a.shape,i=Array.from(s);for(let l=r.length-1;l>=0;l--)if(r[l]===s[l])i[l]=1;else if(r[l]!==1)throw new Error(`broadcastTo(): [${r}] cannot be broadcast to [${s}].`);let o=[];for(let l=0;l1&&o.push(l);return{x:()=>Ce(e,o,!0)}}},gJ={kernelName:el,gradFunc:e=>({x:()=>e.clone()})},yJ={kernelName:Ni,gradFunc:e=>({x:()=>at(e)})},AJ={kernelName:Ti,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{clipValueMin:r,clipValueMax:s}=n;return{x:()=>Pn(ir(Yi(a,r),Ji(a,s)),e,at(e))}}},xJ={kernelName:Zc,inputsToSave:["x"],gradFunc:G8.gradFunc},bJ={kernelName:Cd,saveAllInputs:!0,gradFunc:(e,t,n)=>{let a=t.map(o=>o.shape),{axis:r}=n,s=Ha(r,t[0].shape)[0],i=a.map(o=>o[s]);return da(e,i,s).map(o=>()=>o)}},vJ={kernelName:tl,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[a,r]=t,{dilations:s,strides:i,pad:o,dataFormat:l}=n;return P(Ls(s),()=>`Error in gradient of conv2D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${s}'`),{x:()=>_A(a.shape,e,r,i,o,l),filter:()=>h2(a,e,r.shape,i,o,l)}}},wJ={kernelName:nl,inputsToSave:["dy","filter"],gradFunc:(e,t,n)=>{let[a,r]=t,{strides:s,pad:i,dataFormat:o,dimRoundingMode:l}=n;return{dy:()=>Ws(e,r,s,i,o,1,l),filter:()=>h2(e,a,r.shape,s,i,o,l)}}};function kJ(e,t,n,a,r){let s=e;e.rank===4&&(s=Y(e,[1,e.shape[0],e.shape[1],e.shape[2],e.shape[3]]));let i=t;i.rank===4&&(i=Y(t,[1,t.shape[0],t.shape[1],t.shape[2],t.shape[3]])),P(s.rank===5,()=>`Error in conv3dDerFilter: input must be rank 5, but got shape ${s.shape}.`),P(i.rank===5,()=>`Error in conv3dDerFilter: dy must be rank 5, but got shape ${i.shape}.`),P(n.length===5,()=>`Error in conv3dDerFilter: filterShape must be length 5, but got ${n}.`),P(s.shape[4]===n[3],()=>`Error in conv3dDerFilter: depth of input ${s.shape[4]}) must match input depth in filter (${n[3]}.`),P(i.shape[4]===n[4],()=>`Error in conv3dDerFilter: depth of dy (${i.shape[4]}) must match output depth for filter (${n[4]}).`);let o={x:s,dy:i},l={strides:a,pad:r,filterShape:n};return j.runKernel(N1,o,l)}var IJ=B({conv3DBackpropFilter_:kJ}),SJ={kernelName:Yc,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:a,strides:r,pad:s}=n;P(Ls(a),()=>`Error in gradient of conv3D: dilation rates greater than 1 are not yet supported in gradients. Got dilations '${a}'`);let[i,o]=t;return{x:()=>a8(i.shape,e,o,r,s),filter:()=>IJ(i,e,o.shape,r,s)}}},NJ={kernelName:al,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>K(Kt(t2(we(n,"float32"))),e)}}},TJ={kernelName:Md,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>K(n2(we(n,"float32")),e)}}},EJ={kernelName:rl,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{axis:r,exclusive:s,reverse:i}=n;return{x:()=>{let o=f8([r],a.rank),l=LA(e,r,s,!i);return o!=null&&(l=ct(l,o)),l}}}},CJ={kernelName:sl,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let{dilations:a,strides:r,pad:s,dimRoundingMode:i}=n,o=a==null?[1,1]:a;P(Ls(o),()=>`Error in gradient of depthwiseConv2dNative: dilation rates greater than 1 are not yet supported. Got dilations '${o}'`);let[l,u]=t;return P(l.rank===4,()=>`Error in gradient of depthwiseConv2dNative: input must be rank 4, but got rank ${l.rank}.`),P(u.rank===4,()=>`Error in gradient of depthwiseConv2dNative: filter must be rank 4, but got rank ${u.rank}.`),P(l.shape[3]===u.shape[2],()=>`Error in gradient of depthwiseConv2d: number of input channels (${l.shape[3]}) must match the inChannels dimension in filter ${u.shape[2]}.`),P(Mr(r,o),()=>`Error in gradient of depthwiseConv2d: Either strides or dilations must be 1. Got strides ${r} and dilations '${o}'.`),i!=null&&P(mn(s),()=>`Error in depthwiseConv2d: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`),{x:()=>F8(l.shape,e,u,r,s,a,i),filter:()=>R8(l,e,u.shape,r,s,a,i)}}},MJ={kernelName:Jc,inputsToSave:["x","filter"],gradFunc:(e,t,n)=>{let[a,r]=t,s={x:a,filter:r,dy:e},i={x:a,filter:r,dy:e};return{x:()=>j.runKernel(R1,s,n),filter:()=>j.runKernel(F1,i,n)}}},$J={kernelName:Fd,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t,a={dy:e,y:n};return{x:()=>j.runKernel(D1,a)}}},RJ={kernelName:Od,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,a=K(qa(Kt(vt(n))),2/Math.sqrt(Math.PI));return{x:()=>K(e,a)}}},FJ={kernelName:Ei,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>K(e,n)}}},OJ={kernelName:Dd,inputsToSave:["input"],gradFunc:(e,t)=>{let[n]=t;return{input:()=>Y(e,n.shape)}}},DJ={kernelName:ll,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>K(e,qa(n))}}},_J={kernelName:Ci,gradFunc:e=>({x:()=>at(e)})},zJ={kernelName:ul,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=Rt(n.shape,a.shape);return{a:()=>{let s=Me(e,we(a,"float32")),i=ln(n.shape,r);return i.length>0?Y(Ce(s,i),n.shape):s},b:()=>{let s=K(e,we(n,"float32")),i=ln(a.shape,r);i.length>0&&(s=Y(Ce(s,i),a.shape));let o=vt(a);return Kt(Me(s,we(o,"float32")))}}}},PJ={kernelName:dl,inputsToSave:["x","mean","variance","scale"],gradFunc:(e,t,n)=>{let{varianceEpsilon:a}=n,[r,s,i,o]=t,l=o==null?Re(1):o,u=ln(s.shape,r.shape),d=[];if(s.rank===1){for(let f=0;fs.rank===1?Y(K(K(e,Zi(Y(c,[1,1,1,s.shape[0]]),d)),l),r.shape):Y(K(K(e,c),l),r.shape),mean:()=>{let f=K(K(c,Re(-1)),p);return s.rank===1&&(f=Ce(f,u)),Y(f,s.shape)},variance:()=>{let f=K(K(m,h),p);return s.rank===1&&(f=Ce(f,u)),Y(f,s.shape)},scale:()=>{let f=K(h,c),g=K(e,f);return s.rank===1&&(g=Ce(g,u)),Y(g,s.shape)},offset:()=>{let f=e;return s.rank===1&&(f=Ce(f,u)),Y(f,s.shape)}}}},LJ={kernelName:zd,inputsToSave:["x","indices"],gradFunc:(e,t,n)=>{let[a,r]=t,{axis:s}=n,i=Ha(s,a.shape)[0];return{x:()=>{let o=a.shape,l=r.size,u=o.slice(0,i),d=u.length,h=o.slice(s,o.length).slice(1),p=h.length,c=q8(0,d),m=q8(d+1,d+1+p),f=K8([u,[l],h]),g=Y(e,f),y=Y(r,[l]),A=K8([[d],c,m]),x=ct(g,A),v=T8(x,y,a.shape[i]),b=HA(A);return v=ct(v,b),v},indices:()=>r}}};function q8(e,t){let n=[];for(let a=e;a{let[n,a]=t;return{a:()=>at(n),b:()=>at(a)}}},BJ={kernelName:pl,gradFunc:e=>({x:()=>we(e,"float32")})},VJ={kernelName:Ld,gradFunc:e=>({x:()=>at(e)})},UJ={kernelName:Wd,gradFunc:e=>({x:()=>at(e)})},jJ={kernelName:Bd,gradFunc:e=>({x:()=>at(e)})},HJ={kernelName:cl,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{alpha:r}=n,s=Ca(a,0);return{x:()=>Pn(s,e,K(e,r))}}},GJ={kernelName:Vd,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Me(e,pe(n,1))}}},qJ={kernelName:$i,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Me(e,we(n,"float32"))}}},KJ={kernelName:nj,inputsToSave:[],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a]=t,{axis:r}=n;return{logits:()=>{let s=!0,i=qa(a);return Ne(e,K(Ce(e,r,s),i))}}}};function XJ(e,t,n,a=5,r=1,s=1,i=.5){let o={x:e,y:t,dy:n},l={depthRadius:a,bias:r,alpha:s,beta:i};return j.runKernel(W1,o,l)}var ZJ=B({localResponseNormalizationBackprop_:XJ}),YJ={kernelName:nf,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a,r]=t,{depthRadius:s,bias:i,alpha:o,beta:l}=n;return{x:()=>ZJ(a,r,e,s,i,o,l)}}};function X8(e,t,n,a){return t.rankK(e,we(Xi(n,t),e.dtype))}}var Z8={kernelName:gl,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let a=n,{reductionIndices:r}=a,s=t[0],i=t[1],o=Ha(r,s.shape),l=X8(e,i,s,o);return{x:()=>l.x()}}},JJ={kernelName:Ri,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t;return{a:()=>K(e,we(Yi(n,a),"float32")),b:()=>K(e,we(BA(n,a),"float32"))}}};function QJ(e,t,n,a,r,s,i){let o=F(e,"dy","maxPool3dGrad"),l=F(t,"input","maxPool3dGrad"),u=F(n,"output","maxPool3dGrad"),d=o,h=l,p=u,c=!1;l.rank===4&&(c=!0,d=Y(o,[1,o.shape[0],o.shape[1],o.shape[2],o.shape[3]]),h=Y(l,[1,l.shape[0],l.shape[1],l.shape[2],l.shape[3]]),p=Y(u,[1,u.shape[0],u.shape[1],u.shape[2],u.shape[3]])),P(d.rank===5,()=>`Error in maxPool3dGrad: dy must be rank 5 but got rank ${d.rank}.`),P(h.rank===5,()=>`Error in maxPool3dGrad: input must be rank 5 but got rank ${h.rank}.`),P(p.rank===5,()=>`Error in maxPool3dGrad: output must be rank 5 but got rank ${p.rank}.`),i!=null&&P(mn(s),()=>`Error in maxPool3dGrad: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);let m={dy:d,input:h,output:p},f={filterSize:a,strides:r,pad:s,dimRoundingMode:i},g=j.runKernel(V1,m,f);return c?Y(g,[g.shape[1],g.shape[2],g.shape[3],g.shape[4]]):g}var eQ=B({maxPool3dGrad_:QJ}),tQ={kernelName:af,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a,r]=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=n;return{x:()=>eQ(e,a,r,s,i,o,l)}}};function nQ(e,t,n,a,r,s,i){let o=F(e,"dy","maxPoolGrad"),l=F(t,"input","maxPoolGrad"),u=F(n,"output","maxPoolGrad");P(l.rank===o.rank,()=>`Rank of input (${l.rank}) does not match rank of dy (${o.rank})`),P(o.rank===4,()=>`Error in maxPoolGrad: dy must be rank 4 but got rank ${o.rank}.`),P(l.rank===4,()=>`Error in maxPoolGrad: input must be rank 4 but got rank ${l.rank}.`),i!=null&&P(mn(s),()=>`Error in maxPoolGrad: pad must be an integer when using, dimRoundingMode ${i} but got pad ${s}.`);let d={dy:o,input:l,output:u},h={filterSize:a,strides:r,pad:s,dimRoundingMode:i};return j.runKernel(B1,d,h)}var aQ=B({maxPoolGrad_:nQ}),rQ={kernelName:yl,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a,r]=t,{filterSize:s,strides:i,pad:o}=n;return{x:()=>aQ(e,a,r,s,i,o)}}},sQ={kernelName:Al,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{axis:r}=n,s=Ha(r,a.shape),i=c8(a.shape,s)[1],o=on(i);return{x:()=>{let l=a.shape.slice();s.forEach(d=>{l[d]=1});let u=Y(e,l);return Me(K(u,os(a.shape,"float32")),o)}}}},iQ={kernelName:xl,inputsToSave:["x"],outputsToSave:[!0],gradFunc:(e,t,n)=>{let a=n,{axis:r}=a,[s,i]=t,o=Ha(r,s.shape),l=X8(e,i,s,o);return{x:()=>l.x()}}},oQ={kernelName:Fi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t;return{a:()=>K(e,we(Ji(n,a),"float32")),b:()=>K(e,we(Ca(n,a),"float32"))}}},lQ={kernelName:bl,inputsToSave:["x"],gradFunc:(e,t,n)=>{let a=t[0],{paddings:r}=n,s=r.map(i=>i[0]);return{x:()=>nt(e,s,a.shape)}}},uQ={kernelName:jd,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=Rt(n.shape,a.shape);return{a:()=>{let s=ln(n.shape,r);return s.length>0?Y(Ce(e,s),n.shape):e},b:()=>{let s=K(e,Kt(Ch(Me(n,a)))),i=ln(a.shape,r);return i.length>0?Y(Ce(s,i),a.shape):s}}}},dQ={kernelName:Oi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=Rt(n.shape,a.shape);return{a:()=>{let s=K(e,we(a,"float32")),i=ln(n.shape,r);return i.length>0?Y(Ce(s,i),n.shape):s},b:()=>{let s=K(e,we(n,"float32")),i=ln(a.shape,r);return i.length>0?Y(Ce(s,i),a.shape):s}}}},hQ={kernelName:Hd,gradFunc:e=>({x:()=>Kt(e)})},pQ={kernelName:wl,inputsToSave:["indices"],gradFunc:(e,t)=>{let n=t[0];return{indices:()=>un(n.shape,"float32")}}},cQ={kernelName:Xd,gradFunc:e=>({x:()=>at(e)})},fQ={kernelName:Zd,saveAllInputs:!0,gradFunc:(e,t,n)=>{let{axis:a}=n;return or(e,a).map(r=>()=>r)}},Y8={kernelName:kl,inputsToSave:["x"],gradFunc:(e,t,n)=>{let a=t[0],{paddings:r}=n,s=r.map(i=>i[0]);return{x:()=>nt(e,s,a.shape)}}},mQ={kernelName:Il,inputsToSave:["a","b"],outputsToSave:[!0],gradFunc:(e,t)=>{let[n,a,r]=t,s=n,i=a,o=Rt(s.shape,i.shape);return{a:()=>{let l=we(i,"float32"),u=K(e,K(l,Vs(s,Ne(l,Re(1))))),d=ln(s.shape,o);return d.length>0&&(u=Ce(u,d)),Y(u,s.shape)},b:()=>{let l=Ca(s,0),u=Pn(l,Ma(s),at(s)),d=K(e,K(r,u)),h=ln(i.shape,o);return h.length>0&&(d=Ce(d,h)),Y(d,i.shape)}}}},gQ={kernelName:Sl,inputsToSave:["x","alpha"],gradFunc:(e,t)=>{let[n,a]=t,r=Ca(n,0);return{x:()=>Pn(r,e,K(e,a)),alpha:()=>{let s=Pn(r,at(e),K(e,n)),i=ln(a.shape,e.shape);return i.length>0&&(s=Ce(s,i)),Y(s,a.shape)}}}},yQ={kernelName:il,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=Rt(n.shape,a.shape);return{a:()=>{let s=Me(e,we(a,"float32")),i=ln(n.shape,r);return i.length>0?Y(Ce(s,i),n.shape):s},b:()=>{let s=K(e,we(n,"float32")),i=ln(a.shape,r);i.length>0&&(s=Y(Ce(s,i),a.shape));let o=vt(a);return Kt(Me(s,we(o,"float32")))}}}},AQ={kernelName:Jd,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Me(e,Kt(vt(n)))}}},xQ={kernelName:El,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t,a=K(Ji(n,6),Oh(n));return{x:()=>K(e,we(a,"float32"))}}},bQ={kernelName:Nl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>K(e,we(Oh(n),"float32"))}}},vQ={kernelName:Qd,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Y(e,n.shape)}}},wQ={kernelName:Tl,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[a]=t,r={dy:e,images:a};return{images:()=>j.runKernel(q1,r,n)}}},kQ={kernelName:sf,inputsToSave:["images"],gradFunc:(e,t,n)=>{let[a]=t,r={dy:e,images:a};return{images:()=>j.runKernel(G1,r,n)}}},IQ={kernelName:Cl,gradFunc:(e,t,n)=>{let{dims:a}=n,r=Ha(a,e.shape);return{x:()=>Ra(e,r)}}},SQ={kernelName:Ml,gradFunc:e=>({x:()=>at(e)})},NQ={kernelName:Di,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Kt(Me(e,K(Vs(n,1.5),2)))}}},TQ={kernelName:th,inputsToSave:["condition"],gradFunc:(e,t)=>{let[n]=t;return{condition:()=>we(at(n),"float32"),t:()=>K(e,we(n,e.dtype)),e:()=>K(e,we(Cf(n),e.dtype))}}},EQ={kernelName:nh,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>{let a=Ca(n,Re(0)),r=Re(B8),s=Re(V8),i=K(e,s),o=K(K(e,r),qa(we(n,"float32")));return Pn(a,i,o)}}}},CQ={kernelName:Rl,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>K(e,K(n,Ne(Re(1),n)))}}},MQ={kernelName:sh,gradFunc:e=>({x:()=>at(e)})},$Q={kernelName:$l,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>K(Tf(we(n,"float32")),e)}}},RQ={kernelName:rh,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>K(PA(we(n,"float32")),e)}}},FQ={kernelName:ah,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{begin:r,size:s}=n,i=a.shape,[o,l]=L4(a,r,s),u=[];for(let d=0;dBs(e,u)}}},OQ={kernelName:Dl,outputsToSave:[!0],gradFunc:(e,t,n)=>{let[a]=t,{dim:r}=n,s=!0,i=K(e,a);return{logits:()=>Ne(i,K(Ce(i,[r],s),a))}}},DQ={kernelName:ih,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>K(e,$r(n))}}},J8={kernelName:of,gradFunc:(e,t,n)=>{let{blockShape:a,paddings:r}=n;return{x:()=>Nf(e,a,r)}}},Q8={kernelName:oh,gradFunc:(e,t,n)=>{let{axis:a}=n;return{x:()=>en(e,a)}}},_Q={kernelName:Fl,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Me(e,K(Mn(we(n,"float32")),2))}}},zQ={kernelName:lf,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>K(e,K(we(n,"float32"),2))}}},PQ={kernelName:_i,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=Re(2);return{a:()=>K(e,K(r,Ne(n,a))),b:()=>K(e,K(r,Ne(a,n)))}}},LQ={kernelName:Li,gradFunc:e=>({x:()=>at(e)})},WQ={kernelName:zi,inputsToSave:["a","b"],gradFunc:(e,t)=>{let[n,a]=t,r=Rt(n.shape,a.shape);return{a:()=>{let s=e,i=ln(n.shape,r);return i.length>0&&(s=Ce(s,i)),Y(s,n.shape)},b:()=>{let s=e,i=ln(a.shape,r);return i.length>0&&(s=Ce(s,i)),Y(Kt(s),a.shape)}}}},BQ={kernelName:Ol,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,r=a.shape.slice(),{axis:s}=n;Ha(s,a.shape).forEach(l=>{r[l]=1});let i=Y(e,r),o=K(i,os(a.shape,"float32"));return{x:()=>o}}},VQ={kernelName:_l,inputsToSave:["x"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>Me(e,vt(Tf(n)))}}},UQ={kernelName:zl,outputsToSave:[!0],gradFunc:(e,t)=>{let[n]=t;return{x:()=>K(Ne(Re(1),vt(n)),e)}}},jQ={kernelName:Pi,inputsToSave:["x"],gradFunc:(e,t,n)=>{let[a]=t,{reps:r}=n;return{x:()=>{let s=at(a);if(a.rank===1)for(let i=0;i{let a=n,{perm:r}=a,s=HA(r);return{x:()=>ct(e,s)}}},GQ={kernelName:hh,gradFunc:(e,t,n)=>{let a=n,{axis:r}=a;return{value:()=>Fa(e,r)}}},qQ={kernelName:uf,inputsToSave:["segmentIds"],gradFunc:(e,t)=>{let[n]=t;return{x:()=>KQ(e,n)}}};function KQ(e,t){let n=is(t,at(t)),a=Mh(e,n),r=Yi(t,Re(0,"int32")),s=a.rank-r.rank;for(let o=0;o({x:()=>at(e)})},ZQ=[G8,ZY,YY,JY,QY,eJ,tJ,nJ,aJ,rJ,sJ,iJ,uJ,pJ,cJ,fJ,mJ,gJ,yJ,AJ,xJ,bJ,wJ,vJ,SJ,NJ,TJ,EJ,CJ,MJ,yQ,$J,RJ,FJ,OJ,DJ,zJ,_J,PJ,LJ,WJ,BJ,VJ,UJ,jJ,HJ,GJ,qJ,KJ,YJ,Z8,Z8,JJ,tQ,rQ,sQ,iQ,oQ,lQ,uQ,dQ,hQ,pQ,cQ,fQ,Y8,Y8,mQ,gQ,AQ,xQ,bQ,vQ,wQ,kQ,IQ,SQ,NQ,TQ,EQ,CQ,MQ,$Q,RQ,FQ,OQ,DQ,J8,J8,Q8,Q8,_Q,PQ,zQ,LQ,WQ,BQ,VQ,UQ,jQ,HQ,GQ,qQ,XQ];for(let e of ZQ)aj(e);var eI={};$e(eI,{maxNorm:()=>eee,minMaxNorm:()=>aee,nonNeg:()=>nee,unitNorm:()=>tee});var k2;function dn(){return k2==null&&(k2=UH().epsilon()),k2}function lr(){return"channelsLast"}var ds=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,ds.prototype)}},ur=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,ur.prototype)}},G=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,G.prototype)}},He=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,He.prototype)}},tI=class extends Error{constructor(e){super(e);Object.setPrototypeOf(this,tI.prototype)}};function ao(e,t){if(Array.isArray(e)){let n=[];for(let a=0;an.toUpperCase())}var Ka={};function I2(e){if(e==null)return null;let t={};return t.className=e.getClassName(),t.config=e.getConfig(),t}function S2(e){if(!(e==null||typeof e!="object"))if(Array.isArray(e))e.forEach(t=>S2(t));else{let t=Object.keys(e);for(let n of t){let a=e[n];a!=null&&typeof a=="object"&&(!Array.isArray(a)&&a.type==="ndarray"&&typeof a.value=="number"?e[n]=a.value:S2(a))}}}function Dh(e,t={},n={},a="object",r=!1){if(typeof e=="string"){let s=e,i;if(s in n)i=n[s];else if(s in Ka)i=Ka[s];else if(i=t[s],i==null)throw new G(`Unknown ${a}: ${e}. This may be due to one of the following reasons: 1. The ${a} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code. 2. The custom ${a} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);return i}else{let s=e;if(s.className==null||s.config==null)throw new G(`${a}: Improper config format: ${JSON.stringify(s)}. 'className' and 'config' must set.`);let i=s.className,o,l;if(i in n?[o,l]=n[i]:i in Ka?[o,l]=Ka.className:i in t&&([o,l]=t[i]),o==null)throw new G(`Unknown ${a}: ${i}. This may be due to one of the following reasons: 1. The ${a} is defined in Python, in which case it needs to be ported to TensorFlow.js or your JavaScript code. 2. The custom ${a} is defined in JavaScript, but is not registered properly with tf.serialization.registerClass().`);if(l!=null){let u={};for(let c of Object.keys(Ka))u[c]=Ka[c];for(let c of Object.keys(n))u[c]=n[c];let d=s.config;d.customObjects=u;let h={...Ka};for(let c of Object.keys(n))Ka[c]=n[c];S2(s.config);let p=l(o,s.config,n,r);return Ka={...h},p}else{let u={...Ka};for(let h of Object.keys(n))Ka[h]=n[h];let d=new o(s.config);return Ka={...u},d}}}function YQ(e,t){return et?1:0}function jf(e,t){return-1*YQ(e,t)}function Hs(e){if(e==null)return e;let t=[];for(let n of e)t.indexOf(n)===-1&&t.push(n);return t}function JQ(e){if(e==null)throw new G(`Invalid value in obj: ${JSON.stringify(e)}`);for(let t in e)if(e.hasOwnProperty(t))return!1;return!0}function so(e,t,n){if(n!=null&&e.indexOf(n)<0)throw new G(`${n} is not a valid ${t}. Valid values are ${e} or null/undefined.`)}function N2(e,t,n=0,a=Infinity){return Rr(n>=0),Rr(a>=n),Array.isArray(e)&&e.length>=n&&e.length<=a&&e.every(r=>typeof r===t)}function An(e,t){Array.isArray(e)?(k.assert(e.length>0,()=>`${t} is unexpectedly an empty array.`),e.forEach((n,a)=>An(n,`element ${a+1} of ${t}`))):k.assert(Number.isInteger(e)&&e>0,()=>`Expected ${t} to be a positive integer, but got ${aI(e)}.`)}function aI(e){return e===null?"null":Array.isArray(e)?"["+e.map(t=>aI(t)).join(",")+"]":typeof e=="string"?`"${e}"`:`${e}`}function QQ(e,t){let n=k.now(),a;return(...r)=>{let s=k.now();return s-nMn(Ce(K(e,e),t,!0)))}var _h=class extends ue.Serializable{getConfig(){return{}}},E2=class extends _h{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 Z(()=>{let t=T2(e,this.axis),n=ua(t,0,this.maxValue);return K(e,Me(n,pe(dn(),t)))})}getConfig(){return{maxValue:this.maxValue,axis:this.axis}}};E2.className="MaxNorm";ue.registerClass(E2);var C2=class extends _h{constructor(e){super();this.defaultAxis=0,this.axis=e.axis!=null?e.axis:this.defaultAxis}apply(e){return Z(()=>Me(e,pe(dn(),T2(e,this.axis))))}getConfig(){return{axis:this.axis}}};C2.className="UnitNorm";ue.registerClass(C2);var M2=class extends _h{apply(e){return ls(e)}};M2.className="NonNeg";ue.registerClass(M2);var $2=class extends _h{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 Z(()=>{let t=T2(e,this.axis),n=pe(K(this.rate,ua(t,this.minValue,this.maxValue)),K(1-this.rate,t));return K(e,Me(n,pe(dn(),t)))})}getConfig(){return{minValue:this.minValue,maxValue:this.maxValue,rate:this.rate,axis:this.axis}}};$2.className="MinMaxNorm";ue.registerClass($2);var sI={maxNorm:"MaxNorm",minMaxNorm:"MinMaxNorm",nonNeg:"NonNeg",unitNorm:"UnitNorm"};function hn(e){return I2(e)}function iI(e,t={}){return Dh(e,ue.SerializationMap.getMap().classNameMap,t,"constraint")}function pn(e){if(e==null)return null;if(typeof e=="string"){let t={className:e in sI?sI[e]:e,config:{}};return iI(t)}else return e instanceof _h?e:iI(e)}function eee(e){return new E2(e)}function tee(e){return new C2(e)}function nee(){return new M2}function aee(e){return new $2(e)}var oI={};$e(oI,{constant:()=>Nee,glorotNormal:()=>Fee,glorotUniform:()=>Ree,heNormal:()=>Oee,heUniform:()=>Dee,identity:()=>Mee,leCunNormal:()=>_ee,leCunUniform:()=>zee,ones:()=>See,orthogonal:()=>Pee,randomNormal:()=>Eee,randomUniform:()=>Tee,truncatedNormal:()=>Cee,varianceScaling:()=>$ee,zeros:()=>Iee});var ree=["channelsFirst","channelsLast"],see=["nearest","bilinear"],iee=["valid","same","causal"],oee=["max","avg"],lee=["sum","mul","concat","ave"],nu=new Map;function Yt(e){so(ree,"DataFormat",e)}function uee(e){so(see,"InterpolationFormat",e)}function Oa(e){so(iee,"PaddingMode",e)}function lI(e){so(oee,"PoolMode",e)}var zh=[],uI="/";function io(e,t){zh.push(e);try{let n=t();return zh.pop(),n}catch(n){throw zh.pop(),n}}function dee(){return zh.length===0?"":zh.join(uI)+uI}function dI(e){if(!pI(e))throw new Error("Not a valid tensor name: '"+e+"'");return dee()+e}function hI(e){if(!pI(e))throw new Error("Not a valid tensor name: '"+e+"'");nu.has(e)||nu.set(e,0);let t=nu.get(e);if(nu.set(e,nu.get(e)+1),t>0){let n=`${e}_${t}`;return nu.set(n,1),n}else return e}var hee=new RegExp(/^[A-Za-z0-9][-A-Za-z0-9\._\/]*$/);function pI(e){return!!e.match(hee)}function pee(e){return e===parseInt(e.toString(),10)}function Gs(e,t,n){t==null&&(t=0),n==null&&(n=e.length);let a=1;for(let r=t;rt&&(t=a)}return t}function dr(e,t){if(t{if(e.shape.length!==2)throw new G(`repeat() expects a rank-2 tensor, but received a rank-${e.shape.length} tensor.`);let n=Lh(e,1);return O2(n,[1,t,1])})}function fee(e){let t=[Gs(e.shape)];return e.reshape(t)}function mee(e){if(e.rank<=1)throw new G(`batchFlatten requires a minimum rank of 2. Got rank: ${e.rank}.`);let t=[e.shape[0],Gs(e.shape,1)];return e.reshape(t)}function oo(e,t,n){return Z(()=>{switch(e.rank){case 1:return a2(e,t,n);case 2:return w8(e,[t,0],[n,e.shape[1]]);case 3:return r2(e,[t,0,0],[n,e.shape[1],e.shape[2]]);case 4:return Df(e,[t,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3]]);case 5:return nt(e,[t,0,0,0,0],[n,e.shape[1],e.shape[2],e.shape[3],e.shape[4]]);case 6:return nt(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 G(`sliceAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}})}function R2(e,t,n){return Z(()=>{switch(e.rank){case 1:return a2(e,t,n);case 2:return w8(e,[0,t],[e.shape[0],n]);case 3:return r2(e,[0,0,t],[e.shape[0],e.shape[1],n]);case 4:return Df(e,[0,0,0,t],[e.shape[0],e.shape[1],e.shape[2],n]);default:throw new G(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function Hf(e,t,n,a){return Z(()=>{switch(e.rank){case 1:return a2(e,t,n);case 2:switch(a){case 1:return oo(e,t,n);case 2:return R2(e,t,n);default:throw new G(`The axis is not within the rank of the tensor ${a}`)}case 3:switch(a){case 1:return oo(e,t,n);case 2:return r2(e,[0,t,0],[e.shape[0],n,e.shape[2]]);case 3:return R2(e,t,n);default:throw new G(`The axis is not within the rank of the tensor ${a}`)}case 4:switch(a){case 1:return oo(e,t,n);case 2:return Df(e,[0,t,0,0],[e.shape[0],n,e.shape[2],e.shape[3]]);case 3:return Df(e,[0,0,t,0],[e.shape[0],e.shape[1],n,e.shape[3]]);case 4:return R2(e,t,n);default:throw new G(`The axis is not within the rank of the tensor ${a}`)}default:throw new G(`sliceAlongLastAxis() received an unsupported tensor rank: ${e.rank}`)}})}function F2(e,t=-1){let n;return t<0&&(n=e[0].rank,n!==0?t=n:t=0),t===e[0].rank&&(t=-1),en(e,t)}function cI(e,t){switch(e.rank){case 1:return _G([e,t]);case 2:return PG([e,t],0);case 3:return WG([e,t],0);case 4:return VG([e,t],0);default:throw new G(`concatAlongFirstAxis() received an unsupported tensor rank: ${e.rank}`)}}function O2(e,t){if(Array.isArray(t)||(t=[t]),e.rank!==t.length)throw new G(`The length of input n (${t.length}) does not match the number of dimensions in input x (${e.rank})`);return Zi(e,t)}function Gf(e,t=0,n=1,a,r){return PK(e,t,n,a,r)}function Fr(e,t,n,a){if(e.rank<2||t.rank<2)throw new He(`dot requires both inputs to be rank >= 2 but got x shape = ${e.shape} and y shape = ${t.shape}`);if(t.rank>=3){let r=e.shape.slice(-1)[0],s=t.shape.slice(-2)[0];if(r!==s)throw new He(`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){let r=!1,s=!1;return eo.matMul({a:e,b:t,transposeA:r,transposeB:s,bias:a?D2(e.rank,a,lr()):null,activation:n})}else{let r=e.shape.slice(),s=r.pop();e=e.reshape([-1,s]);let i=t.shape.slice(),o=i.pop(),l=i.pop(),u=[...i,o],d=Array.from({length:t.rank},(m,f)=>f===0?t.rank-2:f<=t.rank-2?f-1:f);t=t.transpose(d).reshape([l,-1]);let h=[...r,...u],p=!1,c=!1;return eo.matMul({a:e,b:t,transposeA:p,transposeB:c,bias:a?D2(e.rank,a,lr()):null,activation:n}).reshape(h)}}function fI(e,t,n){return Z(()=>(Array.isArray(t)?t=$n(t,"int32"):t=t.toInt(),Mh(e,t,n)))}function Wh(e){return K(e,e)}function D2(e,t,n){let a=t.shape;if(t.rank!==1&&t.rank!==e)throw new G(`Unexpected bias dimensions: ${t.rank}; expected it to be 1 or ${e}`);if(e===5){if(n==="channelsFirst")return a.length===1?t.reshape([1,a[0],1,1,1]):t.reshape([1,a[3],a[0],a[1],a[2]]);if(n==="channelsLast")return a.length===1?t.reshape([1,1,1,1,a[0]]):t.reshape([1].concat(a))}else if(e===4){if(n==="channelsFirst")return a.length===1?t.reshape([1,a[0],1,1]):t.reshape([1,a[2],a[0],a[1]]);if(n==="channelsLast")return a.length===1?t.reshape([1,1,1,a[0]]):t.reshape([1].concat(a))}else if(e===3){if(n==="channelsFirst")return a.length===1?t.reshape([1,a[0],1]):t.reshape([1,a[1],a[0]]);if(n==="channelsLast")return a.length===1?t.reshape([1,1,a[0]]):t.reshape([1].concat(a))}else if(e<3)return t;throw new G(`Unsupported input rank by biasAdd: ${t.rank}`)}function hr(e,t,n){return Z(()=>(n==null&&(n=lr()),Yt(n),e.add(D2(e.rank,t,n))))}function gee(e,t=1){if(t!==1)throw new He(`Support for alpha values other than 1 (${t}) is not implemented yet.`);return Th(e)}function yee(e){return Z(()=>Me(e,yn(e).add(1)))}function mI(e,t,n,a){return Z(()=>LX(e,t,n,a))}function Aee(e){return Z(()=>{let t=pe(.5,K(.2,e));return ua(t,0,1)})}function Bh(e,t,n=!1){return n?e():t()}var xee=["fanIn","fanOut","fanAvg"],bee=["normal","uniform","truncatedNormal"];function vee(e){so(xee,"FanMode",e)}function wee(e){so(bee,"Distribution",e)}var Xa=class extends ue.Serializable{fromConfigUsesCustomObjects(){return!1}getConfig(){return{}}},_2=class extends Xa{apply(e,t){return un(e,t)}};_2.className="Zeros";ue.registerClass(_2);var qf=class extends Xa{apply(e,t){return os(e,t)}};qf.className="Ones";ue.registerClass(qf);var z2=class extends Xa{constructor(e){super();if(typeof e!="object")throw new G(`Expected argument of type ConstantConfig but got ${e}`);if(e.value===void 0)throw new G(`config must have value set but got ${e}`);this.value=e.value}apply(e,t){return Z(()=>K(Re(this.value),os(e,t)))}getConfig(){return{value:this.value}}};z2.className="Constant";ue.registerClass(z2);var P2=class extends Xa{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 Rh(e,this.minval,this.maxval,t)}getConfig(){return{minval:this.minval,maxval:this.maxval,seed:this.seed}}};P2.className="RandomUniform";ue.registerClass(P2);var L2=class extends Xa{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 He(`randomNormal does not support dType ${t}.`);return Gf(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};L2.className="RandomNormal";ue.registerClass(L2);var W2=class extends Xa{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 He(`truncatedNormal does not support dType ${t}.`);return l2(e,this.mean,this.stddev,t,this.seed)}getConfig(){return{mean:this.mean,stddev:this.stddev,seed:this.seed}}};W2.className="TruncatedNormal";ue.registerClass(W2);var B2=class extends Xa{constructor(e){super();this.gain=e.gain!=null?e.gain:1}apply(e,t){return Z(()=>{if(e.length!==2||e[0]!==e[1])throw new G("Identity matrix initializer can only be used for 2D square matrices.");return K(this.gain,u8(e[0]))})}getConfig(){return{gain:this.gain}}};B2.className="Identity";ue.registerClass(B2);function kee(e,t="channelsLast"){let n,a;if(Yt(t),e.length===2)n=e[0],a=e[1];else if([3,4,5].indexOf(e.length)!==-1){if(t==="channelsFirst"){let r=Gs(e,2);n=e[1]*r,a=e[0]*r}else if(t==="channelsLast"){let r=Gs(e,0,e.length-2);n=e[e.length-2]*r,a=e[e.length-1]*r}}else{let r=Gs(e);n=Math.sqrt(r),a=Math.sqrt(r)}return[n,a]}var ea=class extends Xa{constructor(e){super();if(e.scale<0)throw new G(`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,vee(this.mode),this.distribution=e.distribution==null?"normal":e.distribution,wee(this.distribution),this.seed=e.seed}apply(e,t){let n=kee(e),a=n[0],r=n[1],s=this.scale;if(this.mode==="fanIn"?s/=Math.max(1,a):this.mode==="fanOut"?s/=Math.max(1,r):s/=Math.max(1,(a+r)/2),this.distribution==="normal"){let i=Math.sqrt(s);if(t=t||"float32",t!=="float32"&&t!=="int32")throw new He(`${this.getClassName()} does not support dType ${t}.`);return l2(e,0,i,t,this.seed)}else{let i=Math.sqrt(3*s);return Rh(e,-i,i,t)}}getConfig(){return{scale:this.scale,mode:this.mode,distribution:this.distribution,seed:this.seed}}};ea.className="VarianceScaling";ue.registerClass(ea);var Kf=class extends ea{constructor(e){super({scale:1,mode:"fanAvg",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return ea.className}};Kf.className="GlorotUniform";ue.registerClass(Kf);var Xf=class extends ea{constructor(e){super({scale:1,mode:"fanAvg",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return ea.className}};Xf.className="GlorotNormal";ue.registerClass(Xf);var Zf=class extends ea{constructor(e){super({scale:2,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return ea.className}};Zf.className="HeNormal";ue.registerClass(Zf);var Yf=class extends ea{constructor(e){super({scale:2,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return ea.className}};Yf.className="HeUniform";ue.registerClass(Yf);var Jf=class extends ea{constructor(e){super({scale:1,mode:"fanIn",distribution:"normal",seed:e==null?null:e.seed})}getClassName(){return ea.className}};Jf.className="LeCunNormal";ue.registerClass(Jf);var Qf=class extends ea{constructor(e){super({scale:1,mode:"fanIn",distribution:"uniform",seed:e==null?null:e.seed})}getClassName(){return ea.className}};Qf.className="LeCunNormal";ue.registerClass(Qf);var V2=class extends Xa{constructor(e){super();if(this.DEFAULT_GAIN=1,this.gain=e.gain==null?this.DEFAULT_GAIN:e.gain,this.seed=e.seed,this.seed!=null)throw new He("Random seed is not implemented for Orthogonal Initializer yet.")}apply(e,t){return Z(()=>{if(e.length<2)throw new He("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,a=Gf(n,0,1,"float32"),r=dY.gramSchmidt(a);return e[0]>e[1]&&(r=r.transpose()),K(this.gain,r)})}getConfig(){return{gain:this.gain,seed:this.seed}}};V2.className="Orthogonal";ue.registerClass(V2);var gI={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 yI(e,t={}){return Dh(e,ue.SerializationMap.getMap().classNameMap,t,"initializer")}function jt(e){return I2(e)}function Pt(e){if(typeof e=="string"){let t=e in gI?gI[e]:e;if(t==="GlorotNormal")return new Xf;if(t==="GlorotUniform")return new Kf;if(t==="HeNormal")return new Zf;if(t==="HeUniform")return new Yf;if(t==="LeCunNormal")return new Jf;if(t==="LeCunUniform")return new Qf;{let n={};return n.className=t,n.config={},yI(n)}}else return e instanceof Xa?e:yI(e)}function Iee(){return new _2}function See(){return new qf}function Nee(e){return new z2(e)}function Tee(e){return new P2(e)}function Eee(e){return new L2(e)}function Cee(e){return new W2(e)}function Mee(e){return new B2(e)}function $ee(e){return new ea(e)}function Ree(e){return new Kf(e)}function Fee(e){return new Xf(e)}function Oee(e){return new Zf(e)}function Dee(e){return new Yf(e)}function _ee(e){return new Jf(e)}function zee(e){return new Qf(e)}function Pee(e){return new V2(e)}var AI={};$e(AI,{Layer:()=>rt,RNN:()=>cs,RNNCell:()=>Kh,activation:()=>xne,add:()=>Ene,alphaDropout:()=>hae,average:()=>Cne,averagePooling1d:()=>u5,averagePooling2d:()=>d5,averagePooling3d:()=>h5,avgPool1d:()=>Pne,avgPool2d:()=>Wne,avgPool3d:()=>Vne,avgPooling1d:()=>Lne,avgPooling2d:()=>Bne,avgPooling3d:()=>Une,batchNormalization:()=>Dne,bidirectional:()=>aae,concatenate:()=>Mne,conv1d:()=>dne,conv2d:()=>hne,conv2dTranspose:()=>pne,conv3d:()=>cne,conv3dTranspose:()=>fne,convLstm2d:()=>Qne,convLstm2dCell:()=>eae,cropping2D:()=>gne,dense:()=>bne,depthwiseConv2d:()=>Ane,dot:()=>One,dropout:()=>vne,elu:()=>rne,embedding:()=>Tne,flatten:()=>kne,gaussianDropout:()=>dae,gaussianNoise:()=>uae,globalAveragePooling1d:()=>jne,globalAveragePooling2d:()=>Hne,globalMaxPool1d:()=>sae,globalMaxPool2d:()=>iae,globalMaxPooling1d:()=>$S,globalMaxPooling2d:()=>RS,gru:()=>qne,gruCell:()=>Kne,input:()=>YI,inputLayer:()=>ane,layerNormalization:()=>_ne,leakyReLU:()=>ine,lstm:()=>Xne,lstmCell:()=>Zne,masking:()=>pae,maxPool1d:()=>oae,maxPool2d:()=>lae,maxPooling1d:()=>FS,maxPooling2d:()=>OS,maxPooling3d:()=>Gne,maximum:()=>$ne,minimum:()=>Rne,multiply:()=>Fne,permute:()=>Nne,prelu:()=>one,reLU:()=>sne,repeatVector:()=>Ine,reshape:()=>Sne,rnn:()=>tae,separableConv2d:()=>mne,simpleRNN:()=>Yne,simpleRNNCell:()=>Jne,softmax:()=>lne,spatialDropout1d:()=>wne,stackedRNNCells:()=>nae,thresholdedReLU:()=>une,timeDistributed:()=>rae,upSampling2d:()=>yne,zeroPadding2d:()=>zne});var Lee=0;function xI(){return Lee++}var e0={};function t0(e=""){return e in e0||(e0[e]=0),e0[e]+=1,e+e0[e].toString()}function U2(e){return Array.isArray(e)&&Array.isArray(e[0])}function n0(e){return e.length===0?[]:Array.isArray(e[0])?e:[e]}function Ke(e){let t;if(Array.isArray(e)){if(e.length!==1)throw new G(`Expected Tensor length to be 1; got ${e.length}`);t=e[0]}else t=e;return t}function At(e){if(Array.isArray(e)&&Array.isArray(e[0])){if(e.length===1)return e=e,e[0];throw new G(`Expected exactly 1 Shape; got ${e.length}`)}else return e}function a0(e){let t=0;for(let n of e)n.shape.length===0?t+=1:t+=n.shape.reduce((a,r)=>a*r);return t}var bI="Variable",vI=class{constructor(e,t="float32",n=bI,a=!0,r=null){this.dtype=t==null?"float32":t,this.shape=e.shape,this.id=xI(),n=n==null?bI:n,this.originalName=dI(n),this.name=hI(this.originalName),this.trainable_=a,this.constraint=r,this.val=NX(e,this.trainable_,this.name,this.dtype)}read(){return this.assertNotDisposed(),this.val}write(e){return this.assertNotDisposed(),Wee(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 Wee(e,t){if(e.shape.toString()!==t.shape.toString())throw new Error("Shape mismatch: "+JSON.stringify(e.shape)+" vs. "+JSON.stringify(t.shape))}function j2(e){return e.map(t=>t.read())}function H2(e){e.forEach(t=>{t[0].write(t[1])})}var tn=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||{}}},pr=class{constructor(e,t,n,a,r,s,i){this.dtype=e,this.shape=t,this.sourceLayer=n,this.inputs=a,this.callArgs=r,this.outputTensorIndex=i,this.id=xI(),s!=null&&(this.originalName=dI(s),this.name=hI(this.originalName)),this.rank=t.length}},Bee=0,r0=class{constructor(e,t){this.callArgs=t,this.id=Bee++,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}}},Vee=0,rt=class extends ue.Serializable{constructor(e={}){super();this._callHook=null,this._addedWeightNames=[],this._stateful=!1,this.id=Vee++,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=hs(n)+"_"+t0(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 r=null;e.batchSize!=null&&(r=e.batchSize),n=[r].concat(e.inputShape)}this.batchInputShape=n;let a=e.dtype;a==null&&(a=e.inputDType),a==null&&(a="float32"),this.dtype=a}e.weights!=null?this.initialWeights=e.weights:this.initialWeights=null,this._refCount=null,this.fastWeightInitDuringBuild=!1}static nodeKey(e,t){return e.name+"_ib-"+t.toString()}getNodeAtIndex(e,t){if(this.inboundNodes.length===0)throw new ur(`The layer has never been called and thus has no defined ${t}.`);if(this.inboundNodes.length<=e)throw new G(`Asked to get ${t} at node ${e}, but the layer has only ${this.inboundNodes.length} inbound nodes.`);return this.inboundNodes[e]}getInputAt(e){return Qn(this.getNodeAtIndex(e,"input").inputTensors)}getOutputAt(e){return Qn(this.getNodeAtIndex(e,"output").outputTensors)}get input(){if(this.inboundNodes.length>1)throw new ds(`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 ds(`Layer ${this.name} is not connected, no input to return.`);return Qn(this.getNodeAtIndex(0,"input").inputTensors)}get output(){if(this.inboundNodes.length===0)throw new ds(`Layer ${this.name} has no inbound nodes.`);if(this.inboundNodes.length>1)throw new ds(`Layer ${this.name} has multiple inbound nodes, hence the notion of "layer output" is ill-defined. Use \`getOutputAt(nodeIndex)\` instead.`);return Qn(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=Ft(e),this.inputSpec==null||this.inputSpec.length===0)return;let t=Ft(this.inputSpec);if(e.length!==t.length)throw new G(`Layer ${this.name} expects ${t.length} inputs, but it received ${e.length} input tensors. Input received: ${e}`);for(let n=0;nr.maxNDim)throw new G(`Input ${n} is incompatible with layer ${this.name}: expected max_ndim=${r.maxNDim}, found ndim=${s}`);if(r.minNDim!=null&&s=0?i[l]:i[i.length+l];if(u!=null&&[u,null].indexOf(d)===-1)throw new G(`Input ${n} is incompatible with layer ${this.name}: expected axis ${l} of input shape to have value ${u} but got shape ${i}.`)}}if(r.shape!=null)for(let i=0;i{if(!this.built){this.assertInputCompatibility(e);let s=[];for(let i of Ft(e))s.push(i.shape);this.build(Qn(s)),this.built=!0,this.initialWeights&&this.setWeights(this.initialWeights),this._refCount===null&&r&&(this._refCount=1)}if(this.assertInputCompatibility(e),r){let s=this.call(e,t),i=Ft(s),o=[];for(let l of i)n.indexOf(l)!==-1&&(l=l.clone()),o.push(l);if(s=Qn(o),this.activityRegularizer!=null)throw new He("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return s}else{let s=Uee(e),i=this.computeOutputShape(s),o,l=jee(e);if(this.warnOnIncompatibleInputShape(Array.isArray(e)?s[0]:s),i!=null&&i.length>0&&Array.isArray(i[0])?o=i.map((u,d)=>new pr(l,u,this,Ft(e),t,this.name,d)):o=new pr(l,i,this,Ft(e),t,this.name),this.addInboundNode(e,o,null,null,s,i,t),this._refCount++,this.activityRegularizer!=null)throw new He("Layer invocation in the presence of activity regularizer(s) is not supported yet.");return o}})}warnOnIncompatibleInputShape(e){if(this.batchInputShape!=null)if(e.length!==this.batchInputShape.length)console.warn(`The rank of the input tensor provided (shape: ${JSON.stringify(e)}) does not match that of the batchInputShape (${JSON.stringify(this.batchInputShape)}) of the layer ${this.name}`);else{let t=!1;this.batchInputShape.forEach((n,a)=>{n!=null&&e[a]!=null&&e[a]!==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 ds(`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 ds(`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 ur(`You tried to call countParams() on ${this.name}, but the layer is not built yet. Build it first by calling build(batchInputShape).`);return a0(this.weights)}build(e){this.built=!0}getWeights(e=!1){return j2(e?this.trainableWeights:this.weights)}setWeights(e){Z(()=>{let t=this.weights;if(t.length!==e.length)throw new G(`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=[],a=j2(t);for(let r=0;rr.apply(l.read())),s==null&&(s=!0),s?this._trainableWeights.push(l):this._nonTrainableWeights.push(l),l}setFastWeightInitDuringBuild(e){this.fastWeightInitDuringBuild=e}addLoss(e){e==null||Array.isArray(e)&&e.length===0||(e=Ft(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,a,r,s,i=null){let o=Ft(e);t=Ft(t),n=Ft(n),a=Ft(a),r=n0(r),s=n0(s);let l=[],u=[],d=[];for(let h of o)l.push(h.sourceLayer),u.push(h.nodeIndex),d.push(h.tensorIndex);new r0({outboundLayer:this,inboundLayers:l,nodeIndices:u,tensorIndices:d,inputTensors:o,outputTensors:t,inputMasks:n,outputMasks:a,inputShapes:r,outputShapes:s},i);for(let h=0;he.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 Uee(e){e=Ft(e);let t=[];for(let n of e)t.push(n.shape);return Qn(t)}function jee(e){return"float32"}function wI(e,t,n){if((t==null||n!=null&&n>0)&&(t=e.sourceLayer,n=e.nodeIndex),t.inboundNodes.length===0)return[e];{let a=t.inboundNodes[n];if(a.inboundLayers.length===0)return a.inputTensors;{let r=[];for(let s=0;s0){let r=await Promise.all(t);for(let s=0;spe(this.totals[a],K(r,n)));this.totals[a]=i,s!=null&&s.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:Z(()=>{let a=K(Me(1,this.seen),this.totals[n]);t[n]=a,this.totals[n].dispose(),Sn(t[n])}))}},TI=class extends su{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 r in this.history){let s=this.history[r];for(let i=0;inew EI(n,t))}var Or=class{constructor(){}static registerCallbackConstructor(e,t){k.assert(e>=0&&Number.isInteger(e),()=>`Verbosity level is expected to be an integer >= 0, but got ${e}`),Or.checkForDuplicate(t),Or.constructors[e]==null&&(Or.constructors[e]=[]),Or.constructors[e].push(t)}static checkForDuplicate(e){for(let t in Or.constructors)Or.constructors[+t].forEach(n=>{if(n===e)throw new G("Duplicate callback constructor.")})}static clear(){Or.constructors={}}static createCallbacks(e){let t=[];for(let n in Or.constructors){let a=+n;e>=a&&t.push(...Or.constructors[a])}return t.map(n=>new n)}},G2=Or;G2.constructors={};function MI(e,t,n,a,r,s,i,o,l){let u=new TI,d=[new Gee,...G2.createCallbacks(t)];e!=null&&d.push(...e),d.push(u);let h=new NI(d);return h.setParams({epochs:n,initialEpoch:a,samples:r,steps:s,batchSize:i,verbose:t,doValidation:o,metrics:l}),{callbackList:h,history:u}}function cr(e,t={},n=!1){return Dh(e,ue.SerializationMap.getMap().classNameMap,t,"layer",n)}function s0(e,t){return Z(()=>{e.dtype!=="float32"&&(e=e.asType("float32"));let n=Ce(Wh(e),t,!0),a=Eh(n.shape,dn()),r=Mn(is(n,a));return Me(e,r)})}function lo(e,t){return Z(()=>Xt(Wh(Ne(t,e)),-1))}function i0(e,t){return Z(()=>Xt(yn(Ne(t,e)),-1))}function iu(e,t){return Z(()=>{let n=Ne(e,t),a=ua(yn(e),dn(),Number.MAX_VALUE),r=yn(Me(n,a));return K(100,Xt(r,-1))})}function qee(e,t){return Z(()=>{let n=ua(t,dn(),Number.MAX_VALUE),a=Ma(pe(1,n)),r=ua(e,dn(),Number.MAX_VALUE),s=Ma(pe(1,r));return Xt(Wh(Ne(a,s)),-1)})}function Kee(e,t){return Z(()=>{let n=is(0,Ne(1,K(e,t)));return Xt(Wh(n),-1)})}function Xee(e,t){return Z(()=>{let n=is(0,Ne(1,K(e,t)));return Xt(n,-1)})}function Zee(e,t){return Z(()=>{let n=Ce(K(e,t),-1),a=sr(K(Ne(1,e),t),-1);return is(0,pe(1,Ne(a,n)))})}function Yee(e,t){return Z(()=>{let n=Math.log(2),a=Ne(t,e),r=Ne(pe(a,Zl(K(-2,a))),n);return Xt(r,-1)})}function Vh(e,t,n=!1){return Z(()=>{if(n)t=_f(t);else{let a=Ce(t,t.shape.length-1,!0);t=Me(t,a)}return t=ua(t,dn(),1-dn()),Kt(Ce(K(e.toFloat(),Ma(t)),t.shape.length-1))})}function o0(e,t,n=!1){return Z(()=>{let a=Ch(fee(e)).toInt();t=ua(t,dn(),1-dn());let r=t.shape,s=kh(a,r[r.length-1]).reshape(r);return Vh(s,t,n)})}function Jee(e,t){if(!k.arraysEqual(e.shape,t.shape))throw new G(`logits and labels must have the same shape, but got shapes ${JSON.stringify(e.shape)} and ${JSON.stringify(t.shape)}`);return Z(()=>{let n=t.relu(),a=t.abs().neg();return n.sub(t.mul(e)).add(a.exp().log1p())})}function l0(e,t){return Z(()=>{let n;return n=ua(t,dn(),1-dn()),n=Ma(Me(n,Ne(1,n))),Xt(Jee(e,n),-1)})}function Qee(e,t){return Z(()=>{let n=ua(e,dn(),1),a=ua(t,dn(),1);return Ce(K(e,Ma(Me(n,a))),-1)})}function ete(e,t){return Z(()=>{let n=Ma(pe(dn(),t));return Xt(Ne(t,K(e,n)),-1)})}function q2(e,t){return Z(()=>{let n=s0(e,-1),a=s0(t,-1),r=K(n,a);return Kt(Ce(r,-1))})}var u0={meanSquaredError:lo,meanAbsoluteError:i0,meanAbsolutePercentageError:iu,meanSquaredLogarithmicError:qee,squaredHinge:Kee,hinge:Xee,categoricalHinge:Zee,logcosh:Yee,categoricalCrossentropy:Vh,sparseCategoricalCrossentropy:o0,binaryCrossentropy:l0,kullbackLeiblerDivergence:Qee,poisson:ete,cosineProximity:q2};function K2(e){if(typeof e=="string"){if(e in u0)return u0[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 G(t)}else return e}function X2(e,t){return Z(()=>{let n=K(.5,$a(t)),a=Ph(Ca(t,n),e.dtype);return Xt(Xi(e,a),-1)})}function Z2(e,t){return Z(()=>Ph(Xi(kf(e,-1),kf(t,-1)),"float32"))}function $I(e,t){return Z(()=>ir(e.equal(1),t.equal(1)).sum().cast("float32"))}function tte(e,t){return Z(()=>ir(e.equal(1),t.equal(0)).sum().cast("float32"))}function nte(e,t){return Z(()=>ir(e.equal(0),t.equal(1)).sum().cast("float32"))}function RI(e,t){return Z(()=>{let n=$I(e,t),a=nte(e,t),r=n.add(a);return Pn(Ca(r,0),n.div(r),0).cast("float32")})}function ate(e,t){return Z(()=>{let n=$I(e,t),a=tte(e,t),r=n.add(a);return Pn(Ca(r,0),n.div(r),0).cast("float32")})}function FI(e,t){return l0(e,t)}function OI(e,t){return e.rank===t.rank&&(e=e.squeeze([e.rank-1])),t=t.argMax(-1),t.dtype!==e.dtype&&(t=t.asType(e.dtype)),Xi(e,t).asType("float32")}var rte=lo,ste=lo,ite=i0,ote=i0,lte=iu,ute=iu,Y2=Vh,dte=q2,DI=o0,d0={binaryAccuracy:X2,categoricalAccuracy:Z2,precision:RI,categoricalCrossentropy:Y2,sparseCategoricalCrossentropy:DI,mse:rte,MSE:ste,mae:ite,MAE:ote,mape:lte,MAPE:ute,cosine:dte};function hte(e){if(typeof e=="string"&&e in d0)return d0[e];if(typeof e!="string"&&e!=null)return e;throw new G(`Unknown metric ${e}`)}function h0(e){if(Rr(e!==null,`Unknown LossOrMetricFn ${e}`),typeof e=="string")return e;{let t;for(let n of Object.keys(u0))if(u0[n]===e){t=n;break}if(t!==void 0)return t;for(let n of Object.keys(d0))if(d0[n]===e){t=n;break}return t!==void 0?t:e.name}}function pte(e){let t={Adagrad:()=>tu.adagrad(.01),Adadelta:()=>tu.adadelta(1,.95,dn()),Adam:()=>tu.adam(.001,.9,.999,dn()),Adamax:()=>tu.adamax(.002,.9,.999,dn(),0),RMSProp:()=>tu.rmsprop(.001,.9,0,dn()),SGD:()=>tu.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 G(`Unknown Optimizer ${e}`)}var _I=1*1024*1024;function zI(e,t,n=!1){if(e==null||typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype||!J2(e))throw new Error("User-defined metadata is expected to be a JSON object, but is not.");if(n){let a=JSON.stringify(e);a.length>_I&&console.warn(`User-defined metadata of model "${t}" is too large in size (length=${a.length} when serialized). It is not recommended to store such large objects in user-defined metadata. Please make sure its serialized length is <= ${_I}.`)}}function J2(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"||!J2(e[n]))return!1;return!0}else if(Array.isArray(e)){for(let t of e)if(!J2(t))return!1;return!0}else return!1;else{let t=typeof e;return t==="string"||t==="number"||t==="boolean"}}function cte(e,t,n,a=console.log){let r=mte(e),s=["Layer (type)","Output shape","Param #"];r?(t=t||65,n=n||[.45,.85,1]):(t=t||98,n=n||[.33,.55,.67,1]),n[n.length-1]<=1&&(n=n.map(d=>Math.floor(t*d)));let i;if(!r){s.push("Receives inputs"),i=[];for(let d in e.nodesByDepth)i.push(...e.nodesByDepth[d])}a("_".repeat(t)),p0(s,n,a),a("=".repeat(t));let o=e.layers;for(let d=0;d1||r.length===1&&r[0].inboundLayers.length>1){t=!1;break}a.push(...r)}if(t)for(let r of e.layers){let s=!1;for(let i of r.inboundNodes)if(a.indexOf(i)!==-1)if(s){t=!1;break}else s=!0;if(!t)break}return t}function p0(e,t,n=console.log){let a="";for(let r=0;r0&&(a=a.slice(0,a.length-1)+" "),a+=e[r],a=a.slice(0,t[r]),a+=" ".repeat(t[r]-a.length);n(a)}function gte(e,t,n){let a;try{a=JSON.stringify(e.outputShape)}catch(o){a="multiple"}let r=e.name,s=e.getClassName(),i=[`${r} (${s})`,a,e.countParams().toString()];p0(i,t,n)}function yte(e,t,n,a){let r;try{r=JSON.stringify(e.outputShape)}catch(d){r="multiple"}let s=[];for(let d of e.inboundNodes)if(!(n!=null&&n.length>0&&n.indexOf(d)===-1))for(let h=0;hm.name),l=[],u=t.names();for(let m of o)u.indexOf(m)!==-1?l.push(t.getValue(m)):l.push(null);a!=null&&(a.maxNumTensors=-Infinity,a.minNumTensors=Infinity);let d=o.join(",")+"|"+t.names().join(","),h,p;if(tx[d]==null){let m=xte(i,t);h=m.sorted,p=m.recipientCounts,tx[d]=h,LI[d]=p}h=tx[d],p={},r||Object.assign(p,LI[d]);let c=new uo(t);for(let m=0;ma.maxNumTensors&&(a.maxNumTensors=C),C0,()=>"Expected at least one fetch, got none");let n=[],a={};if(e.length===1){let r=WI(e[0],t);n=r.sorted,a=r.recipientMap}else{let r=new Set;for(let s of e){let{sorted:i,recipientMap:o}=WI(s,t);for(let l of i)r.has(l.name)||(n.push(l),r.add(l.name));for(let l in o)a[l]==null&&(a[l]=new Set),o[l].forEach(u=>a[l].add(u))}}return{sorted:n,recipientCounts:bte(a)}}function bte(e){let t={};for(let n in e)t[n]=e[n].size;return t}function WI(e,t){let n=new Set,a=[],r={};for(let o of t.names())n.add(o);let s=[],i=[];for(s.push(e);s.length>0;){let o=s[s.length-1];if(n.has(o.name)){s.pop();continue}let l=i[i.length-1]===s.length-1;if(o.inputs.length===0||l)s.pop(),a.push(o),n.add(o.name),l&&i.pop();else{i.push(s.length-1);for(let u of o.inputs)r[u.name]==null&&(r[u.name]=new Set),r[u.name].add(o.name),!n.has(u.name)&&s.push(u)}}return{sorted:a,recipientMap:r}}function vte(e){let t;if(e.sourceLayer.inboundNodes.length===1)t=e.sourceLayer.output;else{let n=null;for(let a=0;ay.name)}`);Hs(this.outputs).length!==this.outputs.length&&console.warn(`The list of outputs passed to the model is redundant. All outputs should only appear once. Found: ${this.outputs.map(y=>y.name)}`),this.inputLayers=[],this.inputLayersNodeIndices=[],this.inputLayersTensorIndices=[],this.outputLayers=[],this.outputLayersNodeIndices=[],this.outputLayersTensorIndices=[],this.layers=[],this.internalContainerRefs=[];for(let y of this.outputs){let A=y.sourceLayer,x=y.nodeIndex,v=y.tensorIndex;this.outputLayers.push(A),this.outputLayersNodeIndices.push(x),this.outputLayersTensorIndices.push(v)}for(let y of this.inputs){let A=y.sourceLayer,x=y.nodeIndex,v=y.tensorIndex;Rr(x===0,"input layer has >1 nodes"),Rr(v===0,"input layer has >1 tensors"),this.inputLayers.push(A),this.inputLayersNodeIndices.push(x),this.inputLayersTensorIndices.push(v)}this.inputNames=[],this.outputNames=[],this.feedInputShapes=[],this.feedInputNames=[],this.feedOutputNames=[];for(let y=0;yy.shape),this.internalOutputShapes=this.outputs.map(y=>y.shape);let t={},n={},a={},r={},s={},i=[],o=(y,A,x,v,b,w)=>{(v==null||b==null||w==null)&&(v=y.sourceLayer,b=y.nodeIndex,w=y.tensorIndex);let I=v.inboundNodes[b];if(x.indexOf(I)!==-1)throw new ur(`The tensor ${y.name} at layer "${v.name}" is part of a cycle.`);if(A.indexOf(I)!==-1)return;this.containerNodes.add(Dr.nodeKey(v,b)),v.id in s||(s[v.id]=Object.keys(s).length),x.indexOf(I)===-1&&x.push(I);let T=I.inboundLayers.length;for(let C=0;C=0;)x.splice(x.indexOf(I),1);i.push(I)},l=[],u=[];for(let y of this.outputs)o(y,l,u);let d=i.slice().reverse();for(let y of d){n[y.id]=y,y.id in t||(t[y.id]=0);let A=t[y.id],x=a[y.outboundLayer.id]==null?0:a[y.outboundLayer.id];A=Math.max(A,x),a[y.outboundLayer.id]=A,r[y.outboundLayer.id]=y.outboundLayer,t[y.id]=A;for(let v=0;vparseInt(y,10)).sort(jf);this.layers=[];for(let y of c){let A=p[y];A.sort((x,v)=>{let b=s[x.id],w=s[v.id];return bw?1:0});for(let x of A)x instanceof Dr&&this.internalContainerRefs.push(x),this.layers.push(x)}this.layersByDepth=p,c=Object.keys(h).map(y=>parseInt(y,10)).sort(jf);let m=this.inputs.slice(),f=[];for(let y of c)for(let A of h[y]){let x=A.outboundLayer;if(x!=null){for(let v of A.inputTensors)if(m.indexOf(v)===-1)throw new ur(`Graph disconnected: cannot obtain value for tensor ${v} at layer "${x.name}". The following previous layers were accessed without issue: ${f}`);for(let v of A.outputTensors)m.push(v);f.push(x.name)}}this.nodesByDepth=h;let g=this.layers.map(y=>y.name);for(let y of g){let A=g.filter(x=>x===y).length;if(A!==1)throw new ur(`The name "${y}" is used ${A} times in the model. All layer names should be unique. Layer names: `+JSON.stringify(g))}this.outboundNodes=[],this.inboundNodes=[],new r0({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 G("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={},a=0;for(let s of this.layers)for(let i of s.weights){if(n[i.originalName]!=null)throw new G(`Duplicate weight name: ${i.originalName}`);n[i.originalName]=i,a++}let r=[];for(let s in e){let i=s;if(n[s]==null){let o=s.split("/");i=o.slice(0,-2).concat([o[o.length-1]]).join("/")}if(n[i]!=null)r.push([n[i],e[s]]);else if(t)throw new G(`Provided weight data has no target variable: ${s}`);delete n[i]}if(t){let s=[];for(let i in n)s.push(i);if(s.length>0)throw new G(`${s.length} of ${a} weights are not set: ${s}`)}H2(r)}updatedConfig(){let e=this.getConfig(),t={};return t.className=this.getClassName(),t.config=e,t.kerasVersion=`tfjs-layers ${ex}`,t.backend="TensorFlow.js",t}toJSON(e,t=!0){let n=Q2(this.updatedConfig());return t?JSON.stringify(n):n}call(e,t){return Z(()=>{e=Ft(e);let n=new uo;for(let a=0;a{e=Ft(e);let n;return t==null?n=ao(null,e.length):n=Ft(t),this.runInternalGraph(e,n)[1]})}computeOutputShape(e){let t=n0(e);if(t.length!==this.inputLayers.length)throw new G(`Invalid inputShape argument ${e}: model has ${this.inputLayers.length} tensor inputs.`);let n={};for(let i=0;iparseInt(i,10)).sort(jf);if(a.length>1)for(let i of a){let o=this.nodesByDepth[i];for(let l of o){let u=l.outboundLayer;if(this.inputLayers.map(m=>m.id).indexOf(u.id)!==-1)continue;let d=[];for(let m=0;mparseInt(o,10)).sort(jf);for(let o of a){let l=this.nodesByDepth[o];for(let u of l){let d=u.outboundLayer,h=u.inputTensors,p=u.outputTensors,c=new Array;for(let m of h)m.id in n&&c.push(n[m.id]);if(c.length===h.length){let m={},f,g,y,A;if(u.callArgs!=null&&(m=u.callArgs),c.length===1){let[x,v]=c[0];m.mask==null&&(m.mask=v),y=Ft(d.call(x,m)),A=Ft(d.computeMask(x,v)),f=[x],g=[v]}else f=c.map(x=>x[0]),g=c.map(x=>x[1]),m.mask==null&&(m.mask=g),y=Ft(d.call(f,m)),A=Ft(d.computeMask(f,g));if(d.activityRegularizer)throw new He("LayersModel invocation with concrete Tensor value(s) in the presence of activity regularizer(s) is not supported yet.");for(let x=0;x{let e=[];for(let t of this.layers)for(let n=0;n0){let m=[];for(let f=0;f0&&f.apply(Qn(y),A)}function l(f){let g=f.name,y=cr(f,t.customObjects!=null?t.customObjects:{});y.setFastWeightInitDuringBuild(a),r[g]=y,f.inboundNodes.forEach(A=>{if(!(A instanceof Array))throw new G(`Corrupted configuration, expected array for nodeData: ${A}`);i(y,A)})}let u=t.name,d=t.layers;for(let f of d)l(f);for(;!JQ(s);)for(let f of d){let g=r[f.name];if(g.name in s){let y=s[g.name];delete s[g.name];for(let A of y)o(g,A)}}let h=[],p=[],c=t.inputLayers;for(let f of c){let g=f[0],y=f[1],A=f[2];Rr(g in r);let x=r[g].inboundNodes[y].outputTensors;h.push(x[A])}let m=t.outputLayers;for(let f of m){let g=f[0],y=f[1],A=f[2];Rr(g in r);let x=r[g].inboundNodes[y].outputTensors;p.push(x[A])}return new e({inputs:h,outputs:p,name:u})}get stateful(){if(this._stateful)throw new G("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(){Z(()=>{this.layers.forEach(e=>{e.stateful&&e.resetStates()})})}};function wte(e,t,n){let a=t.length;if(e==null||Array.isArray(e)&&e.length===0)return t.map(r=>null);if(a===1)return Array.isArray(e)&&e.length===1?e:typeof e=="object"&&t[0]in e?[e[t[0]]]:[e];if(Array.isArray(e)){if(e.length!==a)throw new Error(`Provided ${n} is an array of ${e.length} element(s), but the model has ${a} outputs. Make sure a set of weights is provided for each model output.`);return e}else if(typeof e=="object"&&Object.keys(e).length>0&&typeof e[Object.keys(e)[0]]=="object"){let r=[];return t.forEach(s=>{s in e?r.push(e[s]):r.push(null)}),r}else throw new Error(`The model has multiple (${a}) outputs, so ${n} must be either an array with ${a} elements or an object with ${t} keys. Provided ${n} not understood: ${JSON.stringify(e)}`)}function BI(e,t){return wte(e,t,"classWeight")}async function VI(e,t,n,a){if(t!=null||a!=null)throw new Error("Support sampleWeight is not implemented yet");if(n!=null){let r=Z(()=>{if(e.shape.length===1)return e.clone();if(e.shape.length===2)if(e.shape[1]>1){let o=1;return e.argMax(o)}else{if(e.shape[1]===1)return e.reshape([e.shape[0]]);throw new Error(`Encountered unexpected last-dimension size (${e.shape[1]}) during handling of class weights. The size is expected to be >= 1.`)}else throw new Error(`Unexpected rank of target (y) tensor (${e.rank}) during handling of class weights. The rank is expected to be 1 or 2.`)}),s=Array.from(await r.data());Ge(r);let i=[];return s.forEach(o=>{if(n[o]==null)throw new Error(`classWeight must contain all classes in the training data. The class ${o} exists in the data but not in classWeight`);i.push(n[o])}),$n(i,"float32")}else return null}function kte(e,t){return K(e,t)}var Ite=32;function UI(e,t){let n,a,r=t;n=r.xs,a=r.ys,k.assert(n!=null&&a!=null,()=>`A Dataset iterator for fitDataset() is expected to generate objects of the form \`{xs: xVal, ys: yVal}\`, where the two values may be \`tf.Tensor\`, an array of Tensors, or a map of string to Tensor. The provided Dataset instead generates ${t}`);let s=jI("input",e.inputNames,n),i=jI("output",e.outputNames,a),o=s[0].shape[0];k.assert(s.length===e.inputs.length,()=>`LayersModel has ${e.inputs.length} inputs, but the dataset provides ${s.length} inputs. (Expected input keys: ${JSON.stringify(e.inputNames)})`),k.assert(i.length===e.outputs.length,()=>`LayersModel has ${e.outputs.length} outputs, but the dataset provides ${i.length} outputs. (Expected output keys: ${JSON.stringify(e.outputNames)})`);for(let l=0;l`Batch size mismatch: input ${e.inputNames[l]} has ${s[l].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`);for(let l=0;l`Batch size mismatch: output ${e.outputNames[l]} has ${i[l].shape[0]}; expected ${o} based on input ${e.inputNames[0]}.`);return{xs:s,ys:i}}function jI(e,t,n){if(n instanceof Tt)return[n];if(Array.isArray(n))return k.assert(n.length===t.length,()=>`Received an array of ${n.length} Tensors, but expected ${t.length} to match the ${e} keys ${t}.`),n;{let a=[];for(let r of t){if(n[r]==null)throw new G(`The feature data generated by the dataset lacks the required ${e} key '${r}'.`);a.push(n[r])}return a}}function Ste(e){if(e.length===3)throw new He("Validation with sample weights is not implemented yet.");return{xs:e[0],ys:e[1]}}async function Nte(e,t,n){let a=n.batchesPerEpoch!=null;if(k.assert(e.optimizer!=null,()=>"You must compile a model before training/testing. Use LayersModel.compile(modelCompileConfig)."),k.assert(n!=null,()=>"For fitDataset(), the 2nd argument (config) is required, but it is not provided in this call."),k.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}`),k.assert(!a||n.batchesPerEpoch>0&&Number.isInteger(n.batchesPerEpoch),()=>`For fitDataset(), config.batchesPerEpoch is expected to be a positive integer if specified, but got ${n.batchesPerEpoch}`),k.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 r=n.validationData!=null,s,i;if(r)if(HI(n.validationData))k.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=Ste(n.validationData);s=g.xs,i=g.ys}let o=e.makeTrainFunction(),l=e.getDedupedMetricsNames(),u;r?u=l.slice().concat(l.map(g=>"val_"+g)):u=l.slice();let d=CI(n.callbacks,n.yieldEvery),h=n.verbose==null?1:n.verbose,{callbackList:p,history:c}=MI(d,h,n.epochs,null,null,Tte(t,n),null,r,u);p.setModel(e),e.history=c,await p.onTrainBegin(),e.stopTraining_=!1;let m=n.initialEpoch==null?0:n.initialEpoch,f=await t.iterator();for(;m=n.batchesPerEpoch:x.done){if(r){let v;HI(n.validationData)?v=Ft(await e.evaluateDataset(n.validationData,{batches:n.validationBatches})):v=Ft(e.evaluate(s,i,{batchSize:n.validationBatchSize==null?Ite:n.validationBatchSize,verbose:0}));for(let b=0;b0)throw new He("Verbose mode is not implemented yet.");k.assert(!a||n.batches>0&&Number.isInteger(n.batches),()=>`Test loop expects \`batches\` to be a positive integer, but received ${JSON.stringify(n.batches)}`);let i=Ete(t)?t:await t.iterator(),o=0,l=0;for(;a?l{if(u.value){let{xs:d,ys:h}=UI(e,u.value),p=d.concat(h),c=Z(()=>r(p));if(Ge(p),l===0)for(let f=0;fpe(s[f],K(m,g))),l>0&&Ge(y)}Ge(c),o+=m,++l}return s}),u.done){a&&console.warn(`Your dataset iterator ran out of data during evaluateDataset(). Interrupting evalution. Make sure that your dataset can generate at least \`batches\` batches (in this case, ${n.batches} batches). You may need to use the repeat() function when building your dataset.`);break}}for(let u=0;u0&&Number.isInteger(e),()=>`batchSize is required to be a positive integer, but got ${e}`)}function Hh(e,t,n){return e==null?[null]:Array.isArray(e)?e.map(a=>oo(a,t,n-t)):oo(e,t,n-t)}function ax(e,t){return Z(()=>e==null?null:Array.isArray(e)?e.map(n=>ax(n,t)):fI(e,t.dtype==="int32"?t:t.toInt()))}function rx(e,t){let n=[],a=0,r=null;for(;a=e&&(r=e),n.push([a,r]),a=r;return n}async function Mte(e,t,n,a,r,s,i,o,l,u,d,h,p,c,m){r==null&&(r=32),s==null&&(s=1),d==null&&(d=!0),p==null&&(p=0);let f=!1;if(l!=null&&u!=null&&(f=!0),m!=null&&(f=!0,c==null))throw new G("Can only use `validationSteps` when doing step-wise training, i.e., `stepsPerEpoch` must be set.");let g=e.checkNumSamples(n,r,c,"steps_per_epoch"),y;g!=null&&(y=dr(0,g)),i==null&&(i=1);let{callbackList:A,history:x}=MI(o,i,s,p,g,c,r,f,h);A.setModel(e),e.history=x,await A.onTrainBegin(),e.stopTraining_=!1;for(let v=p;v{let z=I[T][0],$=I[T][1],S=oo(w,z,$-z);C.batch=T,C.size=$-z;let D=ax(n,S),_=t(D);for(let W=0;W0){if(m=!0,a.validationData.length===2)i=a.validationData[0],o=a.validationData[1];else throw a.validationData.length===3?new He("validationData including sample weights is not supported yet."):new G(`When passing validation data, it must contain 2 (valX, valY) or 3 (valX, valY, valSampleWeight) items; ${a.validationData} is invalid.`);let w=!0,I=await e.standardizeUserData(i,o,null,null,w,h);l=I[0],u=I[1],f=l.concat(u)}else if(a.validationSplit!=null&&a.validationSplit>0&&a.validationSplit<1){m=!0;let w=Math.floor(r[0].shape[0]*(1-a.validationSplit)),I=r[0].shape[0];l=Hh(r,w,I),r=Hh(r,0,w),u=Hh(s,w,I),s=Hh(s,0,w),f=l.concat(u)}else a.validationSteps!=null&&(m=!0);let g=r.concat(s).concat(d);e.checkTrainableWeightsConsistency();let y=e.makeTrainFunction(),A=e.getDedupedMetricsNames(),x,v;m?(e.makeTestFunction(),x=e.testFunction,v=A.slice().concat(A.map(w=>"val_"+w))):(x=null,f=[],v=A.slice());let b=CI(a.callbacks,a.yieldEvery);return await Mte(e,y,g,A,h,a.epochs,a.verbose,b,x,f,a.shuffle,v,a.initialEpoch,null,null)}finally{e.isTraining=!1,ho(r,t),ho(s,n),ho(l,i),ho(u,o),d!=null&&Ge(d)}}function GI(e){let t=[];e instanceof Tt&&(e=[e]);for(let n=0;nn.push(r.id));else if(t!=null)for(let r in t){let s=t[r];n.push(s.id)}let a=[];if(e instanceof Tt)n.indexOf(e.id)===-1&&a.push(e);else if(Array.isArray(e))e.forEach(r=>{n.indexOf(r.id)===-1&&a.push(r)});else if(e!=null)for(let r in e){let s=e[r];n.indexOf(s.id)===-1&&a.push(s)}a.forEach(r=>{r.isDisposed||r.dispose()})}function Rte(e){return e instanceof Tt}function sx(e){return Array.isArray(e)}function qI(e){return!Rte(e)&&!sx(e)}function KI(e,t,n,a=!0,r=""){if(t==null||t.length===0){if(e!=null){let i=!1;if(sx(e)&&e.length>0)i=!0;else if(qI(e)){for(let o in e)if(e.hasOwnProperty(o)){i=!0;break}}else i=!0;if(i)throw new G(`Error when checking model ${r} expected no data, but got ${e}`)}return[]}if(e==null)return t.map(i=>null);let s;if(qI(e)){e=e,s=[];for(let i of t){if(e[i]==null)throw new G(`No data provided for "${i}". Need data for each key in: ${t}`);s.push(e[i])}}else if(sx(e)){if(e=e,e.length!==t.length)throw new G(`Error when checking model ${r}: the Array of Tensors that you are passing to your model is not the size the model expected. Expected to see ${t.length} Tensor(s), but instead got the following list of Tensor(s): ${e}`);s=e}else{if(e=e,t.length>1)throw new G(`The model ${r} expects ${t.length} Tensor(s), but only received one Tensor. Found: Tensor with shape ${e.shape}`);s=[e]}if(s=GI(s),n!=null)for(let i=0;i=0&&u!==d)throw new G(`Error when checking ${r}: expected ${t[i]} to have shape [${n[i]}], but got array with shape [${o.shape}].`)}}return s}function Fte(e,t,n){let a=Hs(e.map(s=>s.shape[0]));a.sort();let r=Hs(t.map(s=>s.shape[0]));if(r.sort(),a.length>1)throw new G(`All input Tensors (x) should have the same number of samples. Got array shapes: ${JSON.stringify(e.map(s=>s.shape))}`);if(r.length>1)throw new G(`All target Tensors (y) should have the same number of samples. Got array shapes: ${JSON.stringify(t.map(s=>s.shape))}`);if(a.length>0&&r.length>0&&!k.arraysEqual(a,r))throw new G(`Input Tensors should have the same number of samples as target Tensors. Found ${a[0]} input sample(s) and ${r[0]} target sample(s).`)}function Ote(e,t,n){let a=[lo,l0,Vh];for(let r=0;r1)throw new G(`The model expects ${t.length} ${r} Tensors, but only received one Tensor. Found: array with shape ${JSON.stringify(e.shape)}.`);s=[e]}if(n!=null)for(let i=0;i[]);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(a=>n);{let a=[];for(let r of t){let s=n.hasOwnProperty(r)?n[r]:[];Array.isArray(s)||(s=[s]),a.push(s)}return a}}var _te="layers-model",ps=class extends Dr{constructor(e){super(e);this.isTraining=!1}summary(e,t,n=console.log){if(!this.built)throw new G("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).");cte(this,e,t,n)}compile(e){if(e.loss==null&&(e.loss=[]),this.loss=e.loss,typeof e.optimizer=="string")this.optimizer_=pte(e.optimizer),this.isOptimizerOwned=!0;else{if(!(e.optimizer instanceof js))throw new G("User-defined optimizer must be an instance of tf.Optimizer.");this.optimizer_=e.optimizer,this.isOptimizerOwned=!1}let t=[];if(!Array.isArray(e.loss)&&typeof e.loss!="string"&&typeof e.loss!="function"){e.loss=e.loss;for(let s in e.loss)if(this.outputNames.indexOf(s)===-1)throw new G(`Unknown entry in loss dictionary: "${s}". Only expected the following keys: ${this.outputNames}`);for(let s of this.outputNames)e.loss[s]==null&&console.warn(`Output "${s}" is missing from loss dictionary. We assume this was done on purpose, and we will not be expecting data to be passed to ${s} during training`),t.push(K2(e.loss[s]))}else if(Array.isArray(e.loss)){if(e.loss.length!==this.outputs.length)throw new G(`When passing an Array as loss, it should have one entry per model output. The model has ${this.outputs.length} output(s), but you passed loss=${e.loss}.`);t=e.loss.map(s=>K2(s))}else{let s=K2(e.loss);this.outputs.forEach(i=>{t.push(s)})}this.lossFunctions=t,this.feedOutputNames=[],this.feedOutputShapes=[],this.feedLossFns=[];for(let s=0;s{for(let s=0;s1&&(this.metricsTensors.push([i,s]),this.metricsNames.push(this.outputNames[s]+"_loss"))}});let a=Dte(e.metrics,this.outputNames),r=(s,i,o)=>{this.outputNames.length>1&&(i=this.outputNames[s]+"_"+i),this.metricsNames.push(i),this.metricsTensors.push([o,s])};io("metric",()=>{for(let s=0;s{let l="",u,d,h;for(let p of o){if(typeof p=="string"&&["accuracy","acc","crossentropy","ce"].indexOf(p)!==-1){let m=this.internalOutputShapes[s];m[m.length-1]===1||this.lossFunctions[s]===l0?["accuracy","acc"].indexOf(p)!==-1?d=X2:["crossentropy","ce"].indexOf(p)!==-1&&(d=FI):this.lossFunctions[s]===o0?["accuracy","acc"].indexOf(p)!==-1?d=OI:["crossentropy","ce"].indexOf(p)!==-1&&(d=DI):["accuracy","acc"].indexOf(p)!==-1?d=Z2:["crossentropy","ce"].indexOf(p)!==-1&&(d=Y2);let f;["accuracy","acc"].indexOf(p)!==-1?f="acc":["crossentropy","ce"].indexOf(p)!==-1&&(f="ce"),h=d,u=l+f}else h=hte(p),u=l+h0(p);let c;io(u,()=>{c=h}),r(s,u,c)}})(i)}}),this.collectedTrainableWeights=this.trainableWeights}checkTrainableWeightsConsistency(){this.collectedTrainableWeights!=null&&this.trainableWeights.length!==this.collectedTrainableWeights.length&&console.warn("Discrepancy between trainableweights and collected trainable weights. Did you set `model.trainable` without calling `model.compile()` afterwards?")}evaluate(e,t,n={}){let a=n.batchSize==null?32:n.batchSize;nx(a);let r=!0,s=this.standardizeUserDataXY(e,t,r,a);try{let i=s[0].concat(s[1]);this.makeTestFunction();let o=this.testFunction,l=this.testLoop(o,i,a,n.verbose,n.steps);return Qn(l)}finally{ho(s[0],e),ho(s[1],t)}}async evaluateDataset(e,t){return this.makeTestFunction(),Cte(this,e,t)}checkNumSamples(e,t,n,a="steps"){let r;if(n!=null){if(r=null,t!=null)throw new G(`If ${a} is set, batchSize must be null or undefined.Got batchSize = ${t}`)}else if(e!=null)Array.isArray(e)?r=e[0].shape[0]:r=e.shape[0];else throw new G(`Either the input data should have a defined shape, or ${a} shoud be specified.`);return r}execute(e,t){if(Array.isArray(t)&&t.length===0)throw new G("`outputs` is an empty Array, which is not allowed.");let n=Array.isArray(t),a=n?t:[t],r=this.retrieveSymbolicTensors(a),s=new uo;if(e instanceof Tt&&(e=[e]),Array.isArray(e)){if(e.length!==this.inputs.length)throw new G(`The number of inputs provided (${e.length}) does not match the number of inputs of this model (${this.inputs.length}).`);for(let o=0;oi.name);for(let i=0;i0){let a=[];throw t.forEach((r,s)=>{r==null&&a.push(e[s])}),new G(`Cannot find SymbolicTensors for output name(s): ${JSON.stringify(a)}`)}return t}predictLoop(e,t=32,n=!1){return Z(()=>{let a=this.checkNumSamples(e);if(n)throw new He("Verbose predictLoop() is not implemented yet.");let r=rx(a,t),s=this.outputs.map(i=>[]);for(let i=0;i{let o=r[i][0],l=r[i][1],u=Hh(e,o,l),d=[];if(Array.isArray(u))for(let p=0;ps[l].push(o));return Qn(s.map(i=>en(i,0)))})}predict(e,t={}){let n=GI(e);XI(n,this.inputNames,this.feedInputShapes,!1);try{let a=t.batchSize==null?32:t.batchSize;return nx(a),this.predictLoop(n,a)}finally{ho(n,e)}}predictOnBatch(e){XI(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,a){if(this.optimizer_==null)throw new ur("You must compile a model before training/testing. Use LayersModel.compile(modelCompileArgs).");let r=[];for(let s=0;s0&&e[0].shape[0]%a!=0)throw new G(`In a stateful network, you should only pass inputs with a number of samples that is divisible by the batch size ${a}. Found: ${e[0].shape[0]} sample(s).`);return[e,t]}async standardizeUserData(e,t,n,a,r=!0,s){let[i,o]=this.standardizeUserDataXY(e,t,r,s);if(n!=null)throw new Error("sample weight is not supported yet.");let l=null;if(a!=null){let u=BI(a,this.outputNames);l=[];for(let d=0;d{let s=this.checkNumSamples(t,n,r,"steps"),i=[];if(a>0)throw new He("Verbose mode is not implemented yet.");if(r!=null)throw new He("steps mode in testLoop() is not implemented yet");{let o=rx(s,n),l=$n(dr(0,s));for(let u=0;u1&&(r+=`_${nI(e.slice(0,n),a)}`),t.push(r)}return t}makeTrainFunction(){return e=>{let t=[],n=e.slice(0,this.inputs.length),a=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),r=e.slice(this.inputs.length+this.outputs.length,this.inputs.length+this.outputs.length*2),s=[],i=()=>{let u=[];for(let c=0;c1&&c{p=pe(p,c)}),p},o=this.collectedTrainableWeights.map(u=>u.read()),l=!0;return[this.optimizer_.minimize(i,l,o)].concat(s)}}makeTestFunction(){this.testFunction=e=>Z(()=>{let t=[],n,a=e.slice(0,this.inputs.length),r=e.slice(this.inputs.length,this.inputs.length+this.outputs.length),s=[];for(let l=0;lhs(t))}else{let t=Object.keys(this.loss);e={};let n=this.loss;for(let a of t)if(typeof n[a]=="string")e[a]=hs(n[a]);else throw new Error("Serialization of non-string loss is not supported.")}return e}getMetricIdentifiers(){if(typeof this.metrics=="string"||typeof this.metrics=="function")return[hs(h0(this.metrics))];if(Array.isArray(this.metrics))return this.metrics.map(e=>hs(h0(e)));{let e={};for(let t in this.metrics)e[t]=hs(h0(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=Uh(e.optimizer_config),n=cr(t),a;if(typeof e.loss=="string")a=ro(e.loss);else if(Array.isArray(e.loss))a=e.loss.map(s=>ro(s));else if(e.loss!=null){a={};for(let s in e.loss)a[s]=ro(e.loss[s])}let r;if(Array.isArray(e.metrics))r=e.metrics.map(s=>ro(s));else if(e.metrics!=null){r={};for(let s in e.metrics)r[s]=ro(e.metrics[s])}this.compile({loss:a,metrics:r,optimizer:n})}async save(e,t){if(typeof e=="string"){let i=la.getSaveHandlers(e);if(i.length===0)throw new G(`Cannot find any save handlers for URL '${e}'`);if(i.length>1)throw new G(`Found more than one (${i.length}) save handlers for URL '${e}'`);e=i[0]}if(e.save==null)throw new G("LayersModel.save() cannot proceed because the IOHandler provided does not have the `save` attribute defined.");let n=await la.encodeWeights(this.getNamedWeights(t)),a=!1,r=null,s={modelTopology:this.toJSON(r,a),format:_te,generatedBy:`TensorFlow.js tfjs-layers v${ex}`,convertedBy:null};if((t==null?!1:t.includeOptimizer)&&this.optimizer!=null){s.trainingConfig=this.getTrainingConfig();let i="optimizer",{data:o,specs:l}=await la.encodeWeights(await this.optimizer.getWeights(),i);n.specs.push(...l),n.data=la.concatenateArrayBuffers([n.data,o])}if(this.userDefinedMetadata!=null){let i=!0;zI(this.userDefinedMetadata,this.name,i),s.userDefinedMetadata=this.userDefinedMetadata}return s.weightData=n.data,s.weightSpecs=n.specs,e.save(s)}setUserDefinedMetadata(e){zI(e,this.name),this.userDefinedMetadata=e}getUserDefinedMetadata(){return this.userDefinedMetadata}};ps.className="Model";ue.registerClass(ps);var ZI=class extends ps{};ZI.className="Functional";ue.registerClass(ZI);async function zte(e,t){"modelTopology"in e||(e={modelTopology:e}),e=e;let n=e.modelTopology;n.model_config!=null&&(n=n.model_config);let a=Uh(n),r=cr(a,t);if(e.weightsManifest!=null){let s=await la.loadWeights(e.weightsManifest,e.pathPrefix,r.weights.map(o=>o.originalName)),i={};for(let o of r.weights)i[o.originalName]=s[o.originalName];r.loadWeights(i),Ge(s)}return r}async function Pte(e,t){if(t==null&&(t={}),typeof e=="string"){let n=la.getLoadHandlers(e,t);if(n.length===0)n.push(la.browserHTTPRequest(e,t));else if(n.length>1)throw new G(`Found more than one (${n.length}) load handlers for URL '${e}'`);e=n[0]}return Lte(e,void 0,t)}async function Lte(e,t,n){if(n==null&&(n={}),e.load==null)throw new G("Cannot proceed with model loading because the IOHandler provided does not have the `load` method implemented.");let a=await e.load(),r=a.modelTopology;r.model_config!=null&&(r=r.model_config);let s=n.strict==null?!0:n.strict,i=a.weightData!=null&&a.weightSpecs!=null&&s,o=cr(Uh(r),t,i),l=a.trainingConfig;if(l!=null&&o.loadTrainingConfig(l),a.userDefinedMetadata!=null&&o.setUserDefinedMetadata(a.userDefinedMetadata),a.weightData!=null){if(a.weightSpecs==null)throw new G("LayersModel artifacts contains weight data, but not weight specs. Therefore loading of weights cannot proceed.");let{modelWeights:u,optimizerWeights:d}=Wte(a.weightData,a.weightSpecs);o.loadWeights(u,s),o.optimizer!=null&&d.length>0&&await o.optimizer.setWeights(d),Ge(u),Ge(d.map(h=>h.tensor))}return o}function Wte(e,t){let n=la.decodeWeights(e,t),a={},r=[];return t.forEach(s=>{s.group==="optimizer"?r.push({name:s.name,tensor:n[s.name]}):a[s.name]=n[s.name]}),{modelWeights:a,optimizerWeights:r}}var ix=class extends ps{constructor(e){super({inputs:[],outputs:[]});if(e=e||{},this.trainable=!0,this.built=!1,this.name=e.name!=null?e.name:t0("sequential_"),e.layers!=null)for(let t of e.layers)this.add(t)}checkShape(e){if(e.inboundNodes[0].outputTensors[0].shape.some(t=>t<0))throw new G(`Negative dimension size caused by adding layer ${e.name} with input shape [${e.inboundNodes[0].inputTensors[0].shape}]`)}add(e){let t=e instanceof ix||e instanceof ps,n;if(t){if(n=e,n.outputs.length!==1)throw new G("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 G("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 G("The first layer in a Sequential model must get an `inputShape` or `batchInputShape` argument.");let a=kI({batchShape:e.batchInputShape,dtype:e.dtype,name:e.name+"_input"});e.apply(a)}if(t)this.outputs=n.outputs,this.inputs=n.inputs;else{if(e.inboundNodes.length!==1)throw new G(`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 G("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=wI(this.outputs[0])}this.inboundNodes=[],new r0({outboundLayer:this,inboundLayers:[],nodeIndices:[],tensorIndices:[],inputTensors:this.inputs,outputTensors:this.outputs,inputMasks:ao(null,this.inputs.length),outputMasks:[null],inputShapes:this.inputs.map(a=>a.shape),outputShapes:this.outputs[0].shape})}else{let a=e.apply(this.outputs[0]);if(Array.isArray(a))throw new TypeError("All layers in a Sequential model should have a single output tensor. For multi-output layers, use the functional API.");this.checkShape(e),this.outputs=[a],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}this.layers.push(e),this.built=!1}pop(){if(this.layers.length===0)throw new TypeError("There are no layers in the model.");if(this.layers.pop(),this.layers.length===0)this.outputs=[],this.inboundNodes=[],this.outboundNodes=[];else{let e=this.layers.length-1;this.layers[e].outboundNodes=[],this.outputs=[this.layers[e].output],this.inboundNodes[0].outputTensors=this.outputs,this.inboundNodes[0].outputShapes=[this.outputs[0].shape]}}call(e,t){return this.model==null&&this.build(),this.model.call(e,t)}build(e){if(At(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 ps({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 ur("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 ur("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 ur("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 ur("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={},a=!1){let r,s={};if(t instanceof Array){if(t[0].className==null||t[0].className==="Merge")throw new G("Legacy serialization format not supported yet.");r=t}else k.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."),r=t.layers,delete t.layers,s=t;let i=new e(s);if(!(i instanceof ix))throw new He(`Sequential.fromConfig called on non-Sequential input: ${i}`);for(let o of r){let l=cr(o,void 0,a);a&&l.setFastWeightInitDuringBuild(!0),i.add(l)}return i}set stopTraining(e){if(this.model==null)throw new G("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 G("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}}},c0=ix;c0.className="Sequential";ue.registerClass(c0);function Bte(e){return new ps(e)}function Vte(e){return new c0(e)}function Ute(e,t){return t==null&&(t={}),Pte(e,t)}function YI(e){return kI(e)}function jte(e,t){G2.registerCallbackConstructor(e,t)}var ta=class extends ue.Serializable{getConfig(){return{}}},JI=class extends ta{apply(e,t=1){return gee(e,t)}};JI.className="elu";ue.registerClass(JI);var QI=class extends ta{apply(e){return e2(e)}};QI.className="selu";ue.registerClass(QI);var eS=class extends ta{apply(e){return ls(e)}};eS.className="relu";ue.registerClass(eS);var tS=class extends ta{apply(e){return Z(()=>$h(6,ls(e)))}};tS.className="relu6";ue.registerClass(tS);var nS=class extends ta{apply(e){return e}};nS.className="linear";ue.registerClass(nS);var aS=class extends ta{apply(e){return $r(e)}};aS.className="sigmoid";ue.registerClass(aS);var rS=class extends ta{apply(e){return Aee(e)}};rS.className="hardSigmoid";ue.registerClass(rS);var sS=class extends ta{apply(e){return Zl(e)}};sS.className="softplus";ue.registerClass(sS);var iS=class extends ta{apply(e){return yee(e)}};iS.className="softsign";ue.registerClass(iS);var oS=class extends ta{apply(e){return Kl(e)}};oS.className="tanh";ue.registerClass(oS);var ox=class extends ta{apply(e,t=-1){return _f(e,t)}};ox.className="softmax";ue.registerClass(ox);var lS=class extends ta{apply(e,t=-1){return UA(e,t)}};lS.className="logSoftmax";ue.registerClass(lS);var uS=class extends ta{apply(e,t=1){return Z(()=>$r(e.mul(t)).mul(e))}};uS.className="swish";ue.registerClass(uS);var dS=class extends ta{apply(e){return Z(()=>K(e,Kl(Zl(e))))}};dS.className="mish";ue.registerClass(dS);function Xs(e){return e.getClassName()}function lx(e,t={}){return Dh(e,ue.SerializationMap.getMap().classNameMap,t,"activation")}function Zs(e){if(e==null){let t={};return t.className="linear",t.config={},lx(t)}if(typeof e=="string"){let t={};return t.className=e,t.config={},lx(t)}else return e instanceof ta?e:lx(e)}function ux(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 hS=class extends ue.Serializable{},Gh=class extends hS{constructor(e){super();ux(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 Z(()=>{let t=un([1]);return this.hasL1&&(t=pe(t,Ce(K(this.l1,yn(e))))),this.hasL2&&(t=pe(t,Ce(K(this.l2,Wh(e))))),t.asScalar()})}getConfig(){return{l1:this.l1,l2:this.l2}}static fromConfig(e,t){return new e({l1:t.l1,l2:t.l2})}};Gh.className="L1L2";ue.registerClass(Gh);function Hte(e){return ux(e),new Gh({l1:e!=null?e.l1:null,l2:0})}function Gte(e){return ux(e),new Gh({l2:e!=null?e.l2:null,l1:0})}var pS={l1l2:"L1L2"};function wt(e){return I2(e)}function cS(e,t={}){return Dh(e,ue.SerializationMap.getMap().classNameMap,t,"regularizer")}function Lt(e){if(e==null)return null;if(typeof e=="string"){let t={className:e in pS?pS[e]:e,config:{}};return cS(t)}else return e instanceof hS?e:cS(e)}var dx=class extends rt{constructor(e){super(e==null?{}:e);this.supportsMasking=!0,e!=null&&(this.maxValue=e.maxValue)}call(e,t){e=Ke(e);let n=ls(e);return this.maxValue!=null&&(n=ua(n,0,this.maxValue)),n}computeOutputShape(e){return e}getConfig(){let e={maxValue:this.maxValue},t=super.getConfig();return Object.assign(e,t),e}};dx.className="ReLU";ue.registerClass(dx);var hx=class extends rt{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=Ke(e);return Ef(n,this.alpha)}computeOutputShape(e){return e}getConfig(){let e={alpha:this.alpha},t=super.getConfig();return Object.assign(e,t),e}};hx.className="LeakyReLU";ue.registerClass(hx);var px=class extends rt{constructor(e){super(e==null?{}:e);if(this.DEFAULT_ALPHA_INITIALIZER="zeros",e==null&&(e={}),this.supportsMasking=!0,this.alphaInitializer=Pt(e.alphaInitializer||this.DEFAULT_ALPHA_INITIALIZER),this.alphaRegularizer=Lt(e.alphaRegularizer),this.alphaConstraint=pn(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 G(`Expected sharedAxes to be a number or an array of numbers, but got ${e.sharedAxes}`)}build(e){e=At(e);let t=e.slice(1);if(this.sharedAxes!=null)for(let a of this.sharedAxes)t[a-1]=1;this.alpha=this.addWeight("alpha",t,"float32",this.alphaInitializer,this.alphaRegularizer,!0,this.alphaConstraint);let n={};if(this.sharedAxes!=null)for(let a=1;a(Yt(t),t==="channelsFirst"?ct(e,[0,2,3,1]):e))}function fS(e,t){return Z(()=>(Yt(t),t==="channelsFirst"?ct(e,[0,2,3,4,1]):e))}function qte(e,t,n,a=1,r="valid",s,i=1){return Z(()=>{if(s==null&&(s=lr()),Yt(s),e.shape.length!==3)throw new G(`The input of a conv1dWithBias operation should be 3, but is ${e.shape.length} instead.`);if(t.shape.length!==3)throw new G(`The kernel for a conv1dWithBias operation should be 3, but is ${t.shape.length} instead`);if(n!=null&&n.shape.length!==1)throw new G(`The bias for a conv1dWithBias operation should be 1, but is ${t.shape.length} instead`);if(s==="channelsFirst"&&(e=ct(e,[0,2,1])),r==="causal")throw new He("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");let o=DA(e,t,a,r==="same"?"same":"valid","NWC",i);return n!=null&&(o=hr(o,n)),o})}function mS(e,t,n,a=[1,1],r="valid",s,i,o=null){return Z(()=>{if(s==null&&(s=lr()),Yt(s),e.rank!==3&&e.rank!==4)throw new G(`conv2dWithBiasActivation expects input to be of rank 3 or 4, but received ${e.rank}.`);if(t.rank!==3&&t.rank!==4)throw new G(`conv2dWithBiasActivation expects kernel to be of rank 3 or 4, but received ${e.rank}.`);let l=gx(e,s);if(r==="causal")throw new He("The support for CAUSAL padding mode in conv1dWithBias is not implemented yet.");return l=eo.conv2d({x:l,filter:t,strides:a,pad:r==="same"?"same":"valid",dilations:i,dataFormat:"NHWC",bias:n,activation:o}),s==="channelsFirst"&&(l=ct(l,[0,3,1,2])),l})}function Kte(e,t,n,a=[1,1,1],r="valid",s,i){return Z(()=>{if(s==null&&(s=lr()),Yt(s),e.rank!==4&&e.rank!==5)throw new G(`conv3dWithBias expects input to be of rank 4 or 5, but received ${e.rank}.`);if(t.rank!==4&&t.rank!==5)throw new G(`conv3dWithBias expects kernel to be of rank 4 or 5, but received ${e.rank}.`);let o=fS(e,s);if(r==="causal")throw new He("The support for CAUSAL padding mode in conv3dWithBias is not implemented yet.");return o=n8(o,t,a,r==="same"?"same":"valid","NDHWC",i),n!=null&&(o=hr(o,n)),s==="channelsFirst"&&(o=ct(o,[0,4,1,2,3])),o})}var yx=class extends rt{constructor(e,t){super(t);if(this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",yx.verifyArgs(t),this.rank=e,An(this.rank,"rank"),this.rank!==1&&this.rank!==2&&this.rank!==3)throw new He(`Convolution layer for rank other than 1, 2, or 3 (${this.rank}) is not implemented yet.`);if(this.kernelSize=ou(t.kernelSize,e,"kernelSize"),this.strides=ou(t.strides==null?1:t.strides,e,"strides"),this.padding=t.padding==null?"valid":t.padding,Oa(this.padding),this.dataFormat=t.dataFormat==null?"channelsLast":t.dataFormat,Yt(this.dataFormat),this.activation=Zs(t.activation),this.useBias=t.useBias==null?!0:t.useBias,this.biasInitializer=Pt(t.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.biasConstraint=pn(t.biasConstraint),this.biasRegularizer=Lt(t.biasRegularizer),this.activityRegularizer=Lt(t.activityRegularizer),this.dilationRate=ou(t.dilationRate==null?1:t.dilationRate,e,"dilationRate"),this.rank===1&&Array.isArray(this.dilationRate)&&this.dilationRate.length!==1)throw new G(`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 G(`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 G(`dilationRate must be a number or array of three numbers for 3D convolution, but received ${JSON.stringify(this.dilationRate)}`)}}static verifyArgs(e){if(Rr("kernelSize"in e,"required key 'kernelSize' not in config"),typeof e.kernelSize!="number"&&!N2(e.kernelSize,"number",1,3))throw new G(`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:Xs(this.activation),useBias:this.useBias,biasInitializer:jt(this.biasInitializer),biasRegularizer:wt(this.biasRegularizer),activityRegularizer:wt(this.activityRegularizer),biasConstraint:hn(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}},qh=class extends yx{constructor(e,t){super(e,t);this.kernel=null,qh.verifyArgs(t),this.filters=t.filters,An(this.filters,"filters"),this.kernelInitializer=Pt(t.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.kernelConstraint=pn(t.kernelConstraint),this.kernelRegularizer=Lt(t.kernelRegularizer)}build(e){e=At(e);let t=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[t]==null)throw new G(`The channel dimension of the input should be defined. Found ${e[t]}`);let n=e[t],a=this.kernelSize.concat([n,this.filters]);this.kernel=this.addWeight("kernel",a,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],null,this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[{ndim:this.rank+2,axes:{[t]:n}}],this.built=!0}call(e,t){return Z(()=>{e=Ke(e);let n,a=this.bias==null?null:this.bias.read(),r=rI(this.activation.getClassName());if(r!=null&&this.rank===2)n=mS(e,this.kernel.read(),a,this.strides,this.padding,this.dataFormat,this.dilationRate,r);else{if(this.rank===1)n=qte(e,this.kernel.read(),a,this.strides[0],this.padding,this.dataFormat,this.dilationRate[0]);else if(this.rank===2)n=mS(e,this.kernel.read(),a,this.strides,this.padding,this.dataFormat,this.dilationRate);else if(this.rank===3)n=Kte(e,this.kernel.read(),a,this.strides,this.padding,this.dataFormat,this.dilationRate);else throw new He("convolutions greater than 3D are not implemented yet.");this.activation!=null&&(n=this.activation.apply(n))}return n})}computeOutputShape(e){e=At(e);let t=[],n=this.dataFormat==="channelsLast"?e.slice(1,e.length-1):e.slice(2);for(let r=0;r 0 but got ${JSON.stringify(e.filters)}`)}},gS=class extends qh{constructor(e){super(2,e);gS.verifyArgs(e)}getConfig(){let e=super.getConfig();return delete e.rank,e}static verifyArgs(e){if(typeof e.kernelSize!="number"&&!N2(e.kernelSize,"number",1,2))throw new G(`Conv2D expects config.kernelSize to be number or number[] with length 1 or 2, but received ${JSON.stringify(e.kernelSize)}.`)}},f0=gS;f0.className="Conv2D";ue.registerClass(f0);var yS=class extends qh{constructor(e){super(3,e);yS.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 G(`Conv3D expects config.kernelSize to be number or [number, number, number], but received ${JSON.stringify(e.kernelSize)}.`)}},m0=yS;m0.className="Conv3D";ue.registerClass(m0);var Ax=class extends f0{constructor(e){super(e);if(this.inputSpec=[new tn({ndim:4})],this.padding!=="same"&&this.padding!=="valid")throw new G(`Conv2DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=At(e),e.length!==4)throw new G("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 G("The channel dimension of the inputs should be defined. Found `None`.");let n=e[t],a=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",a,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new tn({ndim:4,axes:{[t]:n}})],this.built=!0}call(e,t){return Z(()=>{let n=Ke(e);if(n.shape.length!==4)throw new G(`Conv2DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);let a=n.shape,r=a[0],s,i;this.dataFormat==="channelsFirst"?(s=2,i=3):(s=1,i=2);let o=a[s],l=a[i],u=this.kernelSize[0],d=this.kernelSize[1],h=this.strides[0],p=this.strides[1],c=_r(o,h,u,this.padding),m=_r(l,p,d,this.padding),f=[r,c,m,this.filters];this.dataFormat!=="channelsLast"&&(n=ct(n,[0,2,3,1]));let g=zA(n,this.kernel.read(),f,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(g=ct(g,[0,3,1,2])),this.bias!=null&&(g=hr(g,this.bias.read(),this.dataFormat)),this.activation!=null&&(g=this.activation.apply(g)),g})}computeOutputShape(e){e=At(e);let t=e.slice(),n,a,r;this.dataFormat==="channelsFirst"?(n=1,a=2,r=3):(n=3,a=1,r=2);let s=this.kernelSize[0],i=this.kernelSize[1],o=this.strides[0],l=this.strides[1];return t[n]=this.filters,t[a]=_r(t[a],o,s,this.padding),t[r]=_r(t[r],l,i,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};Ax.className="Conv2DTranspose";ue.registerClass(Ax);var xx=class extends m0{constructor(e){super(e);if(this.inputSpec=[new tn({ndim:5})],this.padding!=="same"&&this.padding!=="valid")throw new G(`Conv3DTranspose currently supports only padding modes 'same' and 'valid', but received padding mode ${this.padding}`)}build(e){if(e=At(e),e.length!==5)throw new G("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 G("The channel dimension of the inputs should be defined. Found `None`.");let n=e[t],a=this.kernelSize.concat([this.filters,n]);this.kernel=this.addWeight("kernel",a,"float32",this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint),this.useBias&&(this.bias=this.addWeight("bias",[this.filters],"float32",this.biasInitializer,this.biasRegularizer,!0,this.biasConstraint)),this.inputSpec=[new tn({ndim:5,axes:{[t]:n}})],this.built=!0}call(e,t){return Z(()=>{let n=Ke(e);if(n.shape.length!==5)throw new G(`Conv3DTranspose.call() expects input tensor to be rank-4, but received a tensor of rank-${n.shape.length}`);let a=n.shape,r=a[0],s,i,o;this.dataFormat==="channelsFirst"?(o=2,s=3,i=4):(o=1,s=2,i=3);let l=a[o],u=a[s],d=a[i],h=this.kernelSize[0],p=this.kernelSize[1],c=this.kernelSize[2],m=this.strides[0],f=this.strides[1],g=this.strides[2],y=_r(l,m,h,this.padding),A=_r(u,f,p,this.padding),x=_r(d,g,c,this.padding),v=[r,y,A,x,this.filters];this.dataFormat!=="channelsLast"&&(n=ct(n,[0,2,3,4,1]));let b=ZG(n,this.kernel.read(),v,this.strides,this.padding);return this.dataFormat!=="channelsLast"&&(b=ct(b,[0,4,1,2,3])),this.bias!==null&&(b=hr(b,this.bias.read(),this.dataFormat)),this.activation!==null&&(b=this.activation.apply(b)),b})}computeOutputShape(e){e=At(e);let t=e.slice(),n,a,r,s;this.dataFormat==="channelsFirst"?(n=1,a=2,r=3,s=4):(n=4,a=1,r=2,s=3);let i=this.kernelSize[0],o=this.kernelSize[1],l=this.kernelSize[2],u=this.strides[0],d=this.strides[1],h=this.strides[2];return t[n]=this.filters,t[a]=_r(t[a],u,i,this.padding),t[r]=_r(t[r],d,o,this.padding),t[s]=_r(t[s],h,l,this.padding),t}getConfig(){let e=super.getConfig();return delete e.dilationRate,e}};xx.className="Conv3DTranspose";ue.registerClass(xx);var AS=class extends qh{constructor(e,t){super(e,t);if(this.DEFAULT_DEPTHWISE_INITIALIZER="glorotUniform",this.DEFAULT_POINTWISE_INITIALIZER="glorotUniform",this.depthwiseKernel=null,this.pointwiseKernel=null,t.filters==null)throw new G("The `filters` configuration field is required by SeparableConv, but is unspecified.");if(t.kernelInitializer!=null||t.kernelRegularizer!=null||t.kernelConstraint!=null)throw new G("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 G(`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=Pt(t.depthwiseInitializer||this.DEFAULT_DEPTHWISE_INITIALIZER),this.depthwiseRegularizer=Lt(t.depthwiseRegularizer),this.depthwiseConstraint=pn(t.depthwiseConstraint),this.pointwiseInitializer=Pt(t.depthwiseInitializer||this.DEFAULT_POINTWISE_INITIALIZER),this.pointwiseRegularizer=Lt(t.pointwiseRegularizer),this.pointwiseConstraint=pn(t.pointwiseConstraint)}build(e){if(e=At(e),e.length{e=Ke(e);let n;if(this.rank===1)throw new He("1D separable convolution is not implemented yet.");return this.rank===2&&(this.dataFormat==="channelsFirst"&&(e=ct(e,[0,2,3,1])),n=b8(e,this.depthwiseKernel.read(),this.pointwiseKernel.read(),this.strides,this.padding,this.dilationRate,"NHWC")),this.useBias&&(n=hr(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),this.dataFormat==="channelsFirst"&&(n=ct(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=jt(this.depthwiseInitializer),e.pointwiseInitializer=jt(this.pointwiseInitializer),e.depthwiseRegularizer=wt(this.depthwiseRegularizer),e.pointwiseRegularizer=wt(this.pointwiseRegularizer),e.depthwiseConstraint=hn(this.depthwiseConstraint),e.pointwiseConstraint=hn(this.pointwiseConstraint),e}};AS.className="SeparableConv";var bx=class extends AS{constructor(e){super(2,e)}};bx.className="SeparableConv2D";ue.registerClass(bx);var xS=class extends qh{constructor(e){super(1,e);xS.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"&&!N2(e.kernelSize,"number",1,1))throw new G(`Conv1D expects config.kernelSize to be number or number[] with length 1, but received ${JSON.stringify(e.kernelSize)}.`)}},vx=xS;vx.className="Conv1D";ue.registerClass(vx);var wx=class extends rt{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 Z(()=>{if(e=Ke(e),this.dataFormat==="channelsLast"){let n=Hf(e,this.cropping[0][0],e.shape[1]-this.cropping[0][0]-this.cropping[0][1],2);return Hf(n,this.cropping[1][0],e.shape[2]-this.cropping[1][1]-this.cropping[1][0],3)}else{let n=Hf(e,this.cropping[0][0],e.shape[2]-this.cropping[0][0]-this.cropping[0][1],3);return Hf(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}};wx.className="Cropping2D";ue.registerClass(wx);var kx=class extends rt{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,Yt(this.dataFormat),this.interpolation=e.interpolation==null?"nearest":e.interpolation,uee(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 Z(()=>{let n=Ke(e),a=n.shape;if(this.dataFormat==="channelsFirst"){n=ct(n,[0,2,3,1]);let r=this.size[0]*a[2],s=this.size[1]*a[3],i=this.interpolation==="nearest"?n.resizeNearestNeighbor([r,s]):n.resizeBilinear([r,s]);return ct(i,[0,3,1,2])}else{let r=this.size[0]*a[1],s=this.size[1]*a[2];return this.interpolation==="nearest"?n.resizeNearestNeighbor([r,s]):n.resizeBilinear([r,s])}})}getConfig(){let e={size:this.size,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};kx.className="UpSampling2D";ue.registerClass(kx);function Xte(e,t,n=[1,1],a="valid",r,s){return Z(()=>{r==null&&(r=lr()),Yt(r);let i=gx(e,r);if(e.rank!==4)throw new G(`Input for depthwiseConv2d is required to be 4-D, but is instead ${e.rank}-D`);if(t.rank!==4)throw new G(`depthwiseKernel is required to be 4-D, but is instead ${t.rank}-D`);return i=Nh(i,t,n,a==="same"?"same":"valid","NHWC",s),r==="channelsFirst"&&(i=ct(i,[0,3,1,2])),i})}var Ix=class extends yx{constructor(e){super(2,e);this.depthwiseKernel=null,this.depthMultiplier=e.depthMultiplier==null?1:e.depthMultiplier,this.depthwiseInitializer=Pt(e.depthwiseInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.depthwiseConstraint=pn(e.depthwiseConstraint),this.depthwiseRegularizer=Lt(e.depthwiseRegularizer)}build(e){if(e=At(e),e.length<4)throw new G(`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 G(`The channel dimension of the inputs to DepthwiseConv2D should be defined, but is not (${e[t]}).`);let n=e[t],a=[this.kernelSize[0],this.kernelSize[1],n,this.depthMultiplier];this.depthwiseKernel=this.addWeight("depthwise_kernel",a,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 Z(()=>{e=Ke(e);let n=Xte(e,this.depthwiseKernel.read(),this.strides,this.padding,this.dataFormat,null);return this.useBias&&(n=hr(n,this.bias.read(),this.dataFormat)),this.activation!=null&&(n=this.activation.apply(n)),n})}computeOutputShape(e){e=At(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],a=this.dataFormat==="channelsFirst"?e[1]*this.depthMultiplier:e[3]*this.depthMultiplier,r=fr(t,this.kernelSize[0],this.padding,this.strides[0]),s=fr(n,this.kernelSize[1],this.padding,this.strides[1]);return this.dataFormat==="channelsFirst"?[e[0],a,r,s]:[e[0],r,s,a]}getConfig(){let e=super.getConfig();return e.depthMultiplier=this.depthMultiplier,e.depthwiseInitializer=jt(this.depthwiseInitializer),e.depthwiseRegularizer=wt(this.depthwiseRegularizer),e.depthwiseConstraint=hn(this.depthwiseRegularizer),e}};Ix.className="DepthwiseConv2D";ue.registerClass(Ix);function bS(e,t,n,a){if(Array.isArray(e)){if(t!=null||n!=null)throw new G("When inputs is an array, neither initialState or constants should be provided");a!=null&&(n=e.slice(e.length-a,e.length),e=e.slice(0,e.length-a)),e.length>1&&(t=e.slice(1,e.length)),e=e[0]}function r(s){return s==null||Array.isArray(s)?s:[s]}return t=r(t),n=r(n),{inputs:e,initialState:t,constants:n}}function vS(e,t,n,a=!1,r,s,i=!1,o=!1){return Z(()=>{let l=t.shape.length;if(l<3)throw new G(`Input should be at least 3D, but is ${l}D.`);let u=[1,0].concat(dr(2,l));if(t=ct(t,u),s!=null)throw new He("The rnn() functoin of the deeplearn.js backend does not support constants yet.");i&&console.warn("Backend rnn(): the unroll = true option is not applicable to the imperative deeplearn.js backend."),r!=null&&(r=r.asType("bool").asType("float32"),r.rank===l-1&&(r=Ea(r,-1)),r=ct(r,u)),a&&(t=Ra(t,0),r!=null&&(r=Ra(r,0)));let d=[],h,p=n,c=t.shape[0],m=or(t),f;r!=null&&(f=or(r));for(let y=0;ye(A,p));if(r==null)h=x[0],p=x[1];else{let v=Z(()=>{let b=f[y],w=$a(b).sub(b),I=x[0].mul(b).add(p[0].mul(w)),T=p.map((C,z)=>x[1][z].mul(b).add(C.mul(w)));return{output:I,newStates:T}});h=v.output,p=v.newStates}o&&d.push(h)}let g;return o&&(g=Fa(d,1)),[h,g,p]})}var wS=class extends rt{constructor(e){super(e);let t;if(e.cell==null)throw new G("cell property is missing for the constructor of RNN.");if(Array.isArray(e.cell)?t=new A0({cells:e.cell}):t=e.cell,t.stateSize==null)throw new G("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 tn({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 dr(0,e).map(t=>null)}else return this.states_}setStates(e){this.states_=e}computeOutputShape(e){U2(e)&&(e=e[0]),e=e;let t=this.cell.stateSize;Array.isArray(t)||(t=[t]);let n=t[0],a;if(this.returnSequences?a=[e[0],e[1],n]:a=[e[0],n],this.returnState){let r=[];for(let s of t)r.push([e[0],s]);return[a].concat(r)}else return a}computeMask(e,t){return Z(()=>{Array.isArray(t)&&(t=t[0]);let n=this.returnSequences?t:null;if(this.returnState){let a=this.states.map(r=>null);return[n].concat(a)}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;ni.shape[i.shape.length-1]),s))throw new G(`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=s.map(i=>new tn({shape:[null,i]}));this.stateful&&this.resetStates()}resetStates(e,t=!1){Z(()=>{if(!this.stateful)throw new ds("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape[0];if(n==null)throw new G("If an RNN is stateful, it needs to know its batch size. Specify the batch size of your input tensors: \n- If using a Sequential model, specify the batch size by passing a `batchInputShape` option to your first layer.\n- If using the functional API, specify the batch size by passing a `batchShape` option to your Input layer.");if(this.states_==null)Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(a=>un([n,a])):this.states_=[un([n,this.cell.stateSize])];else if(e==null)Ge(this.states_),this.keptStates!=null&&(Ge(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(a=>un([n,a])):this.states_[0]=un([n,this.cell.stateSize]);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new G(`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()):Ge(this.states_);for(let a=0;aSn(a.clone()))})}apply(e,t){let n=t==null?null:t.initialState,a=t==null?null:t.constants;t==null&&(t={});let r=bS(e,n,a,this.numConstants);e=r.inputs,n=r.initialState,a=r.constants;let s=[],i=[];if(n!=null){t.initialState=n,s=s.concat(n),this.stateSpec=[];for(let o of n)this.stateSpec.push(new tn({shape:o.shape}));i=i.concat(this.stateSpec)}if(a!=null&&(t.constants=a,s=s.concat(a),this.numConstants=a.length),s[0]instanceof pr){let o=[e].concat(s),l=this.inputSpec.concat(i),u=this.inputSpec;this.inputSpec=l;let d=super.apply(o,t);return this.inputSpec=u,d}else return super.apply(e,t)}call(e,t){return Z(()=>{let n=t==null?null:t.mask,a=t==null?null:t.training,r=t==null?null:t.initialState;e=Ke(e),r==null&&(this.stateful?r=this.states_:r=this.getInitialState(e));let s=Array.isArray(this.cell.stateSize)?this.cell.stateSize.length:1;if(r.length!==s)throw new G(`RNN Layer has ${s} state(s) but was passed ${r.length} initial state(s).`);this.unroll&&console.warn("Ignoring unroll = true for RNN layer, due to imperative backend.");let i={training:a},o=vS((p,c)=>{let m=this.cell.call([p].concat(c),i);return[m[0],m.slice(1)]},e,r,this.goBackwards,n,null,this.unroll,this.returnSequences),l=o[0],u=o[1],d=o[2];this.stateful&&this.resetStates(d,a);let h=this.returnSequences?u:l;return this.returnState?[h].concat(d):h})}getInitialState(e){return Z(()=>{let t=un(e.shape);return t=Ce(t,[1,2]),t=Lh(t),Array.isArray(this.cell.stateSize)?this.cell.stateSize.map(n=>n>1?O2(t,[1,n]):t):this.cell.stateSize>1?[O2(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()===wS.className&&(t.cell={className:this.cell.getClassName(),config:n}),{...n,...e,...t}}static fromConfig(e,t,n={}){let a=t.cell,r=cr(a,n);return new e(Object.assign(t,{cell:r}))}},cs=wS;cs.className="RNN";ue.registerClass(cs);var Kh=class extends rt{},g0=class extends Kh{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,An(this.units,"units"),this.activation=Zs(e.activation==null?this.DEFAULT_ACTIVATION:e.activation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Pt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Pt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Pt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Lt(e.kernelRegularizer),this.recurrentRegularizer=Lt(e.recurrentRegularizer),this.biasRegularizer=Lt(e.biasRegularizer),this.kernelConstraint=pn(e.kernelConstraint),this.recurrentConstraint=pn(e.recurrentConstraint),this.biasConstraint=pn(e.biasConstraint),this.dropout=au([1,qs([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=au([1,qs([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=At(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 Z(()=>{if(e=e,e.length!==2)throw new G(`SimpleRNNCell expects 2 input Tensors, got ${e.length}.`);let n=e[1];e=e[0];let a=t.training==null?!1:t.training;0$a(e),rate:this.dropout,training:a})),0$a(n),rate:this.recurrentDropout,training:a}));let r,s=this.dropoutMask,i=this.recurrentDropoutMask;s!=null?r=Fr(K(e,s),this.kernel.read()):r=Fr(e,this.kernel.read()),this.bias!=null&&(r=hr(r,this.bias.read())),i!=null&&(n=K(n,i));let o=pe(r,Fr(n,this.recurrentKernel.read()));return this.activation!=null&&(o=this.activation.apply(o)),[o,o]})}getConfig(){let e=super.getConfig(),t={units:this.units,activation:Xs(this.activation),useBias:this.useBias,kernelInitializer:jt(this.kernelInitializer),recurrentInitializer:jt(this.recurrentInitializer),biasInitializer:jt(this.biasInitializer),kernelRegularizer:wt(this.kernelRegularizer),recurrentRegularizer:wt(this.recurrentRegularizer),biasRegularizer:wt(this.biasRegularizer),activityRegularizer:wt(this.activityRegularizer),kernelConstraint:hn(this.kernelConstraint),recurrentConstraint:hn(this.recurrentConstraint),biasConstraint:hn(this.biasConstraint),dropout:this.dropout,recurrentDropout:this.recurrentDropout};return{...e,...t}}};g0.className="SimpleRNNCell";ue.registerClass(g0);var Sx=class extends cs{constructor(e){e.cell=new g0(e),super(e)}call(e,t){return Z(()=>{this.cell.dropoutMask!=null&&(Ge(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Ge(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,a=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:a,initialState:r})})}static fromConfig(e,t){return new e(t)}};Sx.className="SimpleRNN";ue.registerClass(Sx);var y0=class extends Kh{constructor(e){super(e);if(this.DEFAULT_ACTIVATION="tanh",this.DEFAULT_RECURRENT_ACTIVATION="hardSigmoid",this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_RECURRENT_INITIALIZER="orthogonal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.resetAfter)throw new G("GRUCell does not support reset_after parameter set to true.");this.units=e.units,An(this.units,"units"),this.activation=Zs(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Zs(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Pt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Pt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Pt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelRegularizer=Lt(e.kernelRegularizer),this.recurrentRegularizer=Lt(e.recurrentRegularizer),this.biasRegularizer=Lt(e.biasRegularizer),this.kernelConstraint=pn(e.kernelConstraint),this.recurrentConstraint=pn(e.recurrentConstraint),this.biasConstraint=pn(e.biasConstraint),this.dropout=au([1,qs([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=au([1,qs([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.implementation=e.implementation,this.stateSize=this.units,this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){e=At(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 Z(()=>{if(e=e,e.length!==2)throw new G(`GRUCell expects 2 input Tensors (inputs, h, c), got ${e.length}.`);let n=t.training==null?!1:t.training,a=e[1];e=e[0],0$a(e),rate:this.dropout,training:n,count:3})),0$a(a),rate:this.recurrentDropout,training:n,count:3}));let r=this.dropoutMask,s=this.recurrentDropoutMask,i,o,l;0{this.cell.dropoutMask!=null&&(Ge(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Ge(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,a=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:a,initialState:r})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};Nx.className="GRU";ue.registerClass(Nx);var Xh=class extends Kh{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,An(this.units,"units"),this.activation=Zs(e.activation===void 0?this.DEFAULT_ACTIVATION:e.activation),this.recurrentActivation=Zs(e.recurrentActivation===void 0?this.DEFAULT_RECURRENT_ACTIVATION:e.recurrentActivation),this.useBias=e.useBias==null?!0:e.useBias,this.kernelInitializer=Pt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.recurrentInitializer=Pt(e.recurrentInitializer||this.DEFAULT_RECURRENT_INITIALIZER),this.biasInitializer=Pt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.unitForgetBias=e.unitForgetBias,this.kernelRegularizer=Lt(e.kernelRegularizer),this.recurrentRegularizer=Lt(e.recurrentRegularizer),this.biasRegularizer=Lt(e.biasRegularizer),this.kernelConstraint=pn(e.kernelConstraint),this.recurrentConstraint=pn(e.recurrentConstraint),this.biasConstraint=pn(e.biasConstraint),this.dropout=au([1,qs([0,e.dropout==null?0:e.dropout])]),this.recurrentDropout=au([1,qs([0,e.recurrentDropout==null?0:e.recurrentDropout])]),this.implementation=e.implementation,this.stateSize=[this.units,this.units],this.dropoutMask=null,this.recurrentDropoutMask=null}build(e){var t;e=At(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 a;if(this.useBias){if(this.unitForgetBias){let r=this.biasInitializer,s=this.units;a=new(t=class extends Xa{apply(i,o){let l=r.apply([s]),u=new qf().apply([s]),d=r.apply([s*2]);return cI(cI(l,u),d)}},t.className="CustomInit",t)}else a=this.biasInitializer;this.bias=this.addWeight("bias",[this.units*4],null,a,this.biasRegularizer,!0,this.biasConstraint)}else this.bias=null;this.built=!0}call(e,t){return Z(()=>{let n=t.training==null?!1:t.training;if(e=e,e.length!==3)throw new G(`LSTMCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let a=e[1],r=e[2];e=e[0],0$a(e),rate:this.dropout,training:n,count:4})),0$a(a),rate:this.recurrentDropout,training:n,count:4}));let s=this.dropoutMask,i=this.recurrentDropoutMask,o,l,u,d;0{this.cell.dropoutMask!=null&&(Ge(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Ge(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null);let n=t==null?null:t.mask,a=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:a,initialState:r})})}static fromConfig(e,t){return t.implmentation===0&&(t.implementation=1),new e(t)}};Tx.className="LSTM";ue.registerClass(Tx);var A0=class extends Kh{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 Z(()=>{e=e;let n=e.slice(1),a=[];for(let i of this.cells.slice().reverse())Array.isArray(i.stateSize)?a.push(n.splice(0,i.stateSize.length)):a.push(n.splice(0,1));a.reverse();let r=[],s;for(let i=0;i{io(`RNNCell_${a}`,()=>{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=a=>({className:a.getClassName(),config:a.getConfig()}),n={cells:this.cells.map(t)};return{...e,...n}}static fromConfig(e,t,n={}){let a=[];for(let r of t.cells)a.push(cr(r,n));return new e({cells:a})}get trainableWeights(){if(!this.trainable)return[];let e=[];for(let t of this.cells)e.push(...t.trainableWeights);return e}get nonTrainableWeights(){let e=[];for(let t of this.cells)e.push(...t.nonTrainableWeights);if(!this.trainable){let t=[];for(let 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 j2(e)}setWeights(e){let t=[];for(let n of this.cells){let a=n.weights.length,r=e.splice(a);for(let s=0;smI(t(),n),i=()=>Bh(s,t,a);return!r||r<=1?Sn(i().clone()):Array(r).fill(void 0).map(i).map(o=>Sn(o.clone()))}var kS=class extends cs{constructor(e){if(e.unroll)throw new He("Unrolling is not possible with convolutional RNNs.");if(Array.isArray(e.cell))throw new He("It is not possible at the moment to stack convolutional cells.");super(e);this.inputSpec=[new tn({ndim:5})]}call(e,t){return Z(()=>{if(this.cell.dropoutMask!=null&&(Ge(this.cell.dropoutMask),this.cell.dropoutMask=null),this.cell.recurrentDropoutMask!=null&&(Ge(this.cell.recurrentDropoutMask),this.cell.recurrentDropoutMask=null),t&&t.constants)throw new G("ConvRNN2D cell does not support constants");let n=t==null?null:t.mask,a=t==null?null:t.training,r=t==null?null:t.initialState;return super.call(e,{mask:n,training:a,initialState:r})})}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 Z(()=>{let{stateSize:t}=this.cell,n=e.shape,a=this.computeSingleOutputShape(n),r=[a[0],...a.slice(2)],s=un(r);return Array.isArray(t)?Array(t.length).fill(s):[s]})}resetStates(e,t=!1){Z(()=>{if(!this.stateful)throw new ds("Cannot call resetStates() on an RNN Layer that is not stateful.");let n=this.inputSpec[0].shape,a=this.computeSingleOutputShape(n),r=[a[0],...a.slice(2)];if(n[0]==null)throw new G("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(()=>un(r)):this.states_=[un(r)];else if(e==null)Ge(this.states_),this.keptStates!=null&&(Ge(this.keptStates),this.keptStates=[]),Array.isArray(this.cell.stateSize)?this.states_=this.cell.stateSize.map(()=>un(r)):this.states_[0]=un(r);else{if(Array.isArray(e)||(e=[e]),e.length!==this.states_.length)throw new G(`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()):Ge(this.states_);for(let s=0;sSn(s.clone()))})}computeSingleOutputShape(e){let{dataFormat:t,filters:n,kernelSize:a,padding:r,strides:s,dilationRate:i}=this.cell,o=t==="channelsFirst",l=e[o?3:2],u=e[o?4:3],d=fr(l,a[0],r,s[0],i[0]),h=fr(u,a[1],r,s[1],i[1]);return[...e.slice(0,2),...o?[n,d,h]:[d,h,n]]}};kS.className="ConvRNN2D";var x0=class extends Xh{constructor(e){let{filters:t,kernelSize:n,strides:a,padding:r,dataFormat:s,dilationRate:i}=e;super({...e,units:t});this.filters=t,An(this.filters,"filters"),this.kernelSize=ou(n,2,"kernelSize"),this.kernelSize.forEach(o=>An(o,"kernelSize")),this.strides=ou(a||1,2,"strides"),this.strides.forEach(o=>An(o,"strides")),this.padding=r||"valid",Oa(this.padding),this.dataFormat=s||"channelsLast",Yt(this.dataFormat),this.dilationRate=ou(i||1,2,"dilationRate"),this.dilationRate.forEach(o=>An(o,"dilationRate"))}build(e){var t;e=At(e);let n=this.dataFormat==="channelsFirst"?1:e.length-1;if(e[n]==null)throw new G(`The channel dimension of the input should be defined. Found ${e[n]}`);let a=e[n],r=4,s=this.kernelSize.concat([a,this.filters*r]);this.kernel=this.addWeight("kernel",s,null,this.kernelInitializer,this.kernelRegularizer,!0,this.kernelConstraint);let i=this.kernelSize.concat([this.filters,this.filters*r]);if(this.recurrentKernel=this.addWeight("recurrent_kernel",i,null,this.recurrentInitializer,this.recurrentRegularizer,!0,this.recurrentConstraint),this.useBias){let o;if(this.unitForgetBias){let l=this.biasInitializer,u=this.filters;o=new(t=class extends Xa{apply(d,h){let p=l.apply([u]),c=os([u]),m=l.apply([u*2]);return F2([p,c,m])}},t.className="CustomInit",t)}else o=this.biasInitializer;this.bias=this.addWeight("bias",[this.filters*r],null,o,this.biasRegularizer,!0,this.biasConstraint)}this.built=!0}call(e,t){return Z(()=>{if(e.length!==3)throw new G(`ConvLSTM2DCell expects 3 input Tensors (inputs, h, c), got ${e.length}.`);let n=t.training||!1,a=e[0],r=e[1],s=e[2],i=4;0$a(a),rate:this.dropout,training:n,count:i}));let o=this.dropoutMask,l=(ee,ie,ae)=>!ie||!ie[ae]?ee:K(ie[ae],ee),u=l(a,o,0),d=l(a,o,1),h=l(a,o,2),p=l(a,o,3);0$a(r),rate:this.recurrentDropout,training:n,count:i}));let c=this.recurrentDropoutMask,m=l(r,c,0),f=l(r,c,1),g=l(r,c,2),y=l(r,c,3),A=3,[x,v,b,w]=da(this.kernel.read(),i,A),[I,T,C,z]=this.useBias?da(this.bias.read(),i):[null,null,null,null];u=this.inputConv(u,x,I,this.padding),d=this.inputConv(d,v,T,this.padding),h=this.inputConv(h,b,C,this.padding),p=this.inputConv(p,w,z,this.padding);let[$,S,D,_]=da(this.recurrentKernel.read(),i,A);m=this.recurrentConv(m,$),f=this.recurrentConv(f,S),g=this.recurrentConv(g,D),y=this.recurrentConv(y,_);let W=this.recurrentActivation.apply(pe(u,m)),X=this.recurrentActivation.apply(pe(d,f)),q=pe(K(X,s),K(W,this.activation.apply(pe(h,g)))),Q=K(this.recurrentActivation.apply(pe(p,y)),this.activation.apply(q));return[Q,Q,q]})}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,a){let r=Ws(e,t,this.strides,a||"valid",this.dataFormat==="channelsFirst"?"NCHW":"NHWC",this.dilationRate);return n?hr(r,n,this.dataFormat):r}recurrentConv(e,t){return Ws(e,t,1,"same",this.dataFormat==="channelsFirst"?"NCHW":"NHWC")}};x0.className="ConvLSTM2DCell";ue.registerClass(x0);var Ex=class extends kS{constructor(e){let t=new x0(e);super({...e,cell:t})}static fromConfig(e,t){return new e(t)}};Ex.className="ConvLSTM2D";ue.registerClass(Ex);var b0=class extends rt{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 a=0;a{this.invokeCallHook(e,t);let n=Ke(e);if(0mI(n,this.rate,r,this.seed),()=>n,a)}return e})}getConfig(){let e={rate:this.rate,noiseShape:this.noiseShape,seed:this.seed},t=super.getConfig();return Object.assign(e,t),e}dispose(){return super.dispose()}};b0.className="Dropout";ue.registerClass(b0);var Cx=class extends b0{constructor(e){super(e);this.inputSpec=[{ndim:3}]}getNoiseShape(e){let t=e.shape;return[t[0],1,t[2]]}};Cx.className="SpatialDropout1D";ue.registerClass(Cx);var Mx=class extends rt{constructor(e){super(e);if(this.activation=null,this.useBias=!0,this.kernel=null,this.bias=null,this.DEFAULT_KERNEL_INITIALIZER="glorotNormal",this.DEFAULT_BIAS_INITIALIZER="zeros",e.batchInputShape==null&&e.inputShape==null&&e.inputDim!=null){let t=null;e.batchSize!=null&&(t=e.batchSize),this.batchInputShape=[t,e.inputDim]}this.units=e.units,An(this.units,"units"),this.activation=Zs(e.activation),e.useBias!=null&&(this.useBias=e.useBias),this.kernelInitializer=Pt(e.kernelInitializer||this.DEFAULT_KERNEL_INITIALIZER),this.biasInitializer=Pt(e.biasInitializer||this.DEFAULT_BIAS_INITIALIZER),this.kernelConstraint=pn(e.kernelConstraint),this.biasConstraint=pn(e.biasConstraint),this.kernelRegularizer=Lt(e.kernelRegularizer),this.biasRegularizer=Lt(e.biasRegularizer),this.activityRegularizer=Lt(e.activityRegularizer),this.supportsMasking=!0,this.inputSpec=[{minNDim:2}]}build(e){e=At(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=At(e);let t=e.slice();return t[t.length-1]=this.units,t}call(e,t){return Z(()=>{this.invokeCallHook(e,t);let n=Ke(e),a=rI(this.activation.getClassName()),r;return a!=null?r=Fr(n,this.kernel.read(),a,this.bias?this.bias.read():null):(r=Fr(n,this.kernel.read()),this.bias!=null&&(r=hr(r,this.bias.read())),this.activation!=null&&(r=this.activation.apply(r))),r})}getConfig(){let e={units:this.units,activation:Xs(this.activation),useBias:this.useBias,kernelInitializer:jt(this.kernelInitializer),biasInitializer:jt(this.biasInitializer),kernelRegularizer:wt(this.kernelRegularizer),biasRegularizer:wt(this.biasRegularizer),activityRegularizer:wt(this.activityRegularizer),kernelConstraint:hn(this.kernelConstraint),biasConstraint:hn(this.biasConstraint)},t=super.getConfig();return Object.assign(e,t),e}};Mx.className="Dense";ue.registerClass(Mx);var $x=class extends rt{constructor(e){e=e||{},super(e),this.inputSpec=[{minNDim:3}],this.dataFormat=e.dataFormat}computeOutputShape(e){e=At(e);for(let t of e.slice(1))if(t==null)throw new G(`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],Gs(e,1)]}call(e,t){return Z(()=>{this.invokeCallHook(e,t);let n=Ke(e);if(this.dataFormat==="channelsFirst"&&n.rank>1){let a=[0];for(let r=2;r{this.invokeCallHook(e,t);let n=Ke(e);return this.activation.apply(n)})}getConfig(){let e={activation:Xs(this.activation)},t=super.getConfig();return Object.assign(e,t),e}};Rx.className="Activation";ue.registerClass(Rx);var Fx=class extends rt{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 Z(()=>(e=Ke(e),cee(e,this.n)))}getConfig(){let e={n:this.n},t=super.getConfig();return Object.assign(e,t),e}};Fx.className="RepeatVector";ue.registerClass(Fx);var Ox=class extends rt{constructor(e){super(e);this.targetShape=e.targetShape;for(let t=0;t{this.invokeCallHook(e,t);let n=Ke(e),a=n.shape,r=a.slice(0,1).concat(this.fixUnknownDimension(a.slice(1),this.targetShape));return n.reshape(r)})}getConfig(){let e={targetShape:this.targetShape},t=super.getConfig();return Object.assign(e,t),e}};Ox.className="Reshape";ue.registerClass(Ox);var Dx=class extends rt{constructor(e){super(e);if(e.dims==null)throw new Error("Required configuration field `dims` is missing during Permute constructor call.");if(!Array.isArray(e.dims))throw new Error(`Permute constructor requires \`dims\` to be an Array, but received ${e.dims} instead.`);let t=dr(1,e.dims.length+1);if(!k.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 tn({ndim:this.dims.length+1})]}computeOutputShape(e){e=At(e);let t=e.slice();return this.dims.forEach((n,a)=>{t[a+1]=e[n]}),t}call(e,t){return ct(Ke(e),this.dimsIncludingBatch)}getConfig(){let e={dims:this.dims},t=super.getConfig();return Object.assign(e,t),e}};Dx.className="Permute";ue.registerClass(Dx);var _x=class extends rt{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=Ke(e),a=-1;return wf(Yl(n,this.maskValue),a)}call(e,t){return Z(()=>{this.invokeCallHook(e,t);let n=Ke(e),a=-1,r=!0,s=wf(Yl(n,this.maskValue),a,r);return n.mul(s.asType(n.dtype))})}};_x.className="Masking";ue.registerClass(_x);var zx=class extends rt{constructor(e){super(e);if(this.embeddings=null,this.DEFAULT_EMBEDDINGS_INITIALIZER="randomUniform",e.batchInputShape==null&&e.inputShape==null){let t=null;e.batchSize!=null&&(t=e.batchSize),e.inputLength==null?this.batchInputShape=[t,null]:this.batchInputShape=[t].concat(Ft(e.inputLength))}this.inputDim=e.inputDim,An(this.inputDim,"inputDim"),this.outputDim=e.outputDim,An(this.outputDim,"outputDim"),this.embeddingsInitializer=Pt(e.embeddingsInitializer||this.DEFAULT_EMBEDDINGS_INITIALIZER),this.embeddingsRegularizer=Lt(e.embeddingsRegularizer),this.activityRegularizer=Lt(e.activityRegularizer),this.embeddingsConstraint=pn(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 Z(()=>this.maskZero?(e=Ke(e),Yl(e,at(e))):null)}computeOutputShape(e){if(e=At(e),this.inputLength==null)return[...e,this.outputDim];let t=Ft(this.inputLength);if(t.length!==e.length-1)throw new G(`"inputLength" is ${this.inputLength}, but received input shape has shape ${e}`);{let n=0;for(let a=0;a{this.invokeCallHook(e,t);let n=Ke(e);return n.dtype!=="int32"&&(n=Ph(n,"int32")),fI(this.embeddings.read(),n.as1D()).reshape(At(this.computeOutputShape(n.shape)))})}getConfig(){let e={inputDim:this.inputDim,outputDim:this.outputDim,embeddingsInitializer:jt(this.embeddingsInitializer),embeddingsRegularizer:wt(this.embeddingsRegularizer),activityRegularizer:wt(this.activityRegularizer),embeddingsConstraint:hn(this.embeddingsConstraint),maskZero:this.maskZero,inputLength:this.inputLength},t=super.getConfig();return Object.assign(e,t),e}};zx.className="Embedding";ue.registerClass(zx);var po=class extends rt{constructor(e){super(e||{});this.supportsMasking=!0}mergeFunction(e){throw new He}computeElementwiseOpOutputShape(e,t){if(e==null||t==null)return null;if(e.length1)throw new G(`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 r=1;rr.length);e.indexOf(null)===-1&&Hs(a).length===1?this.reshapeRequired=!1:this.reshapeRequired=!0}call(e,t){return Z(()=>{if(e=e,this.reshapeRequired){let n=[],a=e.map(r=>r.rank);if(a.indexOf(null)===-1){let r=qs(a);for(let s of e){let i=s.rank;for(let o=0;o1){let u=dr(1,l).concat([0]);n.push(ct(o,u)),r=!0}else n.push(o)}let s=this.mergeFunction(n),i=s.rank;if(r){if(i==null){let o=s.shape,l=o.length,u=o[l-1],d=[u].concat(o.slice(0,o.length-1));s=ct(s.reshape([-1,u]),[1,0]).reshape(d)}else if(i>1){let o=[i-1].concat(dr(0,i-1));s=ct(s,o)}}return s}}else return this.mergeFunction(e)})}computeOutputShape(e){e=e;let t;e[0]==null?t=null:t=e[0].slice(1);for(let a=1;a{if(t==null)return null;if(!Array.isArray(t))throw new G("`mask` should be an Array");if(!Array.isArray(e))throw new G("`inputs` should be an Array");if(t.length!==e.length)throw new G(`The Array 'inputs' and 'mask' are expected to have the same length, but have different lengths (${e.length} vs ${t.length})`);if(t.every(a=>a==null))return null;t=t.map(a=>a==null?a:Ea(a,0));let n=t[0];for(let a=1;a{let t=e[0].clone();for(let n=1;n{let t=e[0].clone();for(let n=1;n{let t=e[0].clone();for(let n=1;n{let t=e[0];for(let n=1;n{let t=e[0];for(let n=1;n1)throw new G("A `Concatenate` layer requires inputs with matching shapes except for the concat axis. Got input shapes: "+JSON.stringify(e))}mergeFunction(e){return Z(()=>F2(e,this.axis))}computeOutputShape(e){if(!(Array.isArray(e)&&Array.isArray(e[0])))throw new G("A `Concatenate` layer should be called on a list of inputs.");let t=e,n=t[0].slice(),a=this.axis<0?n.length+this.axis:this.axis;for(let r of t.slice(1)){if(n[a]==null||r[a]==null){n[a]=null;break}n[a]+=r[a]}return n}computeMask(e,t){if(t==null)return null;if(!Array.isArray(t))throw new G("`mask` should be an array for Concatenate");if(!Array.isArray(e))throw new G("`inputs` should be an array for Concatenate");if(t.length!==e.length)throw new G(`Mismatch in the length of mask (${t.length}) and the legnth of inputs (${e.length})`);return Z(()=>{let n=!0;if(t.forEach(s=>{if(s!=null){n=!1;return}}),n)return null;let a=[];for(let s=0;s3||t.shape.length>3)throw new He("batchDot is not implemented for tensors of 4D or higher rank yet");if(k.assert(e.shape.length>=2,()=>`batchDot requires the rank of x to be >= 2, but got ${e.shape.length}`),k.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 He("batchDot is not implemented for complex64-type Tensors yet.");let a=e.shape.length,r=t.shape.length;n==null&&(n=[a-1,r-2]);let s=n;return Z(()=>{let i;if(a>r){i=a-r;let l=[];for(let u=0;ua){i=r-a;let l=[];for(let u=0;u0){let l;a>r?l=a+r-3:l=a-1;let u=[];for(let d=l;d"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 He("Dot layer does not support tensors of 4D or higher rank yet.");let a=this.interpretAxes(t,n);if(t[a[0]]!==n[a[1]])throw new G(`Dimension incompatibility: ${t[a[0]]} !== ${n[a[1]]}`)}mergeFunction(e){if(e.length!==2)throw new G(`A \`Dot\` layer must be called on exactly 2 inputs, but received ${e.length} input(s).`);let t=e[0],n=e[1],a;return Array.isArray(this.axes)?a=this.axes.map((r,s)=>Zh(r,e[s].shape.length)):a=[Zh(this.axes,t.shape.length),Zh(this.axes,n.shape.length)],this.normalize&&(t=s0(t,a[0]),n=s0(n,a[1])),Zte(t,n,a)}interpretAxes(e,t){let n;return Array.isArray(this.axes)?n=this.axes:n=[Zh(this.axes,e.length),Zh(this.axes,t.length)],n}computeOutputShape(e){k.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 He("Dot layer does not support tensors of 4D or higher rank yet.");let a=this.interpretAxes(t,n);t.splice(a[0],1),n.splice(a[1],1),n.splice(0,1);let r=t.concat(n);return r.length===1&&r.push(1),r}computeMask(e,t){return null}getConfig(){let e={axes:this.axes,normalize:this.normalize},t=super.getConfig();return Object.assign(e,t),e}};jx.className="Dot";ue.registerClass(jx);var Hx=class extends rt{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 Z(()=>{this.invokeCallHook(e,t);let n=Ke(e);return Bh(()=>Gf(n.shape,0,this.stddev).add(n),()=>n,t.training||!1)})}};Hx.className="GaussianNoise";ue.registerClass(Hx);var Gx=class extends rt{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 Z(()=>{this.invokeCallHook(e,t);let n=Ke(e);return this.rate>0&&this.rate<1?Bh(()=>{let a=Math.sqrt(this.rate/(1-this.rate));return n.mul(Gf(n.shape,1,a))},()=>n,t.training||!1):n})}};Gx.className="GaussianDropout";ue.registerClass(Gx);var qx=class extends rt{constructor(e){super(e);this.supportsMasking=!0,this.rate=e.rate,this.noiseShape=e.noiseShape}_getNoiseShape(e){return this.noiseShape||Ke(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 Z(()=>{if(this.rate<1&&this.rate>0){let n=this._getNoiseShape(e);return Bh(()=>{let a=Ke(e),r=1.6732632423543772,s=1.0507009873554805,i=-r*s,o=Yi(Rh(n),this.rate);o=Ph(o,"float32");let l=((1-this.rate)*(1+this.rate*i**2))**-.5,u=-l*i*this.rate;return a.mul(o).add(o.add(-1).mul(i)).mul(l).add(u)},()=>Ke(e),t.training||!1)}return e})}};qx.className="AlphaDropout";ue.registerClass(qx);function Yh(e,t,n,a,r,s=.001){let i;if(e.rank===2)i=NG(e,t,n,a,r,s);else if(e.rank===3)i=EG(e,t,n,a,r,s);else if(e.rank===4)i=MG(e,t,n,a,r,s);else throw new He(`batchNormalization is not implemented for array of rank ${e.rank} yet`);return i}function Yte(e,t,n,a,r=.001){return Z(()=>{let s=qA(e,a),i=s.mean,o=s.variance;return[Yh(e,i,o,n,t,r),i,o]})}function Jte(e,t,n,a,r=.001){return Z(()=>{let s=qA(e,a),i=s.mean,o=s.variance,l=[];for(let c of dr(0,e.rank))a.indexOf(c)!==-1?l.push(1):l.push(e.shape[c]);let u=i.reshape(l),d=o.reshape(l),h=t==null?null:t.reshape(l),p=n==null?null:n.reshape(l);return[Yh(e,u,d,p,h,r),i,o]})}function Qte(e,t,n,a,r=.001){return k.arraysEqual(a.slice().sort(),dr(0,e.rank-1))?Yte(e,t,n,a,r):Jte(e,t,n,a,r)}var Kx=class extends rt{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=Pt(e.betaInitializer||"zeros"),this.gammaInitializer=Pt(e.gammaInitializer||"ones"),this.movingMeanInitializer=Pt(e.movingMeanInitializer||"zeros"),this.movingVarianceInitializer=Pt(e.movingVarianceInitializer||"ones"),this.betaConstraint=pn(e.betaConstraint),this.gammaConstraint=pn(e.gammaConstraint),this.betaRegularizer=Lt(e.betaRegularizer),this.gammaRegularizer=Lt(e.gammaRegularizer)}build(e){e=At(e);let t=this.axis>=0?this.axis:this.axis+e.length,n=e[t];if(n==null)throw new G(`Axis ${t} of input tensor should have a defined dimension but the layer received an input with shape ${JSON.stringify(e)}.`);this.inputSpec=[new tn({ndim:e.length,axes:{[t]:n}})];let a=[n];this.scale&&(this.gamma=this.addWeight("gamma",a,null,this.gammaInitializer,this.gammaRegularizer,!0,this.gammaConstraint)),this.center&&(this.beta=this.addWeight("beta",a,null,this.betaInitializer,this.betaRegularizer,!0,this.betaConstraint)),this.movingMean=this.addWeight("moving_mean",a,null,this.movingMeanInitializer,null,!1),this.movingVariance=this.addWeight("moving_variance",a,null,this.movingVarianceInitializer,null,!1),this.built=!0}call(e,t){return Z(()=>{let n=t.training==null?!1:t.training,a=Ke(e),r=a.shape,s=r.length,i=dr(0,s),o=this.axis>=0?this.axis:this.axis+s;i.splice(o,1);let l=ao(1,s);l[o]=r[o];let u=i.slice();u.sort();let d=!k.arraysEqual(u,dr(0,s).slice(0,s-1)),h=()=>{if(d){let g=this.movingMean.read().reshape(l),y=this.movingVariance.read().reshape(l),A=this.center?this.beta.read().reshape(l):null,x=this.scale?this.gamma.read().reshape(l):null;return Yh(a,g,y,A,x,this.epsilon)}else return Yh(a,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 h();let[p,c,m]=Qte(a,this.gamma.read(),this.beta.read(),i,this.epsilon),f=(g,y,A)=>{Z(()=>{let x=1-A,v=g.read(),b=v.sub(y).mul(x);g.write(v.sub(b))})};return(()=>{f(this.movingMean,c,this.momentum),f(this.movingVariance,m,this.momentum)})(),p})}getConfig(){let e={axis:this.axis,momentum:this.momentum,epsilon:this.epsilon,center:this.center,scale:this.scale,betaInitializer:jt(this.betaInitializer),gammaInitializer:jt(this.gammaInitializer),movingMeanInitializer:jt(this.movingMeanInitializer),movingVarianceInitializer:jt(this.movingVarianceInitializer),betaRegularizer:wt(this.betaRegularizer),gammaRegularizer:wt(this.gammaRegularizer),betaConstraint:hn(this.betaConstraint),gammaConstraint:hn(this.gammaConstraint)},t=super.getConfig();return Object.assign(e,t),e}};Kx.className="BatchNormalization";ue.registerClass(Kx);var Xx=class extends rt{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=Pt(e.betaInitializer||"zeros"),this.gammaInitializer=Pt(e.gammaInitializer||"ones"),this.betaRegularizer=Lt(e.betaRegularizer),this.gammaRegularizer=Lt(e.gammaRegularizer),this.supportsMasking=!0}build(e){e=At(e);let t=e.length;typeof this.axis=="number"&&(this.axis=[this.axis]);for(let r=0;r=t)throw new Error(`Invalid axis: ${r}`);if(this.axis.length!==Hs(this.axis).length)throw new Error(`Found duplicate axes in: ${this.axis}`);let n=this.axis.map(r=>e[r]),a=!0;this.scale?this.gamma=this.addWeight("gamma",n,"float32",this.gammaInitializer,this.gammaRegularizer,a):this.gamma=null,this.center?this.beta=this.addWeight("beta",n,"float32",this.betaInitializer,this.betaRegularizer,a):this.beta=null,this.built=!0}call(e,t){let n=Ke(e),a=n.shape,r=a.length;return Z(()=>{let s=!0,{mean:i,variance:o}=qA(n,this.axis,s),l=ao(1,r);for(let m of this.axis)l[m]=a[m];let u=m=>m!=null&&m.shape.length!==r&&this.axis!==[r-1]?m.reshape(l):m,d=u(this.gamma.read()),h=u(this.beta.read()),p=[],c=[];for(let m=0;m{if(e.rank!==4)throw new G(`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 G("spatial2dPadding expects `padding` to be an Array of two Arrays, each of which is an Array of two integers.");if(n==null&&(n=lr()),n!=="channelsLast"&&n!=="channelsFirst")throw new G(`Unknown data format: ${n}. Supported data formats are 'channelsLast' and 'channelsFirst.`);let a;return n==="channelsFirst"?a=[[0,0],[0,0],t[0],t[1]]:a=[[0,0],t[0],t[1],[0,0]],Bs(e,a)})}var Zx=class extends rt{constructor(e){if(e==null&&(e={}),super(e),this.dataFormat=e.dataFormat==null?lr():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 G(`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 G(`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 G(`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 tn({ndim:4})]}computeOutputShape(e){e=At(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 Z(()=>ene(Ke(e),this.padding,this.dataFormat))}getConfig(){let e={padding:this.padding,dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}};Zx.className="ZeroPadding2D";ue.registerClass(Zx);function v0(e,t,n,a,r,s){return Z(()=>{Yt(r),lI(s),Oa(a),n==null&&(n=[1,1]),a==null&&(a="valid"),r==null&&(r=lr()),s==null&&(s="max"),e=gx(e,r);let i,o=a==="same"?"same":"valid";return s==="max"?i=Mf(e,t,n,o):i=Sf(e,t,n,o),r==="channelsFirst"&&(i=ct(i,[0,3,1,2])),i})}function IS(e,t,n,a,r,s){return Z(()=>{Yt(r),lI(s),Oa(a),n==null&&(n=[1,1,1]),a==null&&(a="valid"),r==null&&(r=lr()),s==null&&(s="max"),e=fS(e,r);let i,o=a==="same"?"same":"valid";return s==="max"?i=g8(e,t,n,o):i=Q4(e,t,n,o),r==="channelsFirst"&&(i=ct(i,[0,4,1,2,3])),i})}var SS=class extends rt{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 G(`poolSize for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.poolSize)}`);if(An(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 G(`strides for 1D convolutional layer must be a number or an Array of a single number, but received ${JSON.stringify(e.strides)}`);An(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,Oa(this.padding),this.inputSpec=[new tn({ndim:3})]}computeOutputShape(e){e=At(e);let t=fr(e[1],this.poolSize[0],this.padding,this.strides[0]);return[e[0],t,e[2]]}call(e,t){return Z(()=>{this.invokeCallHook(e,t),e=Lh(Ke(e),2);let n=this.poolingFunction(Ke(e),[this.poolSize[0],1],[this.strides[0],1],this.padding,"channelsLast");return Jl(n,[2])})}getConfig(){let e={poolSize:this.poolSize,padding:this.padding,strides:this.strides},t=super.getConfig();return Object.assign(e,t),e}},Yx=class extends SS{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Yt(r),Oa(a),v0(e,t,n,a,r,"max")}};Yx.className="MaxPooling1D";ue.registerClass(Yx);var Jx=class extends SS{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Yt(r),Oa(a),v0(e,t,n,a,r,"avg")}};Jx.className="AveragePooling1D";ue.registerClass(Jx);var NS=class extends rt{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 G(`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];An(this.poolSize,"poolSize"),An(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Yt(this.dataFormat),Oa(this.padding),this.inputSpec=[new tn({ndim:4})]}computeOutputShape(e){e=At(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2];return t=fr(t,this.poolSize[0],this.padding,this.strides[0]),n=fr(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 Z(()=>(this.invokeCallHook(e,t),this.poolingFunction(Ke(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}},Qx=class extends NS{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Yt(r),Oa(a),v0(e,t,n,a,r,"max")}};Qx.className="MaxPooling2D";ue.registerClass(Qx);var e5=class extends NS{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Yt(r),Oa(a),v0(e,t,n,a,r,"avg")}};e5.className="AveragePooling2D";ue.registerClass(e5);var TS=class extends rt{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 G(`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];An(this.poolSize,"poolSize"),An(this.strides,"strides"),this.padding=e.padding==null?"valid":e.padding,this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Yt(this.dataFormat),Oa(this.padding),this.inputSpec=[new tn({ndim:5})]}computeOutputShape(e){e=At(e);let t=this.dataFormat==="channelsFirst"?e[2]:e[1],n=this.dataFormat==="channelsFirst"?e[3]:e[2],a=this.dataFormat==="channelsFirst"?e[4]:e[3];return t=fr(t,this.poolSize[0],this.padding,this.strides[0]),n=fr(n,this.poolSize[1],this.padding,this.strides[1]),a=fr(a,this.poolSize[2],this.padding,this.strides[2]),this.dataFormat==="channelsFirst"?[e[0],e[1],t,n,a]:[e[0],t,n,a,e[4]]}call(e,t){return Z(()=>(this.invokeCallHook(e,t),this.poolingFunction(Ke(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}},t5=class extends TS{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Yt(r),Oa(a),IS(e,t,n,a,r,"max")}};t5.className="MaxPooling3D";ue.registerClass(t5);var n5=class extends TS{constructor(e){super(e)}poolingFunction(e,t,n,a,r){return Yt(r),Oa(a),IS(e,t,n,a,r,"avg")}};n5.className="AveragePooling3D";ue.registerClass(n5);var ES=class extends rt{constructor(e){super(e);this.inputSpec=[new tn({ndim:3})]}computeOutputShape(e){return[e[0],e[2]]}call(e,t){throw new He}},a5=class extends ES{constructor(e){super(e||{})}call(e,t){return Z(()=>{let n=Ke(e);return Xt(n,1)})}};a5.className="GlobalAveragePooling1D";ue.registerClass(a5);var r5=class extends ES{constructor(e){super(e||{})}call(e,t){return Z(()=>{let n=Ke(e);return sr(n,1)})}};r5.className="GlobalMaxPooling1D";ue.registerClass(r5);var CS=class extends rt{constructor(e){super(e);this.dataFormat=e.dataFormat==null?"channelsLast":e.dataFormat,Yt(this.dataFormat),this.inputSpec=[new tn({ndim:4})]}computeOutputShape(e){return e=e,this.dataFormat==="channelsLast"?[e[0],e[3]]:[e[0],e[1]]}call(e,t){throw new He}getConfig(){let e={dataFormat:this.dataFormat},t=super.getConfig();return Object.assign(e,t),e}},s5=class extends CS{call(e,t){return Z(()=>{let n=Ke(e);return this.dataFormat==="channelsLast"?Xt(n,[1,2]):Xt(n,[2,3])})}};s5.className="GlobalAveragePooling2D";ue.registerClass(s5);var i5=class extends CS{call(e,t){return Z(()=>{let n=Ke(e);return this.dataFormat==="channelsLast"?sr(n,[1,2]):sr(n,[2,3])})}};i5.className="GlobalMaxPooling2D";ue.registerClass(i5);var MS=class extends rt{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 a=t.layer,r=cr(a,n);delete t.layer;let s={layer:r};return Object.assign(s,t),new e(s)}},o5=class extends MS{constructor(e){super(e);this.supportsMasking=!0}build(e){if(e=At(e),e.length<3)throw new G(`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=At(e);let t=[e[0]].concat(e.slice(2)),n=this.layer.computeOutputShape(t),a=e[1];return[n[0],a].concat(n.slice(1))}call(e,t){return Z(()=>(e=Ke(e),vS((n,a)=>[Ke(this.layer.call(n,t)),[]],e,[],!1,null,null,!1,!0)[1]))}};o5.className="TimeDistributed";ue.registerClass(o5);function tne(e){so(lee,"BidirectionalMergeMode",e)}var nne="concat",l5=class extends MS{constructor(e){super(e);let t=e.layer.getConfig(),n={};n.className=e.layer.getClassName(),n.config=t,this.forwardLayer=cr(n),t.goBackwards=t.goBackwards!==!0;let a={};if(a.className=e.layer.getClassName(),a.config=t,this.backwardLayer=cr(a),this.forwardLayer.name="forward_"+this.forwardLayer.name,this.backwardLayer.name="backward_"+this.backwardLayer.name,this.mergeMode=e.mergeMode===void 0?nne:e.mergeMode,tne(this.mergeMode),e.weights)throw new He("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,a,r;return this.returnState&&(r=t.slice(1)),n=t[0],n=n,this.mergeMode==="concat"?(n[n.length-1]*=2,a=[n]):this.mergeMode==null?a=[n,n.slice()]:a=[n],this.returnState?this.mergeMode==null?a.concat(r).concat(r.slice()):[n].concat(r).concat(r.slice()):Qn(a)}apply(e,t){let n=t==null?null:t.initialState,a=t==null?null:t.constants;t==null&&(t={});let r=bS(e,n,a,this.numConstants);if(e=r.inputs,n=r.initialState,a=r.constants,Array.isArray(e)&&(n=e.slice(1),e=e[0]),(n==null||n.length===0)&&a==null)return super.apply(e,t);let s=[],i=[];if(n!=null){let l=n.length;if(l%2>0)throw new G("When passing `initialState` to a Bidrectional RNN, the state should be an Array containing the states of the underlying RNNs.");t.initialState=n,s.push(...n);let u=n.map(d=>new tn({shape:d.shape}));this.forwardLayer.stateSpec=u.slice(0,l/2),this.backwardLayer.stateSpec=u.slice(l/2),i.push(...u)}if(a!=null)throw new He("Support for constants in Bidirectional layers is not implemented yet.");let o=s[0]instanceof pr;for(let l of s)if(l instanceof pr!==o)throw new G("The initial state of a Bidirectional layer cannot be specified as a mix of symbolic and non-symbolic tensors");if(o){let l=[e].concat(s),u=this.inputSpec.concat(i),d=this.inputSpec;this.inputSpec=u;let h=super.apply(l,t);return this.inputSpec=d,h}else return super.apply(e,t)}call(e,t){return Z(()=>{let n=t.initialState,a,r;if(n==null)a=this.forwardLayer.call(e,t),r=this.backwardLayer.call(e,t);else{let o=n.slice(0,n.length/2),l=n.slice(n.length/2);a=this.forwardLayer.call(e,Object.assign(t,{initialState:o})),r=this.backwardLayer.call(e,Object.assign(t,{initialState:l}))}let s;this.returnState&&(Array.isArray(a)&&(s=a.slice(1).concat(r.slice(1))),a=a[0],r=r[0]),this.returnSequences&&(r=Ra(r,1));let i;return this.mergeMode==="concat"?i=F2([a,r]):this.mergeMode==="sum"?i=pe(a,r):this.mergeMode==="ave"?i=K(.5,pe(a,r)):this.mergeMode==="mul"?i=K(a,r):this.mergeMode==null&&(i=[a,r]),this.returnState?this.mergeMode==null?i.concat(s):[i].concat(s):i})}resetStates(e){this.forwardLayer.resetStates(),this.backwardLayer.resetStates()}build(e){io(this.forwardLayer.name,()=>{this.forwardLayer.build(e)}),io(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 a=this.forwardLayer.states.map(r=>null);return Array.isArray(n)?n.concat(a).concat(a):[n].concat(a).concat(a)}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=cr(t.layer);if(delete t.layer,t.numConstants!=null)throw new He("Deserialization of a Bidirectional layer with numConstants present is not supported yet.");let a=t;return a.layer=n,new e(a)}};l5.className="Bidirectional";ue.registerClass(l5);function ane(e){return new ru(e)}function rne(e){return new cx(e)}function sne(e){return new dx(e)}function ine(e){return new hx(e)}function one(e){return new px(e)}function lne(e){return new mx(e)}function une(e){return new fx(e)}function dne(e){return new vx(e)}function hne(e){return new f0(e)}function pne(e){return new Ax(e)}function cne(e){return new m0(e)}function fne(e){return new xx(e)}function mne(e){return new bx(e)}function gne(e){return new wx(e)}function yne(e){return new kx(e)}function Ane(e){return new Ix(e)}function xne(e){return new Rx(e)}function bne(e){return new Mx(e)}function vne(e){return new b0(e)}function wne(e){return new Cx(e)}function kne(e){return new $x(e)}function Ine(e){return new Fx(e)}function Sne(e){return new Ox(e)}function Nne(e){return new Dx(e)}function Tne(e){return new zx(e)}function Ene(e){return new Px(e)}function Cne(e){return new Wx(e)}function Mne(e){return new Ux(e)}function $ne(e){return new Bx(e)}function Rne(e){return new Vx(e)}function Fne(e){return new Lx(e)}function One(e){return new jx(e)}function Dne(e){return new Kx(e)}function _ne(e){return new Xx(e)}function zne(e){return new Zx(e)}function u5(e){return new Jx(e)}function Pne(e){return u5(e)}function Lne(e){return u5(e)}function d5(e){return new e5(e)}function Wne(e){return d5(e)}function Bne(e){return d5(e)}function h5(e){return new n5(e)}function Vne(e){return h5(e)}function Une(e){return h5(e)}function jne(e){return new a5(e)}function Hne(e){return new s5(e)}function $S(e){return new r5(e)}function RS(e){return new i5(e)}function FS(e){return new Yx(e)}function OS(e){return new Qx(e)}function Gne(e){return new t5(e)}function qne(e){return new Nx(e)}function Kne(e){return new y0(e)}function Xne(e){return new Tx(e)}function Zne(e){return new Xh(e)}function Yne(e){return new Sx(e)}function Jne(e){return new g0(e)}function Qne(e){return new Ex(e)}function eae(e){return new x0(e)}function tae(e){return new cs(e)}function nae(e){return new A0(e)}function aae(e){return new l5(e)}function rae(e){return new o5(e)}var sae=$S,iae=RS,oae=FS,lae=OS;function uae(e){return new Hx(e)}function dae(e){return new Gx(e)}function hae(e){return new qx(e)}function pae(e){return new _x(e)}var DS={};$e(DS,{MAPE:()=>kae,MSE:()=>Nae,binaryAccuracy:()=>cae,binaryCrossentropy:()=>fae,categoricalAccuracy:()=>gae,categoricalCrossentropy:()=>yae,cosineProximity:()=>bae,mape:()=>Iae,meanAbsoluteError:()=>vae,meanAbsolutePercentageError:()=>wae,meanSquaredError:()=>Sae,mse:()=>Tae,precision:()=>Aae,recall:()=>xae,sparseCategoricalAccuracy:()=>mae});function cae(e,t){return X2(e,t)}function fae(e,t){return FI(e,t)}function mae(e,t){return OI(e,t)}function gae(e,t){return Z2(e,t)}function yae(e,t){return Y2(e,t)}function Aae(e,t){return RI(e,t)}function xae(e,t){return ate(e,t)}function bae(e,t){return q2(e,t)}function vae(e,t){return i0(e,t)}function wae(e,t){return iu(e,t)}function kae(e,t){return iu(e,t)}function Iae(e,t){return iu(e,t)}function Sae(e,t){return lo(e,t)}function Nae(e,t){return lo(e,t)}function Tae(e,t){return lo(e,t)}var _S={};$e(_S,{modelFromJSON:()=>zte});var zS={};$e(zS,{l1:()=>Cae,l1l2:()=>Eae,l2:()=>Mae});function Eae(e){return new Gh(e)}function Cae(e){return Hte(e)}function Mae(e){return Gte(e)}var PS=class extends su{constructor(){super(...arguments);this.model=null}setModel(e){if(!(e instanceof ps))throw new Error("model must be a LayersModel, not some other Container");this.model=e}};function w0(e,t){return et}var WS=class extends PS{constructor(e){super();if(e==null&&(e={}),e.restoreBestWeights)throw new He("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=w0:this.mode==="max"?this.monitorFunc=LS:this.monitor.indexOf("acc")!==-1?this.monitorFunc=LS:this.monitorFunc=w0,this.monitorFunc===w0&&(this.minDelta*=-1)}async onTrainBegin(e){this.wait=0,this.stoppedEpoch=0,this.baseline!=null?this.best=this.baseline:this.best=this.monitorFunc===w0?Infinity:-Infinity}async onEpochEnd(e,t){await Ks(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 $ae(e){return new WS(e)}var Rae={earlyStopping:$ae},mr;(function(e){e[e.DT_INVALID=0]="DT_INVALID",e[e.DT_FLOAT=1]="DT_FLOAT",e[e.DT_DOUBLE=2]="DT_DOUBLE",e[e.DT_INT32=3]="DT_INT32",e[e.DT_UINT8=4]="DT_UINT8",e[e.DT_INT16=5]="DT_INT16",e[e.DT_INT8=6]="DT_INT8",e[e.DT_STRING=7]="DT_STRING",e[e.DT_COMPLEX64=8]="DT_COMPLEX64",e[e.DT_INT64=9]="DT_INT64",e[e.DT_BOOL=10]="DT_BOOL",e[e.DT_QINT8=11]="DT_QINT8",e[e.DT_QUINT8=12]="DT_QUINT8",e[e.DT_QINT32=13]="DT_QINT32",e[e.DT_BFLOAT16=14]="DT_BFLOAT16",e[e.DT_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"})(mr||(mr={}));var BS;(function(e){let t;(function(n){n[n.LEGACY=0]="LEGACY",n[n.V1=1]="V1",n[n.V2=2]="V2"})(t=e.CheckpointFormatVersion||(e.CheckpointFormatVersion={}))})(BS||(BS={}));var p5={};function Fae(e,t){let n={tfOpName:e,category:"custom",inputs:[],attrs:[],customExecutor:t};p5[e]=n}function VS(e){return p5[e]}function Oae(e){delete p5[e]}function N(e,t,n,a,r){let s=t.inputParams[e];if(s&&s.inputIndexStart!==void 0){let o=s.inputIndexStart,l=s.inputIndexEnd===0?void 0:s.inputIndexEnd===void 0?o+1:s.inputIndexEnd;if(s.type==="tensor")return Ln(t.inputNames[s.inputIndexStart],n,a,r);if(s.type==="tensors")return t.inputNames.slice(o,l).map(h=>Ln(h,n,a,r));let u=Ln(t.inputNames.slice(o)[0],n,a,r),d=u.dataSync();return s.type==="number"?d[0]:k.toNestedArray(u.shape,d)}let i=t.attrParams[e];return i&&i.value}function Ln(e,t,n,a){let[r,s]=ha(e);if(a!=null){let o=a.getHashTableHandleByName(r);if(o!=null)return o}let i=n.currentContextIds.find(o=>!!t[k0(r,o)]);return i!==void 0?t[k0(r,i)][s]:void 0}function Dae(e,t,n){return t[k0(e,n.currentContextId)]}function fs(e,t){let[n,a,r]=ha(e);return[k0(n,t&&t.currentContextId),a,r]}function k0(e,t){return t?`${e}-${t}`:e}function ha(e){let t=e.split(":");if(t.length===1)return[e,0,void 0];let n=t[0],a=t.length===3?t[1]:void 0,r=Number(t[t.length-1]);return[n,r,a]}function I0(e,t,n){let a=N("pad",e,t,n);if(a==="explicit"){a=N("explicitPaddings",e,t,n);let r=[[0,0],[0,0],[0,0],[0,0]];for(let s=0;s<4;s++)r[s][0]=a[s*2],r[s][1]=a[s*2+1];return r}return a}function ms(e){return e.kept?e:Gi(e)}var US={};$e(US,{json:()=>_ae});var _ae=[{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}]}],jS={};$e(jS,{json:()=>zae});var zae=[{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}]}],HS={};$e(HS,{json:()=>Pae});var Pae=[{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"}]}],GS={};$e(GS,{json:()=>Lae});var Lae=[{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"}]}],qS={};$e(qS,{json:()=>Wae});var Wae=[{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"}]}],KS={};$e(KS,{json:()=>Bae});var Bae=[{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}]}],XS={};$e(XS,{json:()=>Vae});var Vae=[{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"}]}],ZS={};$e(ZS,{json:()=>Uae});var Uae=[{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"}]}],YS={};$e(YS,{json:()=>jae});var jae=[{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"}]}],JS={};$e(JS,{json:()=>Hae});var Hae=[{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"}]}],QS={};$e(QS,{json:()=>Gae});var Gae=[{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}]}],e9={};$e(e9,{json:()=>qae});var qae=[{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"}]}],t9={};$e(t9,{json:()=>Kae});var Kae=[{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}]}],n9={};$e(n9,{json:()=>Xae});var Xae=[{tfOpName:"Bincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}]},{tfOpName:"DenseBincount",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"size",type:"number"},{start:2,name:"weights",type:"tensor"}],attrs:[{tfName:"binary_output",name:"binaryOutput",type:"bool"}]},{tfOpName:"Max",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Mean",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Min",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Sum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"All",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Any",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"ArgMax",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"ArgMin",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}]},{tfOpName:"Prod",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number[]"}],attrs:[{tfName:"keep_dims",name:"keepDims",type:"bool"}]},{tfOpName:"Cumsum",category:"reduction",inputs:[{start:0,name:"x",type:"tensor"},{start:1,name:"axis",type:"number"}],attrs:[{tfName:"exclusive",name:"exclusive",type:"bool"},{tfName:"reverse",name:"reverse",type:"bool"}]}],a9={};$e(a9,{json:()=>Zae});var Zae=[{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}]}],r9={};$e(r9,{json:()=>Yae});var Yae=[{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"}]}],s9={};$e(s9,{json:()=>Jae});var Jae=[{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}]}],i9={};$e(i9,{json:()=>Qae});var Qae=[{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"}]}],o9={};$e(o9,{json:()=>ere});var ere=[{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:[]}],l9=class{static get Instance(){return this._instance||(this._instance=new this)}constructor(){let e=[US,jS,HS,GS,qS,KS,XS,ZS,YS,JS,QS,e9,t9,n9,a9,r9,s9,i9,o9],t=[].concat(...e.map(n=>n.json));this.opMappers=t.reduce((n,a)=>(n[a.tfOpName]=a,n),{})}transformGraph(e,t={}){let n=e.node,a=[],r=[],s=[],i=n.reduce((m,f)=>(m[f.name]=this.mapNode(f),f.op.startsWith("Placeholder")?a.push(m[f.name]):f.op==="Const"?r.push(m[f.name]):(f.input==null||f.input.length===0)&&s.push(m[f.name]),m),{}),o=[],l=[],u={},d={};t!=null&&(u=this.mapSignatureEntries(t.inputs),d=this.mapSignatureEntries(t.outputs));let h=Object.keys(i);h.forEach(m=>{let f=i[m];f.inputNames.forEach((g,y)=>{let[A,,x]=fs(g),v=i[A];if(v.outputs!=null){let b=v.outputs.indexOf(x);if(b!==-1){let w=`${A}:${b}`;f.inputNames[y]=w}}f.inputs.push(v),v.children.push(f)})}),Object.keys(d).length===0?h.forEach(m=>{let f=i[m];f.children.length===0&&l.push(f)}):Object.keys(d).forEach(m=>{let[f]=fs(m),g=i[f];g!=null&&(g.signatureKey=d[m],l.push(g))}),Object.keys(u).length>0?Object.keys(u).forEach(m=>{let[f]=fs(m),g=i[f];g&&(g.signatureKey=u[m],o.push(g))}):o=a;let p={};e.library!=null&&e.library.function!=null&&(p=e.library.function.reduce((m,f)=>(m[f.signature.name]=this.mapFunction(f),m),{}));let c={nodes:i,inputs:o,outputs:l,weights:r,placeholders:a,signature:t,functions:p};return s.length>0&&(c.initNodes=s),c}mapSignatureEntries(e){return Object.keys(e||{}).reduce((t,n)=>(t[e[n].name]=n,t),{})}mapNode(e){let t=VS(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(a=>a.startsWith("^")?a.substr(1):a),inputs:[],children:[],inputParams:{},attrParams:{},rawAttrs:e.attr,outputs:t.outputs};return t.inputs!=null&&(n.inputParams=t.inputs.reduce((a,r)=>(a[r.name]={type:r.type,inputIndexStart:r.start,inputIndexEnd:r.end},a),{})),t.attrs!=null&&(n.attrParams=t.attrs.reduce((a,r)=>{let s=r.type,i;switch(r.type){case"string":i=c5(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=c5(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"string[]":i=v5(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=v5(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"number":i=m5(e.attr,r.tfName,r.defaultValue||0),i===void 0&&!!r.tfDeprecatedName&&(i=m5(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"number[]":i=b5(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=b5(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"bool":i=f5(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=f5(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"bool[]":i=k5(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=k5(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"shape":i=x5(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=x5(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"shape[]":i=w5(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=w5(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"dtype":i=y5(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=y5(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"dtype[]":i=A5(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=A5(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"func":i=d9(e.attr,r.tfName,r.defaultValue),i===void 0&&!!r.tfDeprecatedName&&(i=d9(e.attr,r.tfDeprecatedName,r.defaultValue));break;case"tensor":case"tensors":break;default:throw new Error(`Unsupported param type: ${r.type} for op: ${e.op}`)}return a[r.name]={value:i,type:s},a},{})),n}mapFunction(e){let t=e.nodeDef,n=[],a=[],r={};t!=null&&(r=t.reduce((u,d)=>(u[d.name]=this.mapNode(d),d.op==="Const"&&a.push(u[d.name]),u),{}));let s=[],i=[];e.signature.inputArg.forEach(u=>{let[d]=fs(u.name),h={name:d,op:"Placeholder",inputs:[],inputNames:[],category:"graph",inputParams:{},attrParams:{dtype:{value:g5(u.type),type:"dtype"}},children:[]};h.signatureKey=u.name,s.push(h),r[d]=h}),Object.keys(r).forEach(u=>{let d=r[u];d.inputNames.forEach((h,p)=>{let[c,,m]=fs(h),f=r[c];if(f.outputs!=null){let g=f.outputs.indexOf(m);if(g!==-1){let y=`${c}:${g}`;d.inputNames[p]=y}}d.inputs.push(f),f.children.push(d)})});let o=e.ret;e.signature.outputArg.forEach(u=>{let[d,h]=fs(o[u.name]),p=r[d];p!=null&&(p.defaultOutput=h,i.push(p))});let l=this.mapArgsToSignature(e);return{nodes:r,inputs:s,outputs:i,weights:a,placeholders:n,signature:l}}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 tre(e){let t=se().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 u9(e,t){let n=Array.isArray(e)?String.fromCharCode.apply(null,e):tre(e);return t?n:n.toLowerCase()}function c5(e,t,n,a=!1){let r=e[t];return r!=null?u9(r.s,a):n}function f5(e,t,n){let a=e[t];return a?a.b:n}function m5(e,t,n){let a=e[t]||{},r=a.i!=null?a.i:a.f!=null?a.f:n;return typeof r=="number"?r:parseInt(r,10)}function g5(e){switch(typeof e=="string"&&(e=mr[e]),e){case mr.DT_FLOAT:return"float32";case mr.DT_INT32:case mr.DT_INT64:case mr.DT_INT8:case mr.DT_UINT8:return"int32";case mr.DT_BOOL:return"bool";case mr.DT_DOUBLE:return"float32";case mr.DT_STRING:return"string";default:return null}}function d9(e,t,n){let a=e[t];return a&&a.func?a.func.name:n}function y5(e,t,n){let a=e[t];return a&&a.type?g5(a.type):n}function A5(e,t,n){let a=e[t];return a&&a.list&&a.list.type?a.list.type.map(r=>g5(r)):n}function h9(e){if(!e.unknownRank)return e.dim!=null?e.dim.map(t=>typeof t.size=="number"?t.size:parseInt(t.size,10)):[]}function x5(e,t,n){let a=e[t];return a&&a.shape?h9(a.shape):n}function b5(e,t,n){let a=e[t];return a?((a.list.f&&a.list.f.length?a.list.f:a.list.i)||[]).map(r=>typeof r=="number"?r:parseInt(r,10)):n}function v5(e,t,n,a=!1){let r=e[t];return r&&r.list&&r.list.s?r.list.s.map(s=>u9(s,a)):n}function w5(e,t,n){let a=e[t];return a&&a.list&&a.list.shape?a.list.shape.map(r=>h9(r)):n}function k5(e,t,n){let a=e[t];return a&&a.list&&a.list.b?a.list.b:n}var nre=class{constructor(e,t,n){this.node=e,this.tensorMap=t,this.context=n,this.inputs=[],this.attrs={},this.inputs=e.inputNames.map(a=>this.getInput(a)),e.rawAttrs!=null&&(this.attrs=Object.keys(e.rawAttrs).reduce((a,r)=>(a[r]=this.getAttr(r),a),{}))}getInput(e){return Ln(e,this.tensorMap,this.context)}getAttr(e,t){let n=this.node.rawAttrs[e];if(n.tensor!=null)return Ln(e,this.tensorMap,this.context);if(n.i!=null||n.f!=null)return m5(this.node.rawAttrs,e,t);if(n.s!=null)return c5(this.node.rawAttrs,e,t);if(n.b!=null)return f5(this.node.rawAttrs,e,t);if(n.shape!=null)return x5(this.node.rawAttrs,e,t);if(n.type!=null)return y5(this.node.rawAttrs,e,t);if(n.list!=null){if(n.list.i!=null||n.list.f!=null)return b5(this.node.rawAttrs,e,t);if(n.list.s!=null)return v5(this.node.rawAttrs,e,t);if(n.list.shape!=null)return w5(this.node.rawAttrs,e,t);if(n.list.b!=null)return k5(this.node.rawAttrs,e,t);if(n.list.type!=null)return A5(this.node.rawAttrs,e,t)}return t}},are=(e,t,n)=>{switch(e.op){case"BiasAdd":case"AddV2":case"Add":return[pe(N("a",e,t,n),N("b",e,t,n))];case"AddN":return[JH(N("tensors",e,t,n))];case"FloorMod":case"Mod":return[A8(N("a",e,t,n),N("b",e,t,n))];case"Mul":return[K(N("a",e,t,n),N("b",e,t,n))];case"RealDiv":case"Div":return[Me(N("a",e,t,n),N("b",e,t,n))];case"DivNoNan":return[i8(N("a",e,t,n),N("b",e,t,n))];case"FloorDiv":return[$A(N("a",e,t,n),N("b",e,t,n))];case"Sub":return[Ne(N("a",e,t,n),N("b",e,t,n))];case"Minimum":return[$h(N("a",e,t,n),N("b",e,t,n))];case"Maximum":return[is(N("a",e,t,n),N("b",e,t,n))];case"Pow":return[Vs(N("a",e,t,n),N("b",e,t,n))];case"SquaredDifference":return[o2(N("a",e,t,n),N("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},rre=(e,t,n)=>{switch(e.op){case"Abs":case"ComplexAbs":return[yn(N("x",e,t,n))];case"Acos":return[V4(N("x",e,t,n))];case"Acosh":return[U4(N("x",e,t,n))];case"Asin":return[H4(N("x",e,t,n))];case"Asinh":return[G4(N("x",e,t,n))];case"Atan":return[q4(N("x",e,t,n))];case"Atan2":return[K4(N("x",e,t,n),N("y",e,t,n))];case"Atanh":return[X4(N("x",e,t,n))];case"Ceil":return[t8(N("x",e,t,n))];case"Complex":return[Vi(N("real",e,t,n),N("imag",e,t,n))];case"Cos":return[Tf(N("x",e,t,n))];case"Cosh":return[PA(N("x",e,t,n))];case"Elu":return[Th(N("x",e,t,n))];case"Erf":return[o8(N("x",e,t,n))];case"Exp":return[qa(N("x",e,t,n))];case"Expm1":return[l8(N("x",e,t,n))];case"Floor":return[Ch(N("x",e,t,n))];case"Log":return[Ma(N("x",e,t,n))];case"Log1p":return[VA(N("x",e,t,n))];case"Imag":return[WA(N("x",e,t,n))];case"Neg":return[Kt(N("x",e,t,n))];case"Reciprocal":return[x8(N("x",e,t,n))];case"Real":return[Of(N("x",e,t,n))];case"Relu":return[ls(N("x",e,t,n))];case"Round":return[JA(N("x",e,t,n))];case"Selu":return[e2(N("x",e,t,n))];case"Sigmoid":return[$r(N("x",e,t,n))];case"Sin":return[t2(N("x",e,t,n))];case"Sign":return[v8(N("x",e,t,n))];case"Sinh":return[n2(N("x",e,t,n))];case"Softplus":return[Zl(N("x",e,t,n))];case"Sqrt":return[Mn(N("x",e,t,n))];case"Square":return[vt(N("x",e,t,n))];case"Tanh":return[Kl(N("x",e,t,n))];case"Tan":return[S8(N("x",e,t,n))];case"ClipByValue":return[ua(N("x",e,t,n),N("clipValueMin",e,t,n),N("clipValueMax",e,t,n))];case"Relu6":return[YA(N("x",e,t,n))];case"Rsqrt":return[QA(Ln(e.inputNames[0],t,n))];case"Prod":return[KA(N("x",e,t,n),N("axes",e,t,n))];case"LeakyRelu":return[Ef(N("x",e,t,n),N("alpha",e,t,n))];case"Prelu":return[Ff(N("x",e,t,n),N("alpha",e,t,n))];case"IsNan":return[d8(Ln(e.inputNames[0],t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function Za(e,t,n=""){if(!(typeof e=="number"||typeof t=="number")){k.assert(e.length===t.length,()=>n+` Shapes ${e} and ${t} must match`);for(let a=0;an+` Shapes ${e} and ${t} must match`)}}}function p9(e){return!(typeof e=="number"||e.some(t=>t<0))}function Jh(e,t,n){let a=I5(e,n),r=!p9(a);if(r&&t.length===0)throw new Error(`Tried to calculate elements of an empty list with non-fully-defined elementShape: ${a}`);if(r&&t.forEach(s=>{a=I5(s.shape,a)}),!p9(a))throw new Error(`Non-fully-defined elementShape: ${a}`);return a}function I5(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 a=0;a=0&&s>=0&&r!==s)throw new Error(`Incompatible shape during merge: ${e} vs. ${t}`);n[a]=r>=0?r:s}return n}var sre=class{constructor(e,t,n,a,r,s,i){this.name=e,this.dtype=t,this.maxSize=n,this.elementShape=a,this.identicalElementShapes=r,this.dynamicSize=s,this.clearAfterRead=i,this.tensors=[],this.closed_=!1,this.idTensor=Re(0),Sn(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),Za(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,Sn(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,a)=>this.write(n,t[a]))}gather(e,t){if(!!t&&t!==this.dtype)throw new Error(`TensorArray dtype is ${this.dtype} but gather requested dtype ${t}`);if(e)e=e.slice(0,this.size());else{e=[];for(let a=0;a=this.maxSize)throw new Error(`Max index must be < array size (${n} vs. ${this.maxSize})`);this.writeMany(e,or(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,a=e.map(o=>(n+=o,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 r=n===0?0:t.size/n,s=[];Z(()=>{t=Y(t,[1,n,r]);for(let o=0;o{if(n!==r.dtype)throw new Error(`Invalid data types; op elements ${n}, but list elements ${r.dtype}`);Za(t,r.shape,"TensorList shape mismatch: "),Sn(r)}),this.idTensor=Re(0),this.maxNumElements=a,Sn(this.idTensor)}get id(){return this.idTensor.id}copy(){return new Qh([...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.`);Za(e,this.elementShape,"TensorList shape mismatch: ");let a=Jh(this.elementShape,this.tensors,e);return Z(()=>{let r=this.tensors.map(s=>Y(s,a));return Fa(r,0)})}popBack(e,t){if(t!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t}, but list elements ${this.elementDtype}`);if(this.size()===0)throw new Error("Trying to pop from an empty list.");let n=Jh(this.elementShape,this.tensors,e),a=this.tensors.pop();return Za(a.shape,e,"TensorList shape mismatch: "),Y(a,n)}pushBack(e){if(e.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${this.elementDtype}`);if(Za(e.shape,this.elementShape,"TensorList shape mismatch: "),this.maxNumElements===this.size())throw new Error("Trying to push element into a full list.");Sn(e),this.tensors.push(e)}resize(e){if(e<0)throw new Error(`TensorListResize expects size to be non-negative. Got: ${e}`);if(this.maxNumElements!==-1&&e>this.maxNumElements)throw new Error(`TensorListResize input size ${e} is greater maxNumElement ${this.maxNumElements}.`);this.tensors.length=e}getItem(e,t,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.`);Za(this.tensors[e].shape,t,"TensorList shape mismatch: ");let a=Jh(this.elementShape,this.tensors,t);return Y(this.tensors[e],a)}setItem(e,t){if(t.dtype!==this.elementDtype)throw new Error(`Invalid data types; op elements ${t.dtype}, but list elements ${this.elementDtype}`);if(e<0||this.maxNumElements!==-1&&e>=this.maxNumElements)throw new Error(`Trying to set element ${e} in a list with max ${this.maxNumElements} elements.`);Za(this.elementShape,t.shape,"TensorList shape mismatch: "),Sn(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}`);Za(this.elementShape,n,"TensorList shape mismatch: "),e=e.slice(0,this.size());let a=Jh(this.elementShape,this.tensors,n);return e.length===0?Cr([],[0].concat(a)):Z(()=>{let r=e.map(s=>Y(this.tensors[s],a));return Fa(r,0)})}concat(e,t){if(!!e&&e!==this.elementDtype)throw new Error(`TensorList dtype is ${this.elementDtype} but concat requested dtype ${e}`);Za(this.elementShape,t,"TensorList shape mismatch: ");let n=Jh(this.elementShape,this.tensors,t);return this.size()===0?Cr([],[0].concat(n)):Z(()=>{let a=this.tensors.map(r=>Y(r,n));return en(a,0)})}};function ire(e,t,n){let a=e.dtype;if(e.shape.length<1)throw new Error(`Tensor must be at least a vector, but saw shape: ${e.shape}`);if(e.dtype!==n)throw new Error(`Invalid data types; op elements ${e.dtype}, but list elements ${n}`);let r=e.shape.slice(1);Za(r,t,"TensorList shape mismatch: ");let s=or(e);return new Qh(s,t,a)}function ore(e,t,n){return new Qh([],e,t,n)}function lre(e,t,n,a){if(t.length!==e.shape[0])throw new Error(`Expected len(indices) == tensor.shape[0], but saw: ${t.length} vs. ${e.shape[0]}`);let r=Math.max(...t);if(a!=null&&a!==-1&&r>=a)throw new Error(`Max index must be < array size (${r} vs. ${a})`);let s=new Qh([],n,e.dtype,a),i=or(e,0);return t.forEach((o,l)=>{s.setItem(o,i[l])}),s}function ure(e,t,n){let a=0,r=t.map(d=>(a+=d,a));if(a!==e.shape[0])throw new Error(`Expected sum of lengths to be equal to tensor.shape[0], but sum of lengths is ${a}, and tensor's shape is: ${e.shape}`);let s=e.shape.slice(1),i=I5(s,n),o=a===0?0:e.size/a,l=Z(()=>{let d=[];e=Y(e,[1,a,o]);for(let h=0;h{switch(e.op){case"If":case"StatelessIf":{let a=N("thenBranch",e,t,n),r=N("elseBranch",e,t,n),s=N("cond",e,t,n),i=N("args",e,t,n);return(await s.data())[0]?n.functionMap[a].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap):n.functionMap[r].executeFunctionAsync(i,n.tensorArrayMap,n.tensorListMap)}case"While":case"StatelessWhile":{let a=N("body",e,t,n),r=N("cond",e,t,n),s=N("args",e,t,n),i=await n.functionMap[r].executeFunctionAsync(s,n.tensorArrayMap,n.tensorListMap),o=s.map(d=>d.id),l=await i[0].data();i.forEach(d=>{!d.kept&&o.indexOf(d.id)===-1&&d.dispose()});let u=s;for(;l[0];){let d=u;u=await n.functionMap[a].executeFunctionAsync(u,n.tensorArrayMap,n.tensorListMap);let h=u.map(c=>c.id);d.forEach(c=>{!c.kept&&o.indexOf(c.id)===-1&&h.indexOf(c.id)===-1&&c.dispose()});let p=await n.functionMap[r].executeFunctionAsync(u,n.tensorArrayMap,n.tensorListMap);l=await p[0].data(),p.forEach(c=>{!c.kept&&o.indexOf(c.id)===-1&&h.indexOf(c.id)===-1&&c.dispose()})}return u}case"LoopCond":{let a=N("pred",e,t,n);return[ms(a)]}case"Switch":{let a=N("pred",e,t,n),r=N("data",e,t,n);return r.kept||(r=ms(r)),(await a.data())[0]?[void 0,r]:[r,void 0]}case"Merge":{let a=e.inputNames.find(r=>Ln(r,t,n)!==void 0);if(a){let r=Ln(a,t,n);return[ms(r)]}return}case"Enter":{let a=N("frameName",e,t,n),r=N("tensor",e,t,n);return n.enterFrame(a),[ms(r)]}case"Exit":{let a=N("tensor",e,t,n);return n.exitFrame(),[ms(a)]}case"NextIteration":{let a=N("tensor",e,t,n);return n.nextIteration(),[ms(a)]}case"TensorArrayV3":{let a=N("size",e,t,n),r=N("dtype",e,t,n),s=N("elementShape",e,t,n),i=N("dynamicSize",e,t,n),o=N("clearAfterRead",e,t,n),l=N("identicalElementShapes",e,t,n),u=N("name",e,t,n),d=new sre(u,r,a,s,l,i,o);return n.addTensorArray(d),[d.idTensor,Re(1)]}case"TensorArrayWriteV3":{let a=N("tensorArrayId",e,t,n),r=N("index",e,t,n),s=N("tensor",e,t,n),i=n.getTensorArray(a.id);return i.write(r,s),[i.idTensor]}case"TensorArrayReadV3":{let a=N("tensorArrayId",e,t,n),r=N("index",e,t,n);return[n.getTensorArray(a.id).read(r)]}case"TensorArrayGatherV3":{let a=N("tensorArrayId",e,t,n),r=N("indices",e,t,n),s=N("dtype",e,t,n);return[n.getTensorArray(a.id).gather(r,s)]}case"TensorArrayScatterV3":{let a=N("tensorArrayId",e,t,n),r=N("indices",e,t,n),s=N("tensor",e,t,n),i=n.getTensorArray(a.id);return i.scatter(r,s),[i.idTensor]}case"TensorArrayConcatV3":{let a=N("tensorArrayId",e,t,n),r=n.getTensorArray(a.id),s=N("dtype",e,t,n);return[r.concat(s)]}case"TensorArraySplitV3":{let a=N("tensorArrayId",e,t,n),r=N("tensor",e,t,n),s=N("lengths",e,t,n),i=n.getTensorArray(a.id);return i.split(s,r),[i.idTensor]}case"TensorArraySizeV3":{let a=N("tensorArrayId",e,t,n),r=n.getTensorArray(a.id);return[Re(r.size(),"int32")]}case"TensorArrayCloseV3":{let a=N("tensorArrayId",e,t,n),r=n.getTensorArray(a.id);return r.clearAndClose(),[r.idTensor]}case"TensorListSetItem":{let a=N("tensorListId",e,t,n),r=N("index",e,t,n),s=N("tensor",e,t,n),i=n.getTensorList(a.id);return i.setItem(r,s),[i.idTensor]}case"TensorListGetItem":{let a=N("tensorListId",e,t,n),r=N("index",e,t,n),s=N("elementShape",e,t,n),i=N("elementDType",e,t,n);return[n.getTensorList(a.id).getItem(r,s,i)]}case"TensorListScatterV2":case"TensorListScatter":{let a=N("indices",e,t,n),r=N("tensor",e,t,n),s=N("elementShape",e,t,n),i=N("numElements",e,t,n),o=lre(r,a,s,i);return n.addTensorList(o),[o.idTensor]}case"TensorListReserve":case"EmptyTensorList":{let a=N("elementShape",e,t,n),r=N("elementDType",e,t,n),s;e.op==="TensorListReserve"?s="numElements":s="maxNumElements";let i=N(s,e,t,n),o=ore(a,r,i);return n.addTensorList(o),[o.idTensor]}case"TensorListGather":{let a=N("tensorListId",e,t,n),r=N("indices",e,t,n),s=N("elementShape",e,t,n),i=N("elementDType",e,t,n);return[n.getTensorList(a.id).gather(r,i,s)]}case"TensorListStack":{let a=N("tensorListId",e,t,n),r=N("elementShape",e,t,n),s=N("elementDType",e,t,n),i=N("numElements",e,t,n);return[n.getTensorList(a.id).stack(r,s,i)]}case"TensorListFromTensor":{let a=N("tensor",e,t,n),r=N("elementShape",e,t,n),s=N("elementDType",e,t,n),i=ire(a,r,s);return n.addTensorList(i),[i.idTensor]}case"TensorListConcat":{let a=N("tensorListId",e,t,n),r=n.getTensorList(a.id),s=N("dtype",e,t,n),i=N("elementShape",e,t,n);return[r.concat(s,i)]}case"TensorListPushBack":{let a=N("tensorListId",e,t,n),r=N("tensor",e,t,n),s=n.getTensorList(a.id);return s.pushBack(r),[s.idTensor]}case"TensorListPopBack":{let a=N("tensorListId",e,t,n),r=N("elementShape",e,t,n),s=N("elementDType",e,t,n);return[n.getTensorList(a.id).popBack(r,s)]}case"TensorListSplit":{let a=N("tensor",e,t,n),r=N("elementShape",e,t,n),s=N("lengths",e,t,n),i=ure(a,s,r);return n.addTensorList(i),[i.idTensor]}default:throw TypeError(`Node type ${e.op} is not implemented`)}};function c9(e,t,n){let[a,r]=N("fusedOps",e,t,n),s=a==="biasadd",i=!s,o=r==="prelu",l=a==="fusedbatchnorm",u=N("numArgs",e,t,n);if(s){if(o&&u!==2)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!o&&s&&u!==1)throw new Error("FusedConv2d and DepthwiseConv2d with BiasAdd must have one extra argument: bias.")}if(l)throw new Error("FusedConv2d and DepthwiseConv2d with FusedBatchNorm is not supported");let d=N("strides",e,t,n),h=I0(e,t,n),p=N("dataFormat",e,t,n).toUpperCase(),c=N("dilations",e,t,n),[m,f]=N("args",e,t,n);i&&(f=m,m=void 0);let g=N("leakyreluAlpha",e,t,n);return{stride:d,pad:h,dataFormat:p,dilations:c,biasArg:m,preluArg:f,activationFunc:r,leakyreluAlpha:g}}var hre=(e,t,n)=>{switch(e.op){case"Conv1D":{let a=N("stride",e,t,n),r=N("pad",e,t,n),s=N("dataFormat",e,t,n).toUpperCase(),i=N("dilation",e,t,n);return[DA(N("x",e,t,n),N("filter",e,t,n),a,r,s,i)]}case"Conv2D":{let a=N("strides",e,t,n),r=I0(e,t,n),s=N("dataFormat",e,t,n).toUpperCase(),i=N("dilations",e,t,n);return[Ws(N("x",e,t,n),N("filter",e,t,n),[a[1],a[2]],r,s,[i[1],i[2]])]}case"_FusedConv2D":{let{stride:a,pad:r,dataFormat:s,dilations:i,biasArg:o,preluArg:l,activationFunc:u,leakyreluAlpha:d}=c9(e,t,n);return[eo.conv2d({x:N("x",e,t,n),filter:N("filter",e,t,n),strides:[a[1],a[2]],pad:r,dataFormat:s,dilations:[i[1],i[2]],bias:o,activation:u,preluActivationWeights:l,leakyreluAlpha:d})]}case"FusedDepthwiseConv2dNative":{let{stride:a,pad:r,dataFormat:s,dilations:i,biasArg:o,preluArg:l,activationFunc:u,leakyreluAlpha:d}=c9(e,t,n);return[eo.depthwiseConv2d({x:N("x",e,t,n),filter:N("filter",e,t,n),strides:[a[1],a[2]],pad:r,dataFormat:s,dilations:[i[1],i[2]],bias:o,activation:u,preluActivationWeights:l,leakyreluAlpha:d})]}case"Conv2DBackpropInput":case"Conv2dTranspose":{let a=N("outputShape",e,t,n),r=N("strides",e,t,n),s=I0(e,t,n);return[zA(N("x",e,t,n),N("filter",e,t,n),a,[r[1],r[2]],s)]}case"DepthwiseConv2dNative":case"DepthwiseConv2d":{let a=N("strides",e,t,n),r=I0(e,t,n),s=N("dilations",e,t,n),i=N("dataFormat",e,t,n).toUpperCase();return[Nh(N("input",e,t,n),N("filter",e,t,n),[a[1],a[2]],r,i,[s[1],s[2]])]}case"Conv3D":{let a=N("strides",e,t,n),r=N("pad",e,t,n),s=N("dataFormat",e,t,n).toUpperCase(),i=N("dilations",e,t,n);return[n8(N("x",e,t,n),N("filter",e,t,n),[a[1],a[2],a[3]],r,s,[i[1],i[2],i[3]])]}case"AvgPool":{let a=N("strides",e,t,n),r=N("pad",e,t,n),s=N("kernelSize",e,t,n);return[Sf(N("x",e,t,n),[s[1],s[2]],[a[1],a[2]],r)]}case"MaxPool":{let a=N("strides",e,t,n),r=N("pad",e,t,n),s=N("kernelSize",e,t,n);return[Mf(N("x",e,t,n),[s[1],s[2]],[a[1],a[2]],r)]}case"MaxPoolWithArgmax":{let a=N("strides",e,t,n),r=N("pad",e,t,n),s=N("kernelSize",e,t,n),i=N("includeBatchInIndex",e,t,n),{result:o,indexes:l}=sK(N("x",e,t,n),[s[1],s[2]],[a[1],a[2]],r,i);return[o,l]}case"AvgPool3D":{let a=N("strides",e,t,n),r=N("pad",e,t,n),s=N("kernelSize",e,t,n);return[Q4(N("x",e,t,n),[s[1],s[2],s[3]],[a[1],a[2],a[3]],r)]}case"MaxPool3D":{let a=N("strides",e,t,n),r=N("pad",e,t,n),s=N("kernelSize",e,t,n);return[g8(N("x",e,t,n),[s[1],s[2],s[3]],[a[1],a[2],a[3]],r)]}case"Dilation2D":{let a=N("strides",e,t,n),r=N("pad",e,t,n),s=N("dilations",e,t,n),i=a[1],o=a[2],l=s[1],u=s[2];return[s8(N("x",e,t,n),N("filter",e,t,n),[i,o],r,[l,u],"NHWC")]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},pre=(e,t,n)=>{switch(e.op){case"Fill":{let a=N("shape",e,t,n),r=N("dtype",e,t,n),s=N("value",e,t,n);return[Eh(a,s,r)]}case"LinSpace":{let a=N("start",e,t,n),r=N("stop",e,t,n),s=N("num",e,t,n);return[Dq(a,r,s)]}case"Multinomial":{let a=N("logits",e,t,n),r=N("numSamples",e,t,n),s=N("seed",e,t,n);return[gK(a,r,s)]}case"OneHot":{let a=N("indices",e,t,n),r=N("depth",e,t,n),s=N("onValue",e,t,n),i=N("offValue",e,t,n);return[kh(a,r,s,i)]}case"Ones":return[os(N("shape",e,t,n),N("dtype",e,t,n))];case"OnesLike":return[$a(N("x",e,t,n))];case"RandomUniform":return[Rh(N("shape",e,t,n),N("minval",e,t,n),N("maxval",e,t,n),N("dtype",e,t,n))];case"Range":{let a=N("start",e,t,n),r=N("stop",e,t,n),s=N("step",e,t,n);return[Fh(a,r,s,N("dtype",e,t,n))]}case"TruncatedNormal":{let a=N("shape",e,t,n),r=N("mean",e,t,n),s=N("stdDev",e,t,n),i=N("seed",e,t,n);return[l2(a,r,s,N("dtype",e,t,n),i)]}case"Zeros":return[un(N("shape",e,t,n),N("dtype",e,t,n))];case"ZerosLike":return[at(N("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function S5(e,t,n){let a=N("boxes",e,t,n),r=N("scores",e,t,n),s=N("maxOutputSize",e,t,n),i=N("iouThreshold",e,t,n),o=N("scoreThreshold",e,t,n),l=N("softNmsSigma",e,t,n);return{boxes:a,scores:r,maxOutputSize:s,iouThreshold:i,scoreThreshold:o,softNmsSigma:l}}var cre=async(e,t,n)=>{switch(e.op){case"NonMaxSuppressionV5":{let{boxes:a,scores:r,maxOutputSize:s,iouThreshold:i,scoreThreshold:o,softNmsSigma:l}=S5(e,t,n),u=await to.nonMaxSuppressionWithScoreAsync(a,r,s,i,o,l);return[u.selectedIndices,u.selectedScores]}case"NonMaxSuppressionV4":{let{boxes:a,scores:r,maxOutputSize:s,iouThreshold:i,scoreThreshold:o}=S5(e,t,n),l=N("padToMaxOutputSize",e,t,n),u=await to.nonMaxSuppressionPaddedAsync(a,r,s,i,o,l);return[u.selectedIndices,u.validOutputs]}case"NonMaxSuppressionV3":case"NonMaxSuppressionV2":{let{boxes:a,scores:r,maxOutputSize:s,iouThreshold:i,scoreThreshold:o}=S5(e,t,n);return[await to.nonMaxSuppressionAsync(a,r,s,i,o)]}case"Where":{let a=we(N("condition",e,t,n),"bool"),r=[await EX(a)];return a.dispose(),r}case"ListDiff":return eX(N("x",e,t,n),N("y",e,t,n));default:throw TypeError(`Node type ${e.op} is not implemented`)}},fre=(e,t,n)=>{switch(e.op){case"TopKV2":{let a=N("x",e,t,n),r=N("k",e,t,n),s=N("sorted",e,t,n),i=N8(a,r,s);return[i.values,i.indices]}case"Unique":{let a=N("x",e,t,n),r=u2(a);return[r.values,r.indices]}case"UniqueV2":{let a=N("x",e,t,n),r=N("axis",e,t,n),s=u2(a,r);return[s.values,s.indices]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},mre=(e,t,n)=>{switch(e.op){case"Const":return t[e.name];case"PlaceholderWithDefault":let a=N("default",e,t,n);return[Ln(e.name,t,n)||a];case"Placeholder":return[Ln(e.name,t,n)];case"Identity":case"StopGradient":case"FakeQuantWithMinMaxVars":{let u=N("x",e,t,n);return[ms(u)]}case"IdentityN":return N("x",e,t,n).map(u=>ms(u));case"Snapshot":let r=N("x",e,t,n);return[ms(r)];case"Shape":return[$n(N("x",e,t,n).shape,"int32")];case"ShapeN":return N("x",e,t,n).map(u=>$n(u.shape));case"Size":return[Re(N("x",e,t,n).size,"int32")];case"Rank":return[Re(N("x",e,t,n).rank,"int32")];case"NoOp":return[Re(1)];case"Print":let s=N("x",e,t,n),i=N("data",e,t,n),o=N("message",e,t,n),l=N("summarize",e,t,n);console.warn("The graph has a tf.print() operation,usually used for debugging, which slows down performance."),console.log(o);for(let u=0;ue.dispose()),this.tensorMap.clear(),this.handle.dispose()}size(){return this.tensorMap.size}tensorSize(){return Re(this.size(),"int32")}async import(e,t){this.checkKeyAndValueTensor(e,t);let n=await e.data();return this.tensorMap.forEach(a=>a.dispose()),this.tensorMap.clear(),Z(()=>{let a=or(t),r=n.length,s=a.length;k.assert(r===s,()=>`The number of elements doesn't match, keys has ${r} elements, the values has ${s} elements.`);for(let i=0;i{let a=[];for(let r=0;r{switch(e.op){case"HashTable":case"HashTableV2":{let r=N("keyDType",e,t,n),s=N("valueDType",e,t,n),i=new gre(r,s);return a.addHashTable(e.name,i),[i.handle]}case"LookupTableImport":case"LookupTableImportV2":{let r=N("tableHandle",e,t,n,a),s=N("keys",e,t,n),i=N("values",e,t,n);return[await a.getHashTableById(r.id).import(s,i)]}case"LookupTableFind":case"LookupTableFindV2":{let r=N("tableHandle",e,t,n,a),s=N("keys",e,t,n),i=N("defaultValue",e,t,n);return[await a.getHashTableById(r.id).find(s,i)]}case"LookupTableSize":case"LookupTableSizeV2":{let r=N("tableHandle",e,t,n,a);return[a.getHashTableById(r.id).tensorSize()]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Are=(e,t,n)=>{switch(e.op){case"ResizeBilinear":{let a=N("images",e,t,n),r=N("size",e,t,n),s=N("alignCorners",e,t,n),i=N("halfPixelCenters",e,t,n);return[to.resizeBilinear(a,[r[0],r[1]],s,i)]}case"ResizeNearestNeighbor":{let a=N("images",e,t,n),r=N("size",e,t,n),s=N("alignCorners",e,t,n),i=N("halfPixelCenters",e,t,n);return[to.resizeNearestNeighbor(a,[r[0],r[1]],s,i)]}case"CropAndResize":{let a=N("image",e,t,n),r=N("boxes",e,t,n),s=N("boxInd",e,t,n),i=N("cropSize",e,t,n),o=N("method",e,t,n),l=N("extrapolationValue",e,t,n);return[to.cropAndResize(a,r,s,i,o,l)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},xre=(e,t,n)=>{switch(e.op){case"Equal":return[Xi(N("a",e,t,n),N("b",e,t,n))];case"NotEqual":return[Yl(N("a",e,t,n),N("b",e,t,n))];case"Greater":return[Ca(N("a",e,t,n),N("b",e,t,n))];case"GreaterEqual":return[Yi(N("a",e,t,n),N("b",e,t,n))];case"Less":return[BA(N("a",e,t,n),N("b",e,t,n))];case"LessEqual":return[Ji(N("a",e,t,n),N("b",e,t,n))];case"LogicalAnd":return[ir(N("a",e,t,n),N("b",e,t,n))];case"LogicalNot":return[Cf(N("a",e,t,n))];case"LogicalOr":return[GA(N("a",e,t,n),N("b",e,t,n))];case"Select":case"SelectV2":return[Pn(N("condition",e,t,n),N("a",e,t,n),N("b",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},bre=(e,t,n)=>{switch(e.op){case"BatchMatMul":case"BatchMatMulV2":case"MatMul":return[it(N("a",e,t,n),N("b",e,t,n),N("transposeA",e,t,n),N("transposeB",e,t,n))];case"Einsum":return[fq(N("equation",e,t,n),...N("tensors",e,t,n))];case"Transpose":return[ct(N("x",e,t,n),N("perm",e,t,n))];case"_FusedMatMul":let[a,r]=N("fusedOps",e,t,n),s=a==="biasadd",i=r==="prelu",o=N("numArgs",e,t,n),l=N("leakyreluAlpha",e,t,n);if(s){if(i&&o!==2)throw new Error("Fused MatMul with BiasAdd and Prelu must have two extra arguments: bias and alpha.");if(!i&&o!==1)throw new Error("Fused MatMul with BiasAdd must have one extra argument: bias.")}let[u,d]=N("args",e,t,n);return[eo.matMul({a:N("a",e,t,n),b:N("b",e,t,n),transposeA:N("transposeA",e,t,n),transposeB:N("transposeB",e,t,n),bias:u,activation:r,preluActivationWeights:d,leakyreluAlpha:l})];default:throw TypeError(`Node type ${e.op} is not implemented`)}},vre=(e,t,n)=>{switch(e.op){case"FusedBatchNorm":case"FusedBatchNormV2":return[Xl(N("x",e,t,n),N("mean",e,t,n),N("variance",e,t,n),N("offset",e,t,n),N("scale",e,t,n),N("epsilon",e,t,n))];case"FusedBatchNormV3":return[Xl(N("x",e,t,n),N("mean",e,t,n),N("variance",e,t,n),N("offset",e,t,n),N("scale",e,t,n),N("epsilon",e,t,n))];case"LRN":return[h8(N("x",e,t,n),N("radius",e,t,n),N("bias",e,t,n),N("alpha",e,t,n),N("beta",e,t,n))];case"Softmax":return[_f(N("x",e,t,n))];case"LogSoftmax":return[UA(N("x",e,t,n))];case"SparseToDense":return[M8(N("sparseIndices",e,t,n),N("outputShape",e,t,n),N("sparseValues",e,t,n),N("defaultValue",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},wre=(e,t,n)=>{switch(e.op){case"Max":{let i=N("axis",e,t,n),o=N("keepDims",e,t,n);return[sr(N("x",e,t,n),i,o)]}case"Mean":{let i=N("axis",e,t,n),o=N("keepDims",e,t,n);return[Xt(N("x",e,t,n),i,o)]}case"Min":{let i=N("axis",e,t,n),o=N("keepDims",e,t,n);return[$f(N("x",e,t,n),i,o)]}case"Sum":{let i=N("axis",e,t,n),o=N("keepDims",e,t,n);return[Ce(N("x",e,t,n),i,o)]}case"All":{let i=N("axis",e,t,n),o=N("keepDims",e,t,n);return[RA(N("x",e,t,n),i,o)]}case"Any":{let i=N("axis",e,t,n),o=N("keepDims",e,t,n);return[wf(N("x",e,t,n),i,o)]}case"ArgMax":{let i=N("axis",e,t,n);return[kf(N("x",e,t,n),i)]}case"ArgMin":{let i=N("axis",e,t,n);return[j4(N("x",e,t,n),i)]}case"Prod":{let i=N("axis",e,t,n),o=N("keepDims",e,t,n);return[KA(N("x",e,t,n),i,o)]}case"Cumsum":{let i=N("axis",e,t,n),o=N("exclusive",e,t,n),l=N("reverse",e,t,n);return[LA(N("x",e,t,n),i,o,l)]}case"Bincount":let a=N("x",e,t,n),r=N("weights",e,t,n),s=N("size",e,t,n);return[e8(a,r,s)];case"DenseBincount":{let i=N("x",e,t,n),o=N("weights",e,t,n),l=N("size",e,t,n),u=N("binaryOutput",e,t,n);return[tq(i,o,l,u)]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},kre=(e,t,n)=>{switch(e.op){case"ConcatV2":case"Concat":{let a=N("n",e,t,n),r=N("axis",e,t,n),s=N("tensors",e,t,n);return s=s.slice(0,a),[en(s,r)]}case"Gather":{let a=N("x",e,t,n),r=N("indices",e,t,n);return[Mh(a,we(r,"int32"),0)]}case"GatherV2":{let a=N("axis",e,t,n),r=N("batchDims",e,t,n),s=N("x",e,t,n),i=N("indices",e,t,n);return[Mh(s,we(i,"int32"),a,r)]}case"Reverse":{let a=N("dims",e,t,n),r=[];for(let i=0;i{let a=N("axis",e,t,n),r=N("tensors",e,t,n),s=r[0].shape,i=Jl(r[0]).shape,o=r.map(l=>{let u=k.arraysEqual(l.shape,s);if(!u&&!k.arraysEqual(Jl(l).shape,i))throw new Error("the input tensors shape does not match");return u?l:Y(l,s)});return[Fa(o,a)]});case"Unpack":{let a=N("axis",e,t,n),r=N("tensor",e,t,n);return or(r,a)}case"Tile":{let a=N("reps",e,t,n);return[Zi(N("x",e,t,n),a)]}case"Split":case"SplitV":{let a=N("axis",e,t,n),r=N("numOrSizeSplits",e,t,n),s=N("x",e,t,n);return da(s,r,a)}case"ScatterNd":{let a=N("indices",e,t,n),r=N("values",e,t,n),s=N("shape",e,t,n);return[RX(a,r,s)]}case"GatherNd":{let a=N("x",e,t,n),r=N("indices",e,t,n);return[_X(a,r)]}case"SparseToDense":{let a=N("sparseIndices",e,t,n),r=N("outputShape",e,t,n),s=N("sparseValues",e,t,n),i=N("defaultValue",e,t,n);return[M8(a,s,r,s.dtype===i.dtype?i:we(i,s.dtype))]}default:throw TypeError(`Node type ${e.op} is not implemented`)}},Ire=(e,t,n)=>{switch(e.op){case"SparseFillEmptyRows":{let{outputIndices:a,outputValues:r,emptyRowIndicator:s,reverseIndexMap:i}=Vf.sparseFillEmptyRows(N("indices",e,t,n),N("values",e,t,n),N("denseShape",e,t,n),N("defaultValue",e,t,n));return[a,r,s,i]}case"SparseReshape":{let{outputIndices:a,outputShape:r}=Vf.sparseReshape(N("inputIndices",e,t,n),N("inputShape",e,t,n),N("newShape",e,t,n));return[a,r]}case"SparseSegmentMean":return[Vf.sparseSegmentMean(N("data",e,t,n),N("indices",e,t,n),N("segmentIds",e,t,n))];case"SparseSegmentSum":return[Vf.sparseSegmentSum(N("data",e,t,n),N("indices",e,t,n),N("segmentIds",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Sre=(e,t,n)=>{switch(e.op){case"FFT":return[s2(N("x",e,t,n))];case"IFFT":return[zf(N("x",e,t,n))];case"RFFT":return[i2(N("x",e,t,n))];case"IRFFT":return[k8(N("x",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Nre=(e,t,n)=>{switch(e.op){case"StringNGrams":{let{nGrams:a,nGramsSplits:r}=c2.stringNGrams(N("data",e,t,n),N("dataSplits",e,t,n),N("separator",e,t,n),N("nGramWidths",e,t,n),N("leftPad",e,t,n),N("rightPad",e,t,n),N("padWidth",e,t,n),N("preserveShortSequences",e,t,n));return[a,r]}case"StringSplit":{let{indices:a,values:r,shape:s}=c2.stringSplit(N("input",e,t,n),N("delimiter",e,t,n),N("skipEmpty",e,t,n));return[a,r,s]}case"StringToHashBucketFast":return[c2.stringToHashBucketFast(N("input",e,t,n),N("numBuckets",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}},Tre=(e,t,n)=>{switch(e.op){case"Cast":return[we(N("x",e,t,n),N("dtype",e,t,n))];case"ExpandDims":{let a=N("axis",e,t,n);return[Ea(N("x",e,t,n),a)]}case"Squeeze":{let a=N("axis",e,t,n);return[Jl(N("x",e,t,n),a)]}case"Reshape":return[Y(N("x",e,t,n),N("shape",e,t,n))];case"MirrorPad":return[y8(N("x",e,t,n),N("padding",e,t,n),N("mode",e,t,n))];case"PadV2":case"Pad":return[Bs(N("x",e,t,n),N("padding",e,t,n),N("constantValue",e,t,n))];case"SpaceToBatchND":{let a=N("blockShape",e,t,n),r=N("paddings",e,t,n);return[Rf(N("x",e,t,n),a,r)]}case"BatchToSpaceND":{let a=N("blockShape",e,t,n),r=N("crops",e,t,n);return[Nf(N("x",e,t,n),a,r)]}case"DepthToSpace":{let a=N("blockSize",e,t,n),r=N("dataFormat",e,t,n).toUpperCase();return[r8(N("x",e,t,n),a,r)]}case"BroadcastTo":return[Sh(N("x",e,t,n),N("shape",e,t,n))];default:throw TypeError(`Node type ${e.op} is not implemented`)}};function f9(e,t,n,a){let r=((s,i,o)=>{switch(s.category){case"arithmetic":return Z(()=>are(s,i,o));case"basic_math":return Z(()=>rre(s,i,o));case"control":return dre(s,i,o);case"convolution":return Z(()=>hre(s,i,o));case"creation":return Z(()=>pre(s,i,o));case"dynamic":return cre(s,i,o);case"evaluation":return Z(()=>fre(s,i,o));case"image":return Z(()=>Are(s,i,o));case"graph":return Z(()=>mre(s,i,o));case"logical":return Z(()=>xre(s,i,o));case"matrices":return Z(()=>bre(s,i,o));case"normalization":return Z(()=>vre(s,i,o));case"reduction":return Z(()=>wre(s,i,o));case"slice_join":return Z(()=>kre(s,i,o));case"sparse":return Z(()=>Ire(s,i,o));case"spectral":return Z(()=>Sre(s,i,o));case"string":return Z(()=>Nre(s,i,o));case"transformation":return Z(()=>Tre(s,i,o));case"hash_table":return yre(s,i,o,a);case"custom":let l=VS(s.op);if(l&&l.customExecutor)return l.customExecutor(new nre(s,i,o));throw TypeError(`Custom op ${s.op} is not registered.`);default:throw TypeError(`Unknown op '${s.op}'. File an issue at https://github.com/tensorflow/tfjs/issues so we can add it, or register a custom execution with tf.registerOp()`)}})(e,t,n);return k.isPromise(r)?r.then(s=>[].concat(s)):[].concat(r)}var m9=class{constructor(e={},t={},n={},a={}){this.weightMap=e,this.tensorArrayMap=t,this.tensorListMap=n,this.functionMap=a,this.rootContext={id:0,frameName:"",iterationId:0},this.contexts=[this.rootContext],this.lastId=0,this.generateCurrentContextIds()}newFrame(e,t){return{id:e,frameName:t,iterationId:0}}set currentContext(e){this.contexts!==e&&(this.contexts=e,this.generateCurrentContextIds())}get currentContext(){return this.contexts}get currentContextId(){return this._currentContextIds[0]}get currentContextIds(){return this._currentContextIds}generateCurrentContextIds(){let e=[];for(let t=0;tt.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 g9(e,t,n,a){let r=new Set,s=[],i=null,o=null,l=new Set,u=Object.keys(e).map(p=>ha(p)[0]),d=[];a!=null&&(d=a.map(p=>ha(p.name)[0]));let h=[...t];for(;h.length>0;){let p=h.pop();if((y9(p)||Rre(p)||Fre(p))&&i==null&&(i=p,o=i.children.map(c=>c.name).filter(c=>r.has(c))),r.add(p.name),n[p.name]==null&&u.indexOf(p.name)===-1&&d.indexOf(p.name)===-1){if(p.inputs.length===0){s.push(p.name);continue}p.inputs.forEach(c=>{l.has(c.name)||(l.add(c.name),h.push(c))})}}return{inputs:e,outputs:t,usedNodes:r,missingInputs:s,dynamicNode:i,syncInputs:o}}function Ere(e,t,n){let{usedNodes:a,inputs:r}=n,s=[],i=Object.keys(r).map(d=>ha(d)[0]).map(d=>e.nodes[d]),o=e.initNodes;i.forEach(d=>{a.has(d.name)&&s.push(d)}),e.weights.forEach(d=>{a.has(d.name)&&s.push(d)}),o!=null&&o.forEach(d=>{a.has(d.name)&&s.push(d)});let l=new Set,u=[];for(;s.length>0;){let d=s.pop();l.add(d.name),t[d.name]||u.push(d),d.children.forEach(h=>{!l.has(h.name)&&a.has(h.name)&&h.inputs.every(p=>l.has(p.name))&&s.push(h)})}return u}var Cre=["Switch","Merge","Enter","Exit","NextIteration","StatelessIf","StatelessWhile","if","While"],Mre=["NonMaxSuppressionV2","NonMaxSuppressionV3","NonMaxSuppressionV5","Where"],$re=["HashTable","HashTableV2","LookupTableImport","LookupTableImportV2","LookupTableFind","LookupTableFindV2","LookupTableSize","LookupTableSizeV2"];function y9(e){return Cre.indexOf(e.op)>=0}function Rre(e){return Mre.indexOf(e.op)>=0}function Fre(e){return $re.indexOf(e.op)>=0}var N5=class{constructor(e,t){this.graph=e,this.parent=t,this.compiledMap=new Map,this._weightMap={},this.SEPERATOR=",",this._functions={},this._functionExecutorMap={},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 N5(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(a=>a.id));this._weightIds=[].concat(...t),this._weightMap=e}set resourceManager(e){this._resourceManager=e}get inputs(){return this._inputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get outputs(){return this._outputs.map(e=>({name:e.name,shape:e.attrParams.shape?e.attrParams.shape.value:void 0,dtype:e.attrParams.dtype?e.attrParams.dtype.value:void 0}))}get inputNodes(){return this._inputs.map(e=>e.signatureKey||e.name)}get outputNodes(){return this._outputs.map(e=>{let t=e.signatureKey||e.name;return e.defaultOutput?`${t}:${e.defaultOutput}`:t})}get functions(){return Object.keys(this._functions).reduce((e,t)=>(e[t]=this._functions[t].signature,e),{})}getCompilationKey(e,t){let n=e.map(r=>r.name).sort(),a=t.map(r=>r.name).sort();return n.join(this.SEPERATOR)+"--"+a.join(this.SEPERATOR)}compile(e,t){let n=g9(e,t,this.weightMap,this._initNodes),{missingInputs:a,dynamicNode:r,syncInputs:s}=n;if(r!=null)throw new Error(`This execution contains the node '${r.name}', which has the dynamic op '${r.op}'. Please use model.executeAsync() instead. Alternatively, to avoid the dynamic ops, specify the inputs [${s}]`);if(a.length>0){let i=t.map(l=>l.name),o=Object.keys(e);throw new Error(`Cannot compute the outputs [${i}] from the provided inputs [${o}]. Missing the following inputs: [${a}]`)}return Ere(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 a=n.map(d=>this.graph.nodes[ha(d)[0]]),r=t.map(d=>ha(d)[0]),s=r.map(d=>this.graph.nodes[d]);s.length===0&&(s=this._outputs);let i=this.getCompilationKey(a,s),o=this.compiledMap.get(i);o==null&&(o=this.compile(e,s),this.compiledMap.set(i,o));let l={},u={};return Z(()=>{let d=new m9(this.weightMap,l,u,this.functionExecutorMap),h={...this.weightMap};Object.keys(e).forEach(m=>{let[f,g]=ha(m),y=[];y[g]=e[m],h[f]=y});let p=this.getFrozenTensorIds(h),c={};for(let m=0;mLn(m,h,d))})}getFrozenTensorIds(e){let t=[].concat.apply([],Object.keys(e).map(n=>e[n]).map(n=>n.map(a=>a.id)));return new Set(t)}checkTensorForDisposal(e,t,n,a,r,s,i){t.category==="control"||s.indexOf(e)!==-1||(n[e].forEach(o=>{o!=null&&(i[o.id]=(i[o.id]||0)+t.children.length)}),t.inputs.forEach(o=>{if(o.category!=="control"){let l=Dae(o.name,n,a);l!=null&&l.forEach(u=>{if(u&&!u.kept&&!r.has(u.id)){let d=i[u.id];d===1?(u.dispose(),delete i[u.id]):d!=null&&i[u.id]--}})}}))}async executeAsync(e,t){return this._executeAsync(e,t)}async _executeAsync(e,t,n=!1,a={},r={}){n||(e=this.mapInputs(e),this.checkInputs(e),this.checkInputShapeAndType(e),t=this.mapOutputs(t),this.checkOutputs(t));let s=new m9(this.weightMap,a,r,this.functionExecutorMap),i=await this.executeWithControlFlow(e,s,t,n),o=t.map(h=>Ln(h,i,s)),l=o.map(h=>h.id),u=Object.keys(e).map(h=>e[h].id),d=new Set([...l,...u,...this.weightIds]);return Object.keys(i).forEach(h=>{i[h].forEach(p=>{p&&!p.kept&&!p.isDisposed&&!d.has(p.id)&&p.dispose()})}),this.parent==null&&s.dispose(d),o}async executeFunctionAsync(e,t,n){let a=e.reduce((r,s,i)=>(r[this.inputs[i].name]=s,r),{});return this._executeAsync(a,this.outputNodes,!0,t,n)}async executeWithControlFlow(e,t,n,a){let r=Object.keys(e),s=r.map(A=>this.graph.nodes[ha(A)[0]]),i=n.map(A=>ha(A)[0]),o=i.map(A=>this.graph.nodes[A]);o.length===0&&(o=this._outputs);let{usedNodes:l,missingInputs:u,dynamicNode:d,syncInputs:h}=g9(e,o,this.weightMap,this._initNodes),p=[...s,...this.graph.weights,...this._initNodes||[]].map(A=>({node:A,contexts:t.currentContext})),c={...this.weightMap};Object.keys(e).forEach(A=>{let[x,v]=ha(A),b=[];b[v]=e[A],c[x]=b});let m={},f=this.getFrozenTensorIds(c),g={};for(;p.length>0;){let A=this.processStack(s,p,t,c,g,f,i,m,l);await Promise.all(A)}d==null&&!a&&console.warn("This model execution did not contain any nodes with control flow or dynamic output shapes. You can use model.execute() instead.");let y=o.filter(A=>!y9(A)&&!Ln(A.name,c,t)).map(A=>A.name);if(y.length>0){let A="";throw d!=null&&(A=`Alternatively, to avoid the dynamic ops, use model.execute() and specify the inputs [${h}]`),new Error(`Cannot compute the outputs [${y}] from the provided inputs [${r}]. Consider providing the following inputs: [${u}]. ${A}`)}return c}processStack(e,t,n,a,r,s,i,o,l){let u=[];for(;t.length>0;){let d=t.pop();n.currentContext=d.contexts;let h="";if(d.node.op==="Enter"&&N("isConstant",d.node,a,n)&&([h]=fs(d.node.name,n)),a[d.node.name]==null){let p=f9(d.node,a,n,this._resourceManager);h||([h]=fs(d.node.name,n));let c=n.currentContext;k.isPromise(p)?u.push(p.then(m=>(a[h]=m,n.currentContext=c,this.checkTensorForDisposal(h,d.node,a,n,s,i,o),this.processChildNodes(d.node,t,n,a,r,l),m))):(a[h]=p,this.checkTensorForDisposal(h,d.node,a,n,s,i,o),this.processChildNodes(d.node,t,n,a,r,l))}else this.processChildNodes(d.node,t,n,a,r,l)}return u}processChildNodes(e,t,n,a,r,s){e.children.forEach(i=>{let[o]=fs(i.name,n);r[o]||!s.has(i.name)||(i.op==="Merge"?i.inputNames.some(l=>!!Ln(l,a,n))&&(r[o]=!0,t.push({contexts:n.currentContext,node:i})):i.inputNames.every(l=>!!Ln(l,a,n))&&(r[o]=!0,t.push({contexts:n.currentContext,node:i})))})}dispose(){Object.keys(this.weightMap).forEach(e=>this.weightMap[e].forEach(t=>t.dispose()))}checkInputShapeAndType(e){Object.keys(e).forEach(t=>{let n=e[t],[a]=ha(t),r=this.graph.nodes[a];if(r.attrParams.shape&&r.attrParams.shape.value){let s=r.attrParams.shape.value,i=s.length===n.shape.length&&n.shape.every((o,l)=>s[l]===-1||s[l]===o);k.assert(i,()=>`The shape of dict['${r.name}'] provided in model.execute(dict) must be [${s}], but was [${n.shape}]`)}r.attrParams.dtype&&r.attrParams.dtype.value&&k.assert(n.dtype===r.attrParams.dtype.value,()=>`The dtype of dict['${r.name}'] provided in model.execute(dict) must be ${r.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 a=this._signature.inputs[n];t[a.name]=e[n]}else t[n]=e[n];return t}checkInputs(e){let t=Object.keys(e).filter(n=>{let[a]=ha(n);return this.graph.nodes[a]==null});if(t.length>0)throw new Error(`The dict provided in model.execute(dict) has keys: [${t}] that are not part of graph`)}mapOutputs(e){return e.map(t=>this._signature!=null&&this._signature.outputs!=null&&this._signature.outputs[t]!=null?this._signature.outputs[t].name:t,{})}checkOutputs(e){e.forEach(t=>{let[n]=ha(t);if(!this.graph.nodes[n])throw new Error(`The output '${t}' is not found in the graph`)})}},Ore=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]}},Dre="?tfjs-format=file",_re="model.json",A9=class{constructor(e,t={}){this.modelUrl=e,this.loadOptions=t,this.version="n/a",t==null&&(this.loadOptions={}),this.resourceManager=new Ore}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=la.browserHTTPRequest(e,this.loadOptions);else{let t=la.getLoadHandlers(e,this.loadOptions);if(t.length===0)t.push(la.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 a=la.decodeWeights(this.artifacts.weightData,this.artifacts.weightSpecs);if(this.executor=new N5(l9.Instance.transformGraph(t,this.signature)),this.executor.weightMap=this.convertTensorMapToTensorsMap(a),this.executor.resourceManager=this.resourceManager,e.modelInitializer!=null&&e.modelInitializer.node!=null){let r=l9.Instance.transformGraph(e.modelInitializer);this.initializer=new N5(r),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=la.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 Tt)&&!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,a)=>(t[n]=e[a],t),{})}normalizeOutputs(e){return e=e||this.outputNodes,Array.isArray(e)?e:[e]}execute(e,t){e=this.normalizeInputs(e),t=this.normalizeOutputs(t);let 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]}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 Et(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}${_re}${Dre}`);let n=new A9(e,t);return await n.load(),n}var zre="3.7.0",x9={};$e(x9,{CSVDataset:()=>F9,Dataset:()=>uu,FileDataSource:()=>W9,TextLineDataset:()=>M9,URLDataSource:()=>B9,array:()=>ise,csv:()=>yse,func:()=>Ase,generator:()=>xse,microphone:()=>vse,version_data:()=>wse,webcam:()=>bse,zip:()=>ose});var Pre=qr(P3()),Lre=qr(P3());function Wre(e,t){return S0(e,t)}function S0(e,t,n=new Map,a=new Set){if(e==null)return null;if(a.has(e))throw new Error("Circular references are not supported.");if(n.has(e))return n.get(e);let r=t(e);if(r.recurse&&r.value!==null)throw new Error("A deep map function may not return both a value and recurse=true.");if(r.recurse)if(lu(e)){let s=Array.isArray(e)?[]:{};a.add(e);for(let i in e){let o=e[i],l=S0(o,t,n,a);s[i]=l}return a.delete(e),s}else throw new Error(`Can't recurse into non-iterable type: ${e}`);else return n.set(e,r.value),r.value}function Bre(e,t=v9){return b9(e,t)}function b9(e,t,n=new Set){let a=e[0];if(n.has(a))throw new Error("Circular references are not supported.");let r=t(e);if(r.recurse&&r.value!==null)throw new Error("A deep zip function may not return both a value and recurse=true.");if(r.recurse)if(lu(a)){let s=Array.isArray(a)?[]:{};n.add(a);for(let i in a){let o=e.map(u=>u[i]),l=b9(o,t,n);s[i]=l}return n.delete(a),s}else throw new Error(`Can't recurse into non-iterable type: ${a}`);else return r.value}function v9(e){return e===null?null:lu(e[0])?{value:null,recurse:!0}:{value:e,recurse:!1}}async function w9(e,t){let n=new Map;S0(e,t,n);for(let a of Array.from(n.keys())){let r=n.get(a);if(k.isPromise(r)){let s=await r;n.set(a,s)}}return S0(e,t,n)}function lu(e){return e!=null&&!ArrayBuffer.isView(e)&&(Array.isArray(e)||typeof e=="object"&&!(e instanceof Tt))}function Vre(e){return e==null||Ure(e)||Array.isArray(e)||typeof e=="object"&&e instanceof Tt||k.isTypedArray(e)}function Ure(e){return e===null||typeof e!="object"&&typeof e!="function"}function jre(e){return Wre(e,Hre)}function Hre(e){return e instanceof Tt?{value:e.clone(),recurse:!1}:lu(e)?{value:null,recurse:!0}:{value:e,recurse:!1}}var k9=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}},I9=class extends k9{constructor(){super(I9.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 a=0;at===!0)}rowMajorBatch(e,t=!0){return new Qre(this,e,t)}columnMajorBatch(e,t=!0,n=v9){return this.rowMajorBatch(e,t).map(a=>Bre(a,n))}concatenate(e,t){return new E9(N9([this,e]),t)}take(e){return e<0||e==null?this:new Jre(this,e)}skip(e){return e<0||e==null?this:new Yre(this,e)}prefetch(e){return new C9(this,e)}shuffle(e,t){return new sse(this,e,t)}serial(){return new Zre(this)}},Kre=class extends xn{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:jre(e),done:!1}}},Xre=class extends xn{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}}},Zre=class extends xn{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()}},Yre=class extends xn{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++ Take`}async next(){return this.count++>=this.maxCount?{value:null,done:!0}:this.upstream.next()}},Qre=class extends xn{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.length0?{value:e,done:!1}:{value:null,done:!0};e.push(t.value)}return{value:e,done:!1}}},ese=class extends xn{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;Ge(e.value)}}},tse=class extends xn{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=Er.getTensorsInContainer(e.value),n=this.transform(e.value),a=Er.getTensorsInContainer(n);for(let r of t)Er.isTensorInList(r,a)||r.dispose();return{value:n,done:!1}}},nse=class extends xn{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}}}},T9=class extends xn{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=Er.getTensorsInContainer(e.value),n=await this.transform(e.value),a=Er.getTensorsInContainer(n);for(let r of t)Er.isTensorInList(r,a)||r.dispose();return{value:n,done:!1}}},E5=class extends xn{constructor(){super();this.outputQueue=new S9,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}}},ase=class extends E5{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=Er.getTensorsInContainer(e.value),n=this.transform(e.value),a=Er.getTensorsInContainer(n);this.outputQueue.pushAll(n);for(let r of t)Er.isTensorInList(r,a)||r.dispose();return!0}},E9=class extends xn{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}},N0;(function(e){e[e.FAIL=0]="FAIL",e[e.SHORTEST=1]="SHORTEST",e[e.LONGEST=2]="LONGEST"})(N0||(N0={}));var rse=class extends xn{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 a(s){return s instanceof xn?{value:s.next().then(i=>(t++,i.done&&n++,i.value)),recurse:!1}:{value:null,recurse:!0}}let r=await w9(this.iterators,a);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:r,done:!1}}async next(){return this.currentPromise=this.nextState(this.currentPromise),this.currentPromise}},C9=class extends xn{constructor(e,t){super();this.upstream=e,this.bufferSize=t,this.buffer=new k9(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()}},sse=class extends C9{constructor(e,t,n){super(e,t);this.upstream=e,this.windowSize=t,this.upstreamExhausted=!1,this.random=Lre.alea(n||k.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}}},uu=class{constructor(){this.size=null}batch(e,t=!0){let n=this;k.assert(e>0,()=>`batchSize needs to be positive, but it is ${e}`);let a;return this.size===Infinity||this.size==null?a=this.size:t?a=Math.ceil(this.size/e):a=Math.floor(this.size/e),pa(async()=>(await n.iterator()).columnMajorBatch(e,t,lse),a)}concatenate(e){let t=this,n;return this.size===Infinity||e.size===Infinity?n=Infinity:this.size!=null&&e.size!=null?n=this.size+e.size:n=null,pa(async()=>(await t.iterator()).concatenate(await e.iterator()),n)}filter(e){let t=this,n;return this.size===Infinity?n=Infinity:n=null,pa(async()=>(await t.iterator()).filter(a=>Z(()=>e(a))),n)}async forEachAsync(e){return(await this.iterator()).forEachAsync(e)}map(e){let t=this;return pa(async()=>(await t.iterator()).map(n=>Z(()=>e(n))),this.size)}mapAsync(e){let t=this;return pa(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 pa(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=Infinity:n=null,pa(async()=>{let a=T5(async()=>({value:await t.iterator(),done:!1}));return Gre(a.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(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 a=this,r=Pre.alea(t||k.now().toString());return pa(async()=>{let s=r.int32();return n&&(s+=r.int32()),(await a.iterator()).shuffle(e,s.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,pa(async()=>(await t.iterator()).take(e),n)}async toArray(){if(this.size===Infinity)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArray()}async toArrayForTest(){if(this.size===Infinity)throw new Error("Can not convert infinite data stream to array.");return(await this.iterator()).toArrayForTest()}};uu.MAX_BUFFER_SIZE=1e4;function pa(e,t=null){return new class extends uu{constructor(){super(...arguments);this.size=t}async iterator(){return e()}}}function ise(e){return pa(async()=>N9(e),e.length)}function ose(e){if(!lu(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{let n=await w9(e,a=>{if(a instanceof uu)return{value:a.iterator(),recurse:!1};if(lu(a))return{value:null,recurse:!0};throw new Error("Leaves of the structure passed to zip() must be Datasets, not primitives.")});return qre(n,N0.SHORTEST)},t)}function lse(e){if(e===null)return null;let t=e[0];return Vre(t)?{value:use(e),recurse:!1}:{value:null,recurse:!0}}function use(e){if(e.length===0)throw new Error("Can't make a batch of zero elements.");return e[0]instanceof Tt?Fa(e):Cr(e)}var M9=class extends uu{constructor(e){super();this.input=e}async iterator(){return(await this.input.iterator()).decodeUTF8().split(` `).map(e=>(e.endsWith("\r")&&(e=e.slice(0,-1)),e))}},T0='"',ep=Symbol("out"),$9=Symbol("field"),E0=Symbol("quote"),C5=Symbol("quoteafterquote"),R9=Symbol("quoteinquote"),F9=class extends uu{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 M9(e),t||(t={}),this.hasHeader=t.hasHeader!==!1,this.fullColumnNames=t.columnNames,this.columnConfigs=t.columnConfigs,this.configuredColumnsOnly=t.configuredColumnsOnly,t.delimWhitespace?(k.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&&k.assert(e.length===this.fullColumnNames.length,()=>"The length of provided columnNames ("+this.fullColumnNames.length.toString()+") does not match the length of the header line read from file ("+e.length.toString()+")."),this.fullColumnNames||(this.fullColumnNames=e);let t=this.fullColumnNames.reduce((a,r)=>(a[r]=a[r]+1||1,a),{}),n=Object.keys(t).filter(a=>t[a]>1);if(k.assert(n.length===0,()=>"Duplicate column names found: "+n.toString()),this.columnConfigs){for(let a of Object.keys(this.columnConfigs))if(this.fullColumnNames.indexOf(a)===-1)throw new Error('The key "'+a+'" provided in columnConfigs does not match any of the column names ('+this.fullColumnNames.toString()+").")}this.columnNamesValidated=!0}async maybeReadHeaderLine(){if(this.hasHeader){let e=await(await this.base.iterator()).next();if(e.done)throw new Error("No data was found for CSV parsing.");let t=e.value;return this.parseRow(t,!1)}else return null}async iterator(){this.columnNamesValidated||await this.setColumnNames();let e=await this.base.iterator();return this.hasHeader&&(e=e.skip(1)),e.map(t=>this.makeDataElement(t))}makeDataElement(e){let t=this.parseRow(e),n={},a={};for(let r=0;r14||!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(se().get("IS_NODE"))throw new Error("microphone API is only supported in browser environment.");let t=new O9(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 a=this.flattenQueue(n.freqDataQueue);e=this.getTensorFromAudioDataArray(a,[this.numFrames,this.columnTruncateLength,1])}if(this.includeWaveform){let a=this.flattenQueue(n.timeDataQueue);t=this.getTensorFromAudioDataArray(a,[this.numFrames*this.fftSize,1])}return{value:{spectrogram:e,waveform:t},done:!1}}async capture(){return(await this.next()).value}async getAudioData(){let e=[],t=[],n=0;return new Promise(a=>{let r=setInterval(()=>{this.includeSpectrogram&&(this.analyser.getFloatFrequencyData(this.freqData),this.freqData[0]===-Infinity&&a({freqDataQueue:e,timeDataQueue:t}),e.push(this.freqData.slice(0,this.columnTruncateLength))),this.includeWaveform&&(this.analyser.getFloatTimeDomainData(this.timeData),t.push(this.timeData.slice())),++n===this.numFrames&&(clearInterval(r),a({freqDataQueue:e,timeDataQueue:t}))},this.fftSize/this.sampleRateHz*1e3)})}stop(){this.isClosed||(this.isClosed=!0,this.analyser.disconnect(),this.audioContext.close(),this.stream!=null&&this.stream.getTracks().length>0&&this.stream.getTracks()[0].stop())}toArray(){throw new Error("Can not convert infinite audio stream to array.")}getSampleRate(){return this.sampleRateHz}flattenQueue(e){let t=e[0].length,n=new Float32Array(e.length*t);return e.forEach((a,r)=>n.set(a,r*t)),n}getTensorFromAudioDataArray(e,t){let n=new Float32Array(k.sizeFromShape(t));return n.set(e,n.length-e.length),Cr(n,t)}},D9=class extends xn{constructor(e,t){super();if(this.webcamVideoElement=e,this.webcamConfig=t,this.isClosed=!0,this.resize=!1,this.needToResize())if(this.resize=!0,this.cropSize=[this.webcamConfig.resizeHeight,this.webcamConfig.resizeWidth],this.cropBoxInd=$n([0],"int32"),this.webcamConfig.centerCrop){let n=this.webcamConfig.resizeWidth*1/this.webcamVideoElement.width,a=this.webcamConfig.resizeHeight*1/this.webcamVideoElement.height,r=(1-n)/2,s=(1-a)/2,i=r+n,o=a+s;this.cropBox=Ql([s,r,o,i],[1,4])}else this.cropBox=Ql([0,0,1,1],[1,4])}summary(){return"webcam"}static async create(e,t={}){if(se().get("IS_NODE"))throw new Error("tf.data.webcam is only supported in browser environment.");if(!e){if(e=document.createElement("video"),!t.resizeWidth||!t.resizeHeight)throw new Error("Please provide webcam video element, or resizeWidth and resizeHeight to create a hidden video element.");e.width=t.resizeWidth,e.height=t.resizeHeight}let n=new D9(e,t);return await n.start(),n}async start(){this.webcamConfig.facingMode&&k.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=k4.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 Z(()=>{let t=Ea(we(e,"float32"),0),n;n=to.cropAndResize(t,this.cropBox,this.cropBoxInd,this.cropSize,"bilinear");let a=n.shape;return Y(n,a.slice(1))})}async capture(){return(await this.next()).value}stop(){this.stream.getTracks().forEach(e=>e.stop());try{this.webcamVideoElement.srcObject=null}catch(e){console.log(e),this.webcamVideoElement.src=null}this.isClosed=!0}toArray(){throw new Error("Can not convert infinite video stream to array.")}},_9=class{},z9=class extends xn{split(e){return new dse(this,e)}},dse=class extends z9{constructor(e,t){super();this.upstream=e,this.impl=new hse(e,t)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},hse=class extends E5{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}},pse=class extends xn{decodeUTF8(){return new cse(this)}},cse=class extends z9{constructor(e){super();this.upstream=e,this.impl=new fse(e)}summary(){return this.impl.summary()}async next(){return this.impl.next()}},fse=class extends E5{constructor(e){super();if(this.upstream=e,se().get("IS_BROWSER"))this.decoder=new TextDecoder("utf-8");else{let{StringDecoder:t}=wR();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 se().get("IS_BROWSER")?n=this.decoder.decode(t,{stream:!0}):n=this.decoder.write(Buffer.from(t.buffer)),this.outputQueue.push(n),!0}},P9=class extends pse{constructor(e,t={}){super();this.file=e,this.options=t,k.assert(e instanceof Uint8Array||(se().get("IS_BROWSER")?e instanceof File||e instanceof Blob:!1),()=>"FileChunkIterator only supports File, Blob and Uint8Array right now."),this.offset=t.offset||0,this.chunkSize=t.chunkSize||1024*1024}summary(){return`FileChunks ${this.file}`}async next(){return this.offset>=(this.file instanceof Uint8Array?this.file.byteLength:this.file.size)?{value:null,done:!0}:{value:await new Promise((e,t)=>{let n=this.offset+this.chunkSize;if(this.file instanceof Uint8Array)e(new Uint8Array(this.file.slice(this.offset,n)));else{let a=new FileReader;a.onload=s=>{let i=a.result;if(i instanceof ArrayBuffer&&(i=new Uint8Array(i)),!(i instanceof Uint8Array))return t(new TypeError("FileReader returned unknown type."));e(i)},a.onabort=s=>t(new Error("Aborted")),a.onerror=s=>t(new Error(s.type));let r=this.file.slice(this.offset,n);a.readAsArrayBuffer(r)}this.offset=n}),done:!1}}};async function mse(e,t={}){let n,a;typeof e=="string"?n=e:(n=e.url,a=gse(e));let r=await k.fetch(n,a);if(r.ok){let s=new Uint8Array(await r.arrayBuffer());return new P9(s,t)}else throw new Error(r.statusText)}var gse=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 L9(e){return typeof e=="string"&&e.substr(0,7)==="file://"}var W9=class extends _9{constructor(e,t={}){super();this.input=e,this.options=t}async iterator(){if(L9(this.input)&&se().get("IS_NODE")){let e=di("fs");this.input=e.readFileSync(this.input.substr(7))}return new P9(this.input,this.options)}},B9=class extends _9{constructor(e,t={}){super();this.url=e,this.fileOptions=t}async iterator(){return L9(this.url)?new W9(this.url,this.fileOptions).iterator():mse(this.url,this.fileOptions)}};function yse(e,t={}){return new F9(new B9(e),t)}function Ase(e){let t=T5(e);return pa(async()=>t)}function xse(e){return pa(async()=>{let t=await e();return T5(()=>t.next())})}async function bse(e,t){return D9.create(e,t)}async function vse(e){return O9.create(e)}var wse="3.7.0";function Se(e,t){Array.isArray(e)||(e=[e]),e.forEach(n=>{n!=null&&k.assert(n.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the CPU backend.`)})}var kse=us.whereImpl,V9=class extends Wc{constructor(){super();this.blockSize=48,this.firstUse=!0,this.data=new f1(this,Ps())}nextDataId(){return V9.nextDataId++}write(e,t,n){this.firstUse&&(this.firstUse=!1,se().get("IS_NODE")&&M.warn(` ============================ Hi there \u{1F44B}. Looks like you are running TensorFlow.js in Node.js. To speed things up dramatically, install our node backend, which binds to TensorFlow C++, by running npm i @tensorflow/tfjs-node, or npm i @tensorflow/tfjs-node-gpu if you have CUDA. Then call require('@tensorflow/tfjs-node'); (-gpu suffix for CUDA) at the start of your program. Visit https://github.com/tensorflow/tfjs-node for more details. ============================`));let a={id:this.nextDataId()};return this.data.set(a,{values:e,dtype:n,refCount:1}),a}makeTensorInfo(e,t,n){let a;if(t==="string"&&n!=null&&n.length>0&&k.isString(n[0])){let r=n.map(s=>k.encodeString(s));a=this.write(r,e,t)}else a=this.write(n,e,t);return{dataId:a,shape:e,dtype:t}}refCount(e){return this.data.has(e)?this.data.get(e).refCount:0}incRef(e){let t=this.data.get(e);t.refCount++}decRef(e){if(this.data.has(e)){let t=this.data.get(e);t.refCount--}}move(e,t,n,a,r){this.data.set(e,{values:t,dtype:a,refCount:r})}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 a=this.readSync(n.real.dataId),r=this.readSync(n.imag.dataId);return M.mergeRealAndImagArrays(a,r)}return this.data.get(e).values}bufferSync(e){let t=this.readSync(e.dataId),n=t;if(e.dtype==="string")try{n=t.map(a=>k.decodeString(a))}catch(a){throw new Error("Failed to decode encoded string bytes into utf-8")}return Pe(e.shape,e.dtype,n)}makeOutput(e,t,n){let a=this.write(e,t,n);return Ps().makeTensorFromDataId(a,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=k.now();return e(),{kernelMs:k.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){Se([e],"where");let t=this.readSync(e.dataId);return kse(e.shape,t)}dispose(){}floatPrecision(){return 32}epsilon(){return super.epsilon()}},M5=V9;M5.nextDataId=0;var U9={};$e(U9,{addImpl:()=>H9,bincountImpl:()=>R5,bincountReduceImpl:()=>G9,ceilImpl:()=>q9,concatImpl:()=>K9,equalImpl:()=>X9,expImpl:()=>Y9,expm1Impl:()=>Q9,floorImpl:()=>eN,gatherNdImpl:()=>tN,gatherV2Impl:()=>nN,greaterEqualImpl:()=>rN,greaterImpl:()=>aN,lessEqualImpl:()=>iN,lessImpl:()=>sN,linSpaceImpl:()=>oN,logImpl:()=>lN,maxImpl:()=>uN,maximumImpl:()=>dN,minimumImpl:()=>hN,multiplyImpl:()=>F5,negImpl:()=>pN,notEqualImpl:()=>cN,prodImpl:()=>fN,rangeImpl:()=>mN,rsqrtImpl:()=>gN,simpleAbsImpl:()=>j9,sliceImpl:()=>yN,sparseFillEmptyRowsImpl:()=>AN,sparseReshapeImpl:()=>xN,sparseSegmentReductionImpl:()=>D5,squaredDifferenceImpl:()=>bN,stridedSliceImpl:()=>vN,stringNGramsImpl:()=>wN,stringSplitImpl:()=>kN,stringToHashBucketFastImpl:()=>IN,subImpl:()=>SN,tileImpl:()=>NN,topKImpl:()=>TN,transposeImpl:()=>O5,uniqueImpl:()=>EN});function j9(e){let t=new Float32Array(e.length);for(let n=0;n{let{x:t}=e.inputs,n=e.backend;Se(t,"abs");let a=new Float32Array(k.sizeFromShape(t.shape)),r=n.data.get(t.dataId).values;return a=j9(r),n.makeOutput(a,t.shape,"float32")},Sse={kernelName:xd,backendName:"cpu",kernelFunc:Ise};function nn(e){return(t,n,a,r,s)=>{let i=M.assertAndGetBroadcastShape(t,n),o=i.length,l=k.computeStrides(i),u=k.sizeFromShape(i),d=k.getTypedArrayFromDType(s,u),h=t.length,p=n.length,c=k.computeStrides(t),m=k.computeStrides(n),f=M.getBroadcastDims(t,i),g=M.getBroadcastDims(n,i);if(f.length+g.length===0)for(let y=0;yx[I]=0);let v=k.locToIndex(x,h,c),b=A.slice(-p);g.forEach(I=>b[I]=0);let w=k.locToIndex(b,p,m);d[y]=e(a[v],r[w])}return[d,i]}}function ca(e){let{inputs:t,backend:n}=e,{real:a,imag:r}=t,s=n.data.get(a.dataId).values,i=n.data.get(r.dataId).values,o=n.makeTensorInfo(a.shape,"complex64"),l=n.data.get(o.dataId);return l.complexTensorInfos={real:n.makeTensorInfo(a.shape,"float32",s),imag:n.makeTensorInfo(r.shape,"float32",i)},o}var Nse={kernelName:I1,backendName:"cpu",kernelFunc:ca};function C0(e,t,n="float32"){if(n==="complex64"){let r=C0(e,t,"float32"),s=C0(e,t,"float32");return ca({inputs:{real:r,imag:s},backend:e})}let a=k.makeZerosTypedArray(k.sizeFromShape(t),n);return e.makeTensorInfo(t,n,a)}function zr(e){let{inputs:t,backend:n}=e,{x:a}=t;return n.incRef(a.dataId),{dataId:a.dataId,shape:a.shape,dtype:a.dtype}}var Tse={kernelName:pl,backendName:"cpu",kernelFunc:zr};function co(e){let{inputs:t,backend:n}=e,{input:a}=t,r=n.data.get(a.dataId).complexTensorInfos.real,s=n.data.get(r.dataId).values;return n.makeTensorInfo(r.shape,r.dtype,s)}var Ese={kernelName:H1,backendName:"cpu",kernelFunc:co};function Js(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dtype:s}=a;if(s==="complex64"){if(r.dtype==="complex64")return zr({inputs:{x:r},backend:n});let i=C0(n,r.shape,r.dtype),o=Js({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),l=ca({inputs:{real:o,imag:i},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}if(r.dtype==="complex64"){let i=co({inputs:{input:r},backend:n}),o=Js({inputs:{x:i},backend:n,attrs:{dtype:s}});return n.disposeIntermediateTensorInfo(i),o}if(!k.hasEncodingLoss(r.dtype,s)){let i=zr({inputs:{x:r},backend:n});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(s==="int32"){let i=n.data.get(r.dataId).values,o=Int32Array.from(i);return n.makeTensorInfo(r.shape,"int32",o)}if(s==="bool"){let i=n.data.get(r.dataId).values,o=k.toTypedArray([0],r.dtype),[l,u]=nn((d,h)=>d!==h?1:0)(r.shape,[],i,o,"bool");return n.makeTensorInfo(u,"bool",l)}throw new Error(`Error in Cast: failed to cast ${r.dtype} to ${s}`)}var Cse={kernelName:el,backendName:"cpu",kernelFunc:Js};function bn(e,t,n,a){return n==null?({inputs:r,backend:s})=>{let{a:i,b:o}=r,l=s;Se([i,o],e);let u=l.data.get(i.dataId).values,d=l.data.get(o.dataId).values,h=i.dtype==="string"?M.fromUint8ToStringArray(u):u,p=i.dtype==="string"?M.fromUint8ToStringArray(d):d,c=a||i.dtype,[m,f]=t(i.shape,o.shape,h,p,c);return l.makeTensorInfo(f,c,m)}:({inputs:r,backend:s})=>{let{a:i,b:o}=r,l=s;if(i.dtype==="complex64"||o.dtype==="complex64"){let u=Js({inputs:{x:i},backend:l,attrs:{dtype:"complex64"}}),d=l.data.get(u.dataId),h=d.complexTensorInfos.real,p=d.complexTensorInfos.imag,c=l.data.get(h.dataId).values,m=l.data.get(p.dataId).values,f=Js({inputs:{x:o},backend:l,attrs:{dtype:"complex64"}}),g=l.data.get(f.dataId),y=g.complexTensorInfos.real,A=g.complexTensorInfos.imag,x=l.data.get(y.dataId).values,v=l.data.get(A.dataId).values,[b,w,I]=n(i.shape,o.shape,c,m,x,v),T=l.makeTensorInfo(I,"float32",b),C=l.makeTensorInfo(I,"float32",w),z=ca({inputs:{real:T,imag:C},backend:l});return l.disposeIntermediateTensorInfo(u),l.disposeIntermediateTensorInfo(f),l.disposeIntermediateTensorInfo(T),l.disposeIntermediateTensorInfo(C),z}else{let u=l.data.get(i.dataId).values,d=l.data.get(o.dataId).values,h=a||i.dtype,[p,c]=t(i.shape,o.shape,u,d,h);return l.makeTensorInfo(c,h,p)}}}function $5(e){return(t,n,a,r,s,i)=>{let o=M.assertAndGetBroadcastShape(t,n),l=k.sizeFromShape(o),u=o.length,d=k.computeStrides(o),h=k.getTypedArrayFromDType("float32",l),p=k.getTypedArrayFromDType("float32",l),c=M.getBroadcastDims(t,o),m=M.getBroadcastDims(n,o),f=M.mergeRealAndImagArrays(a,r),g=M.mergeRealAndImagArrays(s,i),y=t.length,A=k.computeStrides(t),x=n.length,v=k.computeStrides(n);if(c.length+m.length===0)for(let b=0;bI[S]=0);let T=k.locToIndex(I,y,A),C=w.slice(-x);m.forEach(S=>C[S]=0);let z=k.locToIndex(C,x,v),$=e(f[T*2],f[T*2+1],g[z*2],g[z*2+1]);h[b]=$.real,p[b]=$.imag}return[h,p,o]}}var H9=nn((e,t)=>e+t),Mse=$5((e,t,n,a)=>({real:e+n,imag:t+a})),tp=bn(Os,H9,Mse),$se={kernelName:Os,backendName:"cpu",kernelFunc:tp};function R5(e,t,n,a,r){let s=k.sizeFromShape(a),i=k.makeZerosTypedArray(r,n);for(let o=0;o=r||(s>0?i[l]+=t[o]:i[l]+=1)}return i}function G9(e,t,n,a=!1){let r=e.shape[0],s=e.shape[1],i=Pe([r,n],t.dtype);for(let o=0;o=n||(a?i.set(1,o,u):t.size>0?i.set(i.get(o,u)+t.get(o,l),o,u):i.set(i.get(o,u)+1,o,u))}return i}function du(e){return(t,n,a)=>{let r=k.getTypedArrayFromDType(n,t.length);for(let s=0;s{let{x:i}=a;if(Se(i,e),i.dtype==="string"||n==="string")throw new Error("unaryKernelFunc does not support string input/output");let o=s,l=o.data.get(i.dataId).values,u=k.sizeFromShape(i.shape),d=n||i.dtype,h=k.getArrayFromDType(d,u);for(let p=0;p{let{x:i}=a;if(Se(i,e),i.dtype==="string"||n==="string")throw new Error("unaryKernelFunc does not support string input/output");let o=s,l=o.data.get(i.dataId).values,u=n||i.dtype,d=t(l,u,r);return o.makeTensorInfo(i.shape,u,d)}}var q9=du(e=>Math.ceil(e)),Rse=hu(Ni,q9),Fse={kernelName:Ni,backendName:"cpu",kernelFunc:Rse};function K9(e,t,n,a){let r=k.getArrayFromDType(n,k.sizeFromShape(t));if(a&&n!=="string"){let s=0;e.forEach(i=>{let o=k.sizeFromShape(i.shape);r.set(i.vals,s),s+=o})}else{let s=0;e.forEach(i=>{let o=n==="string"?M.fromUint8ToStringArray(i.vals):i.vals,l=0;for(let u=0;ue===t?1:0),Z9=bn(ol,X9,null,"bool"),Ose={kernelName:ol,backendName:"cpu",kernelFunc:Z9},Y9=du(e=>Math.exp(e)),J9=hu(Ei,Y9),Dse={kernelName:Ei,backendName:"cpu",kernelFunc:J9},Q9=du(e=>Math.expm1(e)),_se=hu(ll,Q9),zse={kernelName:ll,backendName:"cpu",kernelFunc:_se},eN=du(e=>Math.floor(e)),Pse=hu(Ci,eN),Lse={kernelName:Ci,backendName:"cpu",kernelFunc:Pse};function tN(e,t,n,a,r,s,i,o,l){let u=Pe([a,s],n);for(let d=0;d=l/s)throw new Error(`Invalid indices: ${h} does not index into ${o}`);for(let c=0;ce>t?1:0),Wse=bn(hl,aN,null,"bool"),Bse={kernelName:hl,backendName:"cpu",kernelFunc:Wse},rN=nn((e,t)=>e>=t?1:0),Vse=bn(Mi,rN,null,"bool"),Use={kernelName:Mi,backendName:"cpu",kernelFunc:Vse},sN=nn((e,t)=>ee<=t?1:0),Gse=bn(ml,iN,null,"bool"),qse={kernelName:ml,backendName:"cpu",kernelFunc:Gse};function oN(e,t,n){let a=(t-e)/(n-1),r=k.makeZerosTypedArray(n,"float32");r[0]=e;for(let s=1;sMath.log(e)),Kse=hu($i,lN),Xse={kernelName:$i,backendName:"cpu",kernelFunc:Kse};function uN(e,t,n,a){let r=k.getTypedArrayFromDType(a,k.sizeFromShape(n));for(let s=0;so)&&(o=u)}r[s]=o}return r}var dN=nn((e,t)=>Math.max(e,t)),Zse=bn(Ri,dN),Yse={kernelName:Ri,backendName:"cpu",kernelFunc:Zse},hN=nn((e,t)=>Math.min(e,t)),Jse=bn(Fi,hN),Qse={kernelName:Fi,backendName:"cpu",kernelFunc:Jse},F5=nn((e,t)=>e*t),eie=$5((e,t,n,a)=>({real:e*n-t*a,imag:e*a+t*n})),M0=bn(Oi,F5,eie),tie={kernelName:Oi,backendName:"cpu",kernelFunc:M0};function pN(e,t,n){let a=k.createScalarValue(-1,n);return F5([],t,a,e,n)}function nie(e){let{inputs:t,backend:n}=e,{x:a}=t;Se(a,"neg");let r=n.data.get(a.dataId).values,[s,i]=pN(r,a.shape,a.dtype);return n.makeTensorInfo(i,a.dtype,s)}var aie={kernelName:Hd,backendName:"cpu",kernelFunc:nie},cN=nn((e,t)=>e!==t?1:0),rie=bn(vl,cN,null,"bool"),sie={kernelName:vl,backendName:"cpu",kernelFunc:rie};function O5(e,t,n,a,r){let s=t.length,i=k.sizeFromShape(t),o=k.computeStrides(t),l=k.computeStrides(r),u=k.getTypedArrayFromDType(n,k.sizeFromShape(r));for(let d=0;dn.disposeIntermediateTensorInfo(A)),n.makeTensorInfo(y,g,m)}var lie={kernelName:Yd,backendName:"cpu",kernelFunc:oie};function mN(e,t,n,a){let r=e===t,s=e1;if(r||s||i)return k.makeZerosTypedArray(0,a);let o=Math.abs(Math.ceil((t-e)/n)),l=k.makeZerosTypedArray(o,a);t1/Math.sqrt(e)),uie=hu(Di,gN),die={kernelName:Di,backendName:"cpu",kernelFunc:uie};function yN(e,t,n,a,r){let s=Cn.isSliceContinous(a,t,n),i=k.sizeFromShape(n),o=k.computeStrides(a);if(s){let h=Cn.computeFlatOffset(t,o);return r==="string"?e.slice(h,h+i):e.subarray(h,h+i)}let l=r==="string"?M.fromUint8ToStringArray(e):e,u=Pe(a,r,l),d=Pe(n,r);for(let h=0;hm+t[f]);d.set(u.get(...c),...p)}return r==="string"?M.fromStringArrayToUint8(d.values):d.values}function fo(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{begin:s,size:i}=a;Se(r,"slice");let[o,l]=Cn.parseSliceParams(r,s,i);Cn.assertParamsValid(r,o,l);let u=n.data.get(r.dataId).values,d=yN(u,o,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,d)}var hie={kernelName:ah,backendName:"cpu",kernelFunc:fo};function AN(e,t,n,a,r,s,i){let o=t[0],l=s[0],u=new Array(l),d=new Array(o),h=t[1];if(l===0){if(o!==0)throw new Error(`Received SparseTensor with denseShape[0] = 0 but indices.shape[0] = ${o}`);let g=k.getArrayFromDType(n,0),y=k.getArrayFromDType(r,0);return[g,[0,h],y,u,d]}let p=!0,c=0,m=new Array(l).fill(0);for(let g=0;g=l)throw new Error(`indices(${g}, 0) is invalid: ${y} >= ${l}`);++m[y],p=p&&y>=c,c=y}let f=!0;for(let g=0;g0&&(m[g]+=m[g-1])}if(f&&p){let g=e,y=a;for(let A=0;A0){c[p-1]=1;for(let g=p-2;g>=0;--g)c[g]=c[g+1]*a[g+1]}let m=[];if(o>0){m[o-1]=1;for(let g=o-2;g>=0;--g)m[g]=m[g+1]*l[g+1]}let f=k.getArrayFromDType(n,i*o);for(let g=0;g0?r[o-1]+1:0;if(d<0)throw new Error("segment ids must be >= 0");let h=t.slice();h[0]=d;let p=h.reduce((A,x)=>A*x,1),c=k.getArrayFromDType(n,p);if(o===0)return d>0&&c.fill(i),[c,h];if(d<=0)throw new Error("segment ids must be >= 0");let m=0,f=1,g=0,y=r[m];for(;;){let A=0;if(f=A)throw new Error("segment ids are not increasing")}if(y<0||y>=d)throw new Error(`Segment id ${y} out of range [0, ${d}), possibly because segmentIds input is not sorted.`);y>g&&c.fill(i,g*u,y*u);for(let x=m;x=l[0])throw new Error(`Bad: indices[${x}] == ${a[x]} out of range [0, ${l[0]})`);for(let b=0;bo)break}return g{let n=e-t;return n*n}),pie=bn(_i,bN),cie={kernelName:_i,backendName:"cpu",kernelFunc:pie};function vN(e,t,n,a){let r=Pe(e,t.dtype);for(let s=0;s0?0:i-o),p=0;p+=l*this.leftPad.length;for(let g=0;gg.forEach(y=>c[m++]=y);for(let g=0;g0){f(e[h+d-1]);for(let g=0;g0){let o=t[0];if(o!==0)throw new Error(`First split value must be 0, got ${o}`);for(let l=1;l=o;if(u=u&&t[l]<=n,!u)throw new Error(`Invalid split value ${t[l]}, must be in [${o}, ${n}]`);o=t[l]}if(o!==n)throw new Error(`Last split value must be data size. Expected ${n}, got ${o}`)}let r=a-1,s=k.getArrayFromDType("int32",a);if(n===0||a===0){let o=new Array(n);for(let l=0;l<=r;++l)s[l]=0;return[o,s]}s[0]=0;for(let o=1;o<=r;++o){let l=t[o]-t[o-1],u=0;this.nGramWidths.forEach(d=>{u+=this.getNumNGrams(l,d)}),this.preserveShort&&l>0&&u===0&&(u=1),s[o]=s[o-1]+u}let i=new Array(s[r]);for(let o=0;o{let h=t[o+1]-t[o],p=this.getNumNGrams(h,d);this.createNGrams(e,l,i,u,p,d),u+=p}),this.preserveShort&&u===s[o]){let d=t[o+1]-t[o];if(d===0)continue;let h=d+2*this.padWidth,p=1;this.createNGrams(e,l,i,u,p,h)}}return[i,s]}};function wN(e,t,n,a,r,s,i,o){return new fie(n,a,r,s,i,o).compute(e,t)}function mie(e,t,n){if(!e.length)return[];if(t.length===0){let s=new Array(e.length);for(let i=0;ie-t),gie=$5((e,t,n,a)=>({real:e-n,imag:t-a})),_5=bn(zi,SN,gie),yie={kernelName:zi,backendName:"cpu",kernelFunc:_5};function NN(e,t){let n=new Array(e.rank);for(let r=0;rx.value-A.value);let f=h*a,g=l.subarray(f,f+a),y=u.subarray(f,f+a);for(let A=0;A{for(let g=0;gnew M5,1);var CN=xt(Fd,e=>e>=0?e:Math.exp(e)-1),xie={kernelName:Fd,backendName:"cpu",kernelFunc:CN};function MN(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{alpha:s}=a;Se([r],"leakyRelu");let i=k.sizeFromShape(r.shape),o=n.data.get(r.dataId).values,l=k.getTypedArrayFromDType("float32",i);for(let u=0;ue<0?t*e:e);function $N(e){let{inputs:t,backend:n}=e,{x:a,alpha:r}=t;Se([a,r],"prelu");let s=n.data.get(a.dataId).values,i=n.data.get(r.dataId).values,[o,l]=vie(a.shape,r.shape,s,i,a.dtype);return n.makeTensorInfo(l,a.dtype,o)}var wie={kernelName:Sl,backendName:"cpu",kernelFunc:$N},RN=xt(Nl,e=>Math.max(0,e)),kie={kernelName:Nl,backendName:"cpu",kernelFunc:RN},FN=xt(El,e=>Math.min(Math.max(0,e),6)),Iie={kernelName:El,backendName:"cpu",kernelFunc:FN},ON=xt(Rl,e=>1/(1+Math.exp(-e))),Sie={kernelName:Rl,backendName:"cpu",kernelFunc:ON};function z5(e,t,n,a,r){if(n==="linear")return zr({inputs:{x:t},backend:e});if(n==="relu")return RN({inputs:{x:t},backend:e});if(n==="elu")return CN({inputs:{x:t},backend:e});if(n==="relu6")return FN({inputs:{x:t},backend:e});if(n==="prelu")return $N({inputs:{x:t,alpha:a},backend:e});if(n==="leakyrelu")return MN({inputs:{x:t},backend:e,attrs:{alpha:r}});if(n==="sigmoid")return ON({inputs:{x:t},backend:e});throw new Error(`Activation ${n} has not been implemented for the CPU backend.`)}function Ot(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{shape:s}=a,i=k.sizeFromShape(r.shape),o=k.inferFromImplicitShape(s,i),l=k.sizeFromShape(o);k.assert(i===l,()=>`The new shape (${o}) has ${l} elements and the old shape (${r.shape}) has ${i} elements. The new shape and old shape must have the same number of elements.`),n.incRef(r.dataId);let u=n.data.get(r.dataId);if(u.complexTensorInfos!=null){let d=u.complexTensorInfos.real,h=u.complexTensorInfos.imag;d.shape=o,h.shape=o}return{dataId:r.dataId,shape:o,dtype:r.dtype}}var Nie={kernelName:Qd,backendName:"cpu",kernelFunc:Ot};function DN(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s}=t,{transposeA:i,transposeB:o}=a;Se([r,s],"matMul");let l=r.shape.length,u=s.shape.length,d=i?r.shape[l-2]:r.shape[l-1],h=o?s.shape[u-1]:s.shape[u-2],p=i?r.shape[l-1]:r.shape[l-2],c=o?s.shape[u-2]:s.shape[u-1],m=r.shape.slice(0,-2),f=s.shape.slice(0,-2),g=k.sizeFromShape(m),y=k.sizeFromShape(f),A=g===y||g===1||y===1;k.assert(l>=2&&u>=2&&A,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${m}) and (${f}).`);let x=(g>y?r.shape.slice(0,-2):s.shape.slice(0,-2)).concat([p,c]);k.assert(d===h,()=>`Error in matMul: inner shapes (${d}) and (${h}) of Tensors with shapes ${r.shape} and ${s.shape} and transposeA=${i} and transposeB=${o} must match.`);let v=i?[g,d,p]:[g,p,d],b=o?[y,c,h]:[y,h,c],w=Ot({inputs:{x:r},backend:n,attrs:{shape:v}}),I=Ot({inputs:{x:s},backend:n,attrs:{shape:b}}),T=i?w.shape[1]:w.shape[2],C=i?w.shape[2]:w.shape[1],z=o?I.shape[1]:I.shape[2],$=Math.max(g,y),S=n.data.get(w.dataId).values,D=n.data.get(I.dataId).values,_=k.computeStrides(w.shape),W=k.computeStrides(I.shape),[X,q,Q]=i?[_[0],1,_[1]]:[_[0],_[1],1],[ee,ie,ae]=o?[1,W[1],W[0]]:[W[1],1,W[0]],de=C*z,te=Pe([$,C,z],w.dtype),ce=te.values,he=n.blockSize;for(let ve=0;ve<$;ve++)for(let xe=0;xeMath.acos(e)),$ie={kernelName:bd,backendName:"cpu",kernelFunc:Mie},Rie=xt(vd,e=>Math.acosh(e)),Fie={kernelName:vd,backendName:"cpu",kernelFunc:Rie};function Oie(e){let{inputs:t,backend:n}=e,a=t;Se(t,"addN");let r=a.map(o=>n.data.get(o.dataId).values),s=Pe(a[0].shape,a[0].dtype),i=s.values;for(let o=0;oA&&(A=b,x=v)}c[g]=x}return u.forEach(g=>n.disposeIntermediateTensorInfo(g)),n.makeTensorInfo(d,"int32",c)}var Bie={kernelName:Yo,backendName:"cpu",kernelFunc:Wie};function Vie(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a;Se(r,"argMin");let i=k.parseAxisParam(s,r.shape),o=M.getAxesPermutation(i,r.shape.length),l=r,u=[];o!=null&&(l=Da({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=M.getInnerMostAxes(i.length,l.shape.length)),i=[i[0]],M.assertAxesAreInnerMostDims("argMin",i,l.shape.length);let[d,h]=M.computeOutAndReduceShapes(l.shape,i),p=k.sizeFromShape(d),c=k.makeZerosTypedArray(p,"int32"),m=k.sizeFromShape(h),f=n.data.get(l.dataId).values;for(let g=0;gn.disposeIntermediateTensorInfo(g)),n.makeTensorInfo(d,"int32",c)}var Uie={kernelName:qc,backendName:"cpu",kernelFunc:Vie},jie=xt(Id,e=>Math.asin(e)),Hie={kernelName:Id,backendName:"cpu",kernelFunc:jie},Gie=xt(Sd,e=>Math.asinh(e)),qie={kernelName:Sd,backendName:"cpu",kernelFunc:Gie},Kie=xt(Nd,e=>Math.atan(e)),Xie={kernelName:Nd,backendName:"cpu",kernelFunc:Kie},Zie=nn((e,t)=>Math.atan2(e,t)),Yie=bn(Ed,Zie),Jie={kernelName:Ed,backendName:"cpu",kernelFunc:Yie},Qie=xt(Td,e=>Math.atanh(e)),eoe={kernelName:Td,backendName:"cpu",kernelFunc:Qie};function P5(e,t,n,a,r,s){let i=r.strideHeight,o=r.strideWidth,l=r.dilationHeight,u=r.dilationWidth,d=r.effectiveFilterHeight,h=r.effectiveFilterWidth,p=r.padInfo.top,c=r.padInfo.left,m=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,f=Pe(r.outShape,n),g=f.values,y=r.outShape[1]*r.outShape[2]*r.outShape[3],A=r.outShape[2]*r.outShape[3],x=r.outShape[3];for(let v=0;vq?q=he:s==="avg"&&(Q+=he,ee++)}if(isNaN(q))break}let ie=S+D*x+I;g[ie]=s==="avg"?Q/ee:q}}}return f}function _N(e,t,n,a,r=!1,s=!1){let i=Pe(a.outShape,"int32"),o=a.strideHeight,l=a.strideWidth,u=a.dilationHeight,d=a.dilationWidth,h=a.effectiveFilterHeight,p=a.effectiveFilterWidth,c=a.padInfo.top,m=a.padInfo.left,f=Pe(t,n,e);for(let g=0;gz&&(z=X,r?$=s?((g*a.inHeight+S)*a.inWidth+_)*a.inChannels+y:(S*a.inWidth+_)*a.inChannels+y:$=D*p+W)}}i.set($,g,A,w,y)}}return i}function zN(e,t,n,a,r,s){let i=r.strideDepth,o=r.strideHeight,l=r.strideWidth,u=r.dilationDepth,d=r.dilationHeight,h=r.dilationWidth,p=r.effectiveFilterDepth,c=r.effectiveFilterHeight,m=r.effectiveFilterWidth,f=r.padInfo.front,g=r.padInfo.top,y=r.padInfo.left,A=s==="max"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,x=Pe(r.outShape,n),v=x.values,b=r.outShape[1]*r.outShape[2]*r.outShape[3]*r.outShape[4],w=r.outShape[2]*r.outShape[3]*r.outShape[4],I=r.outShape[3]*r.outShape[4],T=r.outShape[4];for(let C=0;CEe?Ee=Je:s==="avg"&&(Fe+=Je,We++),isNaN(Ee))break}if(isNaN(Ee))break}if(isNaN(Ee))break}let qe=xe+S;v[qe]=s==="avg"?Fe/We:Ee}}}}return x}function toe(e,t){let n=Pe(t.outShape,"int32"),a=t.strideDepth,r=t.strideHeight,s=t.strideWidth,i=t.dilationDepth,o=t.dilationHeight,l=t.dilationWidth,u=t.effectiveFilterDepth,d=t.effectiveFilterHeight,h=t.effectiveFilterWidth,p=t.padInfo.front,c=t.padInfo.top,m=t.padInfo.left;for(let f=0;f=D&&(D=ae,_=X*d*h+Q*d+ie)}}}n.set(_,f,y,b,C,g)}}}return n}function noe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;Se(r,"avgPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,u=1;k.assert(M.eitherStridesOrDilationsAreOne(i,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let d=M.computePool2DInfo(r.shape,s,i,u,o,l),h;if(d.filterWidth===1&&d.filterHeight===1&&k.arraysEqual(d.inShape,d.outShape))h=zr({inputs:{x:r},backend:n});else{let p=n.data.get(r.dataId).values,c=k.computeStrides(r.shape),m=P5(p,r.shape,r.dtype,c,d,"avg");h=n.makeTensorInfo(d.outShape,r.dtype,m.values)}return h}var aoe={kernelName:Jo,backendName:"cpu",kernelFunc:noe};function roe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=a;Se(r,"avgPool3d");let d=M.computePool3DInfo(r.shape,s,i,1,o,l,u),h=n.data.get(r.dataId).values,p=zN(h,r.shape,r.dtype,k.computeStrides(r.shape),d,"avg");return n.makeTensorInfo(p.shape,"float32",p.values)}var soe={kernelName:Kc,backendName:"cpu",kernelFunc:roe};function ioe(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=a;Se([r,s],"avgPool3DGrad");let d=M.computePool3DInfo(s.shape,i,o,1,l,u),h=d.strideDepth,p=d.strideHeight,c=d.strideWidth,m=d.filterDepth,f=d.filterHeight,g=d.filterWidth,y=d.dilationDepth,A=d.dilationHeight,x=d.dilationWidth,v=d.effectiveFilterDepth,b=d.effectiveFilterHeight,w=d.effectiveFilterWidth,I=v-1-d.padInfo.front,T=w-1-d.padInfo.left,C=b-1-d.padInfo.top,z=Pe(s.shape,"float32"),$=1/(m*f*g),S=n.bufferSync(r);for(let D=0;D=d.outDepth||Math.floor(te)!==te))for(let ce=0;ce=d.outHeight||Math.floor(he)!==he))for(let ve=0;ve=d.outWidth||Math.floor(xe)!==xe||(ae+=S.get(D,te,he,xe,_))}}}z.set(ae*$,D,W,X,q,_)}return n.makeTensorInfo(z.shape,z.dtype,z.values)}var ooe={kernelName:w1,backendName:"cpu",kernelFunc:ioe};function loe(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s;Se([r,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:u}=a,d=M.computePool2DInfo(i.shape,o,l,1,u),h=d.strideHeight,p=d.strideWidth,c=d.filterHeight,m=d.filterWidth,f=d.dilationHeight,g=d.dilationWidth,y=d.effectiveFilterHeight,A=d.effectiveFilterWidth,x=A-1-d.padInfo.left,v=y-1-d.padInfo.top,b=Pe(i.shape,"float32"),w=1/(c*m),I=n.data.get(r.dataId).values,T=Pe(r.shape,"float32",I);for(let C=0;C=d.outHeight||Math.floor(q)!==q))for(let Q=0;Q=d.outWidth||Math.floor(ee)!==ee||(W+=T.get(C,q,ee,z))}}b.set(W*w,C,$,S,z)}return n.makeTensorInfo(b.shape,b.dtype,b.values)}var uoe={kernelName:v1,backendName:"cpu",kernelFunc:loe};function doe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,scale:s,offset:i,mean:o,variance:l}=t;k.assert(o.shape.length===l.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),k.assert(i==null||o.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),k.assert(s==null||o.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks."),Se([r,o,l,s,i],"batchNorm");let{varianceEpsilon:u}=a;u==null&&(u=.001);let d=n.data.get(r.dataId).values,h=n.data.get(o.dataId).values,p=n.data.get(l.dataId).values,c=s?n.data.get(s.dataId).values:new Float32Array([1]),m=i?n.data.get(i.dataId).values:new Float32Array([0]),f=new Float32Array(d.length),g=m.length,y=c.length,A=p.length,x=h.length,v=0,b=0,w=0,I=0;for(let T=0;T=g&&(v=0),b>=x&&(b=0),w>=y&&(w=0),I>=A&&(I=0);return n.makeTensorInfo(r.shape,r.dtype,f)}var hoe={kernelName:dl,backendName:"cpu",kernelFunc:doe};function poe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,crops:i}=a;Se([r],"batchToSpaceND");let o=s.reduce((y,A)=>y*A),l=M.getReshaped(r.shape,s,o),u=M.getPermuted(l.length,s.length),d=M.getReshapedPermuted(r.shape,s,o),h=M.getSliceBeginCoords(i,s.length),p=M.getSliceSize(d,i,s.length),c=Ot({inputs:{x:r},backend:n,attrs:{shape:l}}),m=Da({inputs:{x:c},backend:n,attrs:{perm:u}}),f=Ot({inputs:{x:m},backend:n,attrs:{shape:d}}),g=fo({inputs:{x:f},backend:n,attrs:{begin:h,size:p}});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(f),g}var coe={kernelName:Xc,backendName:"cpu",kernelFunc:poe};function foe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,weights:s}=t,{size:i}=a,o=n.data.get(r.dataId).values,l=n.data.get(s.dataId).values,u=R5(o,l,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,u)}var moe={kernelName:k1,backendName:"cpu",kernelFunc:foe},goe=xt(Ti,(e,t)=>{let n=t;return e>n.clipValueMax?n.clipValueMax:e{let{x:t}=e.inputs,n=e.backend,a=new Float32Array(k.sizeFromShape(t.shape)),r=n.data.get(t.dataId),s=r.complexTensorInfos.real,i=r.complexTensorInfos.imag,o=n.data.get(s.dataId).values,l=n.data.get(i.dataId).values;for(let u=0;uf.shape),s);if(k.sizeFromShape(i)===0)return n.makeTensorInfo(i,t[0].dtype,[]);let o=t.filter(f=>k.sizeFromShape(f.shape)>0);if(o.length===1)return zr({inputs:{x:o[0]},backend:n});let l=o.map(f=>f.shape);if(M.assertParamsConsistent(l,s),o[0].dtype==="complex64"){let f=o.map(v=>co({inputs:{input:v},backend:n})),g=o.map(v=>pu({inputs:{input:v},backend:n})),y=cu({inputs:f,backend:n,attrs:{axis:s}}),A=cu({inputs:g,backend:n,attrs:{axis:s}}),x=ca({inputs:{real:y,imag:A},backend:n});return f.forEach(v=>n.disposeIntermediateTensorInfo(v)),g.forEach(v=>n.disposeIntermediateTensorInfo(v)),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(A),x}let u=o.map(f=>{let g=k.sizeFromShape(f.shape.slice(s));return Ot({inputs:{x:f},backend:n,attrs:{shape:[-1,g]}})}),d=u.map(f=>({vals:n.data.get(f.dataId).values,shape:f.shape}));i=M.computeOutShape(u.map(f=>f.shape),1);let h=u[0].shape[0]===1,p=K9(d,i,t[0].dtype,h),c=M.computeOutShape(o.map(f=>f.shape),s),m=n.makeTensorInfo(c,t[0].dtype,p);return u.forEach(f=>n.disposeIntermediateTensorInfo(f)),m}var voe={kernelName:Cd,backendName:"cpu",kernelFunc:cu};function PN(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:d}=a;Se([r,s],"conv2d");let h=M.convertConv2DDataFormat(l),p=M.computeConv2DInfo(r.shape,s.shape,i,u,o,d,!1,h),c=p.filterHeight,m=p.filterWidth,f=p.dilationHeight,g=p.dilationWidth,y=p.padInfo.left,A=p.padInfo.top,x=p.dataFormat==="channelsLast",v=new Qt(p.outShape,r.dtype),b=k.computeStrides(r.shape),w=k.computeStrides(s.shape),I=b[0],T=x?b[1]:b[2],C=x?b[2]:1,z=x?1:b[1],$=v.strides[0],S=x?v.strides[1]:v.strides[2],D=x?v.strides[2]:1,_=x?1:v.strides[1],W=n.data.get(r.dataId).values,X=n.data.get(s.dataId).values,q=v.values;for(let Q=0;Q=p.inHeight)continue;let ve=ce*w[0],xe=ee+he*T;for(let Ee=0;Ee=p.inWidth)continue;let ft=ve+qe*w[1],mt=xe+Be*C,bt=ft;for(let lt=0;lt=u.inDepth)continue;let Q=X*C[0],ee=$+q*T[1];for(let ie=0;ie=u.inHeight)continue;let he=Q+te*C[1],ve=ee+ce*T[2];for(let xe=0;xe=u.inWidth)continue;let Be=he+We*C[2],ft=ve+qe*u.inChannels,mt=Be;for(let bt=0;btMath.cos(e)),Ooe={kernelName:al,backendName:"cpu",kernelFunc:Foe},Doe=xt(Md,e=>Math.cosh(e)),_oe={kernelName:Md,backendName:"cpu",kernelFunc:Doe};function zoe(e){let{inputs:t,backend:n,attrs:a}=e,{image:r,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=a,[d,h,p,c]=r.shape,m=s.shape[0],[f,g]=o,y=Pe([m,f,g,c],"float32"),A=n.data.get(s.dataId).values,x=n.data.get(i.dataId).values,v=n.data.get(r.dataId).values,b=k.computeStrides(r.shape),w=k.computeStrides(y.shape);for(let I=0;I=d)continue;let _=f>1?($-C)*(h-1)/(f-1):0,W=g>1?(S-z)*(p-1)/(g-1):0;for(let X=0;X1?C*(h-1)+X*_:.5*(C+$)*(h-1);if(q<0||q>h-1){for(let Q=0;Q1?z*(p-1)+ae*W:.5*(z+S)*(p-1);if(de<0||de>p-1){for(let ve=0;ve1?z*(p-1)+Q*W:.5*(z+S)*(p-1);if(ee<0||ee>p-1){for(let de=0;dey+m-A-1:(y,A)=>y+A;for(let y=0;y`Only NHWC dataFormat supported on CPU for depthToSpace. Got ${i}`),k.assert(s>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${s}`);let o=r.shape[0],l=r.shape[1],u=r.shape[2],d=r.shape[3],h=l*s,p=u*s,c=d/(s*s),m=n.data.get(r.dataId).values,f=new Float32Array(o*h*p*c),g=0;for(let y=0;y`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${p}'`);let c=M.computeConv2DInfo(r.shape,s.shape,i,p,o,u,!0),{filterHeight:m,filterWidth:f,dilationHeight:g,dilationWidth:y,padInfo:A}=c,x=A.left,v=A.top,b=c.outChannels/c.inChannels,w=new Qt(c.outShape,r.dtype),I=n.data.get(r.dataId).values,T=n.data.get(s.dataId).values,C=w.values;for(let z=0;z=c.inHeight)continue;let Q=X*h[0],ee=$+q*d[1];for(let ie=0;ie=c.inWidth)continue;let he=Q+te*h[1],ve=ee+ce*c.inChannels,xe=ae,Ee=he;for(let Fe=0;Fe{let{x:a,filter:r}=e,{strides:s,pad:i,dilations:o}=n,l=t,u=l.data.get(a.dataId).values,d=a.shape.length,h=l.data.get(r.dataId).values,p=r.shape.length,{batchSize:c,inHeight:m,inWidth:f,inChannels:g,outHeight:y,outWidth:A,padInfo:x,strideHeight:v,strideWidth:b,filterHeight:w,filterWidth:I,dilationHeight:T,dilationWidth:C,outShape:z}=M.computeDilation2DInfo(a.shape,r.shape,s,i,"NHWC",o),$=k.sizeFromShape(z),S=z.length,D=k.getArrayFromDType(a.dtype,$);for(let _=0;_=0&&te=0&&heie&&(ie=Ee)}}}let ae=k.locToIndex([_,W,q,ee],S,k.computeStrides(z));D[ae]=ie}}}return{dataId:l.write(k.toTypedArray(D,a.dtype),z,a.dtype),shape:z,dtype:a.dtype}}},Qoe={kernelName:F1,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:a,filter:r,dy:s}=e,{strides:i,pad:o,dilations:l}=n,u=t,d=k.toNestedArray(a.shape,u.data.get(a.dataId).values),h=k.toNestedArray(r.shape,u.data.get(r.dataId).values),{batchSize:p,inHeight:c,inWidth:m,inChannels:f,outHeight:g,outWidth:y,padInfo:A,strideHeight:x,strideWidth:v,filterHeight:b,filterWidth:w,dilationHeight:I,dilationWidth:T,outShape:C}=M.computeDilation2DInfo(a.shape,r.shape,i,o,"NHWC",l);k.assert(s.rank===C.length,()=>`Error in ${F1}, dy must have the same rank as output ${C.length}, but got ${s.rank}`);let z=k.toNestedArray(C,u.data.get(s.dataId).values),$=k.makeZerosNestedTypedArray(r.shape,r.dtype);for(let S=0;S=0&&de=0&&ceQ&&(Q=he,ee=ae,ie=te)}}}$[ee][ie][q]+=z[S][D][W][q]}}}return{dataId:u.write(k.toTypedArray($,a.dtype),r.shape,r.dtype),shape:r.shape,dtype:r.dtype}}},ele={kernelName:R1,backendName:"cpu",kernelFunc:({inputs:e,backend:t,attrs:n})=>{let{x:a,filter:r,dy:s}=e,{strides:i,pad:o,dilations:l}=n,u=t,d=k.toNestedArray(a.shape,u.data.get(a.dataId).values),h=k.toNestedArray(r.shape,u.data.get(r.dataId).values),{batchSize:p,inHeight:c,inWidth:m,inChannels:f,outHeight:g,outWidth:y,padInfo:A,strideHeight:x,strideWidth:v,filterHeight:b,filterWidth:w,dilationHeight:I,dilationWidth:T,outShape:C}=M.computeDilation2DInfo(a.shape,r.shape,i,o,"NHWC",l);k.assert(s.rank===C.length,()=>`Error in ${R1}, dy must have the same rank as output ${C.length}, but got ${s.rank}`);let z=k.toNestedArray(C,u.data.get(s.dataId).values),$=k.makeZerosNestedTypedArray(a.shape,a.dtype);for(let S=0;S=0&&de=0&&ceQ&&(Q=he,ee=de,ie=ce)}}}$[S][ee][ie][q]+=z[S][D][W][q]}}}return{dataId:u.write(k.toTypedArray($,a.dtype),a.shape,a.dtype),shape:a.shape,dtype:a.dtype}}};function np(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;Se(r,"sum");let o;r.dtype==="bool"?o=Js({inputs:{x:r},backend:n,attrs:{dtype:"int32"}}):o=zr({inputs:{x:r},backend:n});let l=o.shape.length,u=k.parseAxisParam(s,o.shape),d=M.getAxesPermutation(u,l),h=u,p=o;d!=null&&(p=Da({inputs:{x:o},backend:n,attrs:{perm:d}}),h=M.getInnerMostAxes(h.length,l)),M.assertAxesAreInnerMostDims("sum",h,p.shape.length);let[c,m]=M.computeOutAndReduceShapes(p.shape,h),f=M.upcastType(p.dtype,"int32"),g=C0(n,c,f),y=k.sizeFromShape(m),A=n.data.get(g.dataId).values,x=n.data.get(p.dataId).values;for(let v=0;v=0&&(p=np({inputs:{x:p},backend:n,attrs:{axis:u[f]-(i.length-c),keepDims:!1}}),m.push(p)),c--)}for(let f of m)f!==p&&n.disposeIntermediateTensorInfo(f);return p}var ale={kernelName:O1,backendName:"cpu",kernelFunc:nle};function rle(e){let{inputs:t,backend:n}=e,{dy:a,y:r}=t;Se([a,r],"eluGrad");let s=new Float32Array(k.sizeFromShape(r.shape)),i=n.data.get(r.dataId).values,o=n.data.get(a.dataId).values;for(let l=0;l=1?s[l]=o[l]:s[l]=o[l]*(u+1)}return n.makeTensorInfo(r.shape,"float32",s)}var sle={kernelName:D1,backendName:"cpu",kernelFunc:rle},ile=M.ERF_P,ole=M.ERF_A1,lle=M.ERF_A2,ule=M.ERF_A3,dle=M.ERF_A4,hle=M.ERF_A5,ple=xt(Od,e=>{let t=Math.sign(e),n=Math.abs(e),a=1/(1+ile*n);return t*(1-((((hle*a+dle)*a+ule)*a+lle)*a+ole)*a*Math.exp(-n*n))}),cle={kernelName:Od,backendName:"cpu",kernelFunc:ple};function $0(e){let{inputs:t,backend:n,attrs:a}=e,{input:r}=t,{dim:s}=a,i=r.shape.length,o=r.shape.slice(),l=s;return s<0&&(k.assert(-(i+1)<=s,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+s+1),o.splice(l,0,1),Ot({inputs:{x:r},backend:n,attrs:{shape:o}})}var fle={kernelName:Dd,backendName:"cpu",kernelFunc:$0},mle=nn((e,t)=>e/t),L5=bn(il,mle),W5={kernelName:il,backendName:"cpu",kernelFunc:L5};function WN(e,t,n){let a=e.shape,r=a[0],s=a[1],i=n.data.get(e.dataId),o=i.complexTensorInfos.real,l=i.complexTensorInfos.imag,u=[r,s],d=k.sizeFromShape(u),h=k.getTypedArrayFromDType("float32",d),p=k.getTypedArrayFromDType("float32",d);for(let g=0;g{let{image:a}=e,r=n,s=k.getTypedArrayFromDType(a.dtype,k.sizeFromShape(a.shape)),[i,o,l,u]=a.shape,d=r.data.get(a.dataId).values;for(let h=0;h=0&&xMath.floor(e/t)),Sle=bn(ul,Ile,null,"int32"),Nle={kernelName:ul,backendName:"cpu",kernelFunc:Sle};function Tle(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:d,dilations:h,dimRoundingMode:p,activation:c,leakyreluAlpha:m}=a,f=PN({inputs:{x:r,filter:s},backend:n,attrs:{strides:l,pad:u,dataFormat:d,dilations:h,dimRoundingMode:p}});if(i){let g=f;f=tp({inputs:{a:f,b:i},backend:n}),n.disposeIntermediateTensorInfo(g)}if(c){let g=f;f=z5(n,f,c,o,m),n.disposeIntermediateTensorInfo(g)}return f}var Ele={kernelName:Wl,backendName:"cpu",kernelFunc:Tle};function Cle(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:d,dilations:h,dimRoundingMode:p,activation:c,leakyreluAlpha:m}=a,f=LN({inputs:{x:r,filter:s},backend:n,attrs:{strides:l,pad:u,dataFormat:d,dilations:h,dimRoundingMode:p}});if(i){let g=f;f=tp({inputs:{a:f,b:i},backend:n}),n.disposeIntermediateTensorInfo(g)}if(c){let g=f;f=z5(n,f,c,o,m),n.disposeIntermediateTensorInfo(g)}return f}var Mle={kernelName:Bl,backendName:"cpu",kernelFunc:Cle};function $le(e){let{inputs:t,backend:n}=e,{params:a,indices:r}=t,s=k.sizeFromShape(a.shape),i=r.shape,o=i[i.length-1],[l,u,d,h]=M.prepareAndValidate(a,r);if(u===0)return n.makeTensorInfo(l,a.dtype,[]);let p=n.data.get(r.dataId).values,c=n.bufferSync(a),m=tN(p,c,a.dtype,u,o,d,h,a.shape,s);return n.makeTensorInfo(l,a.dtype,m.values)}var Rle={kernelName:Pd,backendName:"cpu",kernelFunc:$le};function Fle(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,indices:s}=t,{axis:i,batchDims:o}=a;Se([r,s],"gatherV2");let l=o;o==null&&(l=0);let u=k.sizeFromShape(s.shape),d=k.parseAxisParam(i,r.shape)[0],h=M.segment_util.collectGatherOpShapeInfo(r,s,d,l),p=Ot({inputs:{x:r},backend:n,attrs:{shape:[h.batchSize,h.outerSize,h.dimSize,h.sliceSize]}}),c=Ot({inputs:{x:s},backend:n,attrs:{shape:[h.batchSize,u/h.batchSize]}}),m=[h.batchSize,h.outerSize,u/h.batchSize,h.sliceSize],f=n.bufferSync(c),g=n.bufferSync(p),y=nN(g,f,m);return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(c),n.makeTensorInfo(h.outputShape,y.dtype,y.values)}var Ole={kernelName:zd,backendName:"cpu",kernelFunc:Fle};function Dle(e){let{inputs:t,backend:n}=e,{input:a}=t,r=k.sizeFromShape(a.shape),s=a.shape[a.shape.length-1],i=r/s,o=Ot({inputs:{x:a},backend:n,attrs:{shape:[i,s]}}),l=WN(o,!0,n),u=Ot({inputs:{x:l},backend:n,attrs:{shape:a.shape}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(l),u}var _le={kernelName:z1,backendName:"cpu",kernelFunc:Dle},zle=xt(Ld,e=>Number.isFinite(e)?1:0,"bool"),Ple={kernelName:Ld,backendName:"cpu",kernelFunc:zle},Lle=xt(Wd,e=>Math.abs(e)===Infinity?1:0,"bool"),Wle={kernelName:Wd,backendName:"cpu",kernelFunc:Lle},Ble=xt(Bd,e=>Number.isNaN(e)?1:0,"bool"),Vle={kernelName:Bd,backendName:"cpu",kernelFunc:Ble};function Ule(e){let{backend:t,attrs:n}=e,{start:a,stop:r,num:s}=n,i=oN(a,r,s);return t.makeTensorInfo([i.length],"float32",i)}var jle={kernelName:L1,backendName:"cpu",kernelFunc:Ule},Hle=xt(Vd,e=>Math.log1p(e)),Gle={kernelName:Vd,backendName:"cpu",kernelFunc:Hle},qle=nn((e,t)=>e&&t),Kle=bn(Ud,qle,null,"bool"),Xle={kernelName:Ud,backendName:"cpu",kernelFunc:Kle},Zle=xt(ef,e=>e?0:1,"bool"),Yle={kernelName:ef,backendName:"cpu",kernelFunc:Zle},Jle=nn((e,t)=>e||t),Qle=bn(tf,Jle,null,"bool"),eue={kernelName:tf,backendName:"cpu",kernelFunc:Qle};function tue(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=a;Se(r,"LRN");let u=r.shape[3],d=u-1,h=n.data.get(r.dataId).values,p=k.sizeFromShape(r.shape),c=new Float32Array(p);function m(f){let g=f%u,y=f-g+Math.max(0,g-s),A=f-g+Math.min(g+s,d),x=0;for(;y<=A;y++){let v=h[y];x+=v*v}return x}for(let f=0;f`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let d=M.computePool2DInfo(r.shape,s,i,u,o,l),h;if(d.filterWidth===1&&d.filterHeight===1&&k.arraysEqual(d.inShape,d.outShape))h=zr({inputs:{x:r},backend:n});else{let p=n.data.get(r.dataId).values,c=k.computeStrides(r.shape),m=P5(p,r.shape,r.dtype,c,d,"max");h=n.makeTensorInfo(d.outShape,r.dtype,m.values)}return h}var oue={kernelName:yl,backendName:"cpu",kernelFunc:iue};function lue(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=a;Se(r,"maxPool3d");let d=M.computePool3DInfo(r.shape,s,i,1,o,l,u),h=n.data.get(r.dataId).values,p=zN(h,r.shape,r.dtype,k.computeStrides(r.shape),d,"max");return n.makeTensorInfo(p.shape,"float32",p.values)}var uue={kernelName:af,backendName:"cpu",kernelFunc:lue};function due(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=a;Se([r,s],"maxPool3DGrad");let d=M.computePool3DInfo(s.shape,i,o,1,l,u),h=n.bufferSync(s),p=toe(h,d),c=d.strideDepth,m=d.strideHeight,f=d.strideWidth,g=d.dilationDepth,y=d.dilationHeight,A=d.dilationWidth,x=d.effectiveFilterDepth,v=d.effectiveFilterHeight,b=d.effectiveFilterWidth,w=x-1-d.padInfo.front,I=b-1-d.padInfo.left,T=v-1-d.padInfo.top,C=Pe(s.shape,"float32"),z=n.bufferSync(r);for(let $=0;$=d.outDepth||Math.floor(ae)!==ae))for(let de=0;de=d.outHeight||Math.floor(te)!==te))for(let ce=0;ce=d.outWidth||Math.floor(he)!==he)continue;let ve=x*v*b-1-p.get($,ae,te,he,S),xe=ie*v*b+de*b+ce,Ee=ve===xe?1:0;Ee!==0&&(ee+=z.get($,ae,te,he,S)*Ee)}}}C.set(ee,$,D,_,W,S)}return n.makeTensorInfo(C.shape,C.dtype,C.values)}var hue={kernelName:V1,backendName:"cpu",kernelFunc:due};function pue(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s,output:i}=t,o=s;Se([s,i],"maxPoolGrad");let{filterSize:l,strides:u,pad:d,dimRoundingMode:h}=a,p=M.computePool2DInfo(o.shape,l,u,1,d,h),c=n.data.get(o.dataId).values,m=Pe(p.outShape,o.dtype,_N(c,o.shape,o.dtype,p).values),f=p.strideHeight,g=p.strideWidth,y=p.dilationHeight,A=p.dilationWidth,x=p.effectiveFilterHeight,v=p.effectiveFilterWidth,b=v-1-p.padInfo.left,w=x-1-p.padInfo.top,I=Pe(o.shape,"float32"),T=n.data.get(r.dataId).values,C=Pe(r.shape,"float32",T);for(let z=0;z=p.outHeight||Math.floor(Q)!==Q))for(let ee=0;ee=p.outWidth||Math.floor(ie)!==ie)continue;let ae=x*v-1-m.get(z,Q,ie,$),de=q*v+ee,te=ae===de?1:0;te!==0&&(X+=C.get(z,Q,ie,$)*te)}}I.set(X,z,S,D,$)}return n.makeTensorInfo(I.shape,I.dtype,I.values)}var cue={kernelName:B1,backendName:"cpu",kernelFunc:pue};function fue(e,t,n,a,r){let s=k.computeStrides(t),i=P5(e,t,n,s,r,"max"),o=_N(e,t,n,r,!0,a);return[i.values,o.values]}var mue={kernelName:U1,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:a}=e,{filterSize:r,strides:s,pad:i,includeBatchInIndex:o}=t,l=n;Se(a,"MaxPoolWithArgmax");let u=l.data.get(a.dataId).values,d=M.computePool2DInfo(a.shape,r,s,[1,1],i),[h,p]=fue(u,a.shape,a.dtype,o,d),c=l.write(h,d.outShape,a.dtype),m=l.write(p,d.outShape,a.dtype);return[{dataId:c,shape:d.outShape,dtype:a.dtype},{dataId:m,shape:d.outShape,dtype:"int32"}]}};function gue(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=k.parseAxisParam(s,r.shape),l=M.computeOutAndReduceShapes(r.shape,o)[1],u=k.sizeFromShape(l),d=[],h=n.makeTensorInfo([],"float32",new Float32Array([u]));d.push(h);let p=Js({inputs:{x:r},backend:n,attrs:{dtype:"float32"}});d.push(p);let c=L5({inputs:{a:p,b:h},backend:n});d.push(c);let m=np({inputs:{x:c},backend:n,attrs:{axis:s,keepDims:i}});return d.forEach(f=>n.disposeIntermediateTensorInfo(f)),m}var yue={kernelName:Al,backendName:"cpu",kernelFunc:gue};function Aue(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a;Se(r,"min");let o=k.parseAxisParam(s,r.shape),l=o,u=M.getAxesPermutation(l,r.shape.length),d=r;u!=null&&(d=Da({inputs:{x:r},backend:n,attrs:{perm:u}}),l=M.getInnerMostAxes(l.length,r.shape.length)),M.assertAxesAreInnerMostDims("min",l,d.shape.length);let[h,p]=M.computeOutAndReduceShapes(d.shape,l),c=k.sizeFromShape(p),m=k.makeZerosTypedArray(k.sizeFromShape(h),d.dtype),f=n.data.get(d.dataId).values;for(let y=0;yA[0]+r.shape[x]+A[1]),l=s.map(A=>A[0]),u=s.map((A,x)=>A[0]+r.shape[x]),d=i==="reflect"?0:1,h=n.data.get(r.dataId).values,p=r.shape.length,c=k.computeStrides(r.shape),m=k.sizeFromShape(o),f=o.length,g=k.computeStrides(o),y=k.getTypedArrayFromDType(r.dtype,m);for(let A=0;A=u[b]&&(x[b]=(u[b]-1)*2-x[b]+d);x=x.map((b,w)=>b-l[w]);let v=k.locToIndex(x,p,c);y[A]=h[v]}return{dataId:n.write(y,o,r.dtype),shape:o,dtype:r.dtype}}var vue={kernelName:bl,backendName:"cpu",kernelFunc:bue},wue=nn((e,t)=>{let n=e%t;return e<0&&t<0||e>=0&&t>=0?n:(n+t)%t}),kue=bn(jd,wue),Iue={kernelName:jd,backendName:"cpu",kernelFunc:kue},Sue=qr(ey());function VN(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{dim:s}=a,i=r.shape.length,o=s;if(o===-1&&(o=i-1),o!==i-1)throw Error(`Softmax along a non-last dimension is not yet supported. Logits was rank ${i} and dim was ${o}`);let l=k.parseAxisParam([o],r.shape),u=BN({inputs:{x:r},backend:n,attrs:{reductionIndices:l,keepDims:!1}}),d=M.expandShapeToKeepDim(u.shape,l),h=Ot({inputs:{x:u},backend:n,attrs:{shape:d}}),p=_5({inputs:{a:r,b:h},backend:n}),c=J9({inputs:{x:p},backend:n}),m=np({inputs:{x:c},backend:n,attrs:{axis:l,keepDims:!1}}),f=Ot({inputs:{x:m},backend:n,attrs:{shape:d}}),g=L5({inputs:{a:c,b:f},backend:n});return n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(f),g}var Nue={kernelName:Dl,backendName:"cpu",kernelFunc:VN};function Tue(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{numSamples:s,seed:i,normalized:o}=a;Se(r,"multinomial");let l=o?r:VN({inputs:{logits:r},backend:n,attrs:{dim:-1}}),u=l.shape[0],d=l.shape[1],h=n.data.get(l.dataId).values,p=[u,s],c=k.makeZerosTypedArray(k.sizeFromShape(p),"int32");for(let m=0;m=0&&d[h]{k.assertShapesMatch(s,d.shape,"All tensors passed to stack must have matching shapes"),k.assert(i===d.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(d=>{let h=$0({inputs:{input:d},backend:n,attrs:{dim:r}});return o.push(h),h}),u=cu({inputs:l,backend:n,attrs:{axis:r}});return o.forEach(d=>n.disposeIntermediateTensorInfo(d)),u}var Vue={kernelName:Zd,backendName:"cpu",kernelFunc:jN};function Uue(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{paddings:s,constantValue:i}=a;Se(r,"pad");let o=s.map((y,A)=>y[0]+r.shape[A]+y[1]),l=s.map(y=>y[0]),u=n.data.get(r.dataId).values,d=k.sizeFromShape(r.shape),h=r.shape.length,p=k.computeStrides(r.shape),c=k.sizeFromShape(o),m=o.length,f=k.computeStrides(o),g=k.getTypedArrayFromDType(r.dtype,c);i!==0&&g.fill(i);for(let y=0;yv+l[b]),x=k.locToIndex(A,m,f);g[x]=u[y]}return{dataId:n.write(g,o,r.dtype),shape:o,dtype:r.dtype}}var HN={kernelName:kl,backendName:"cpu",kernelFunc:Uue},jue=nn((e,t)=>Math.pow(e,t)),Hue=bn(Il,jue),Gue={kernelName:Il,backendName:"cpu",kernelFunc:Hue};function que(e){let{backend:t,attrs:n}=e,{start:a,stop:r,dtype:s,step:i}=n,o=mN(a,r,i,s);return t.makeTensorInfo([o.length],s,o)}var Kue={kernelName:rf,backendName:"cpu",kernelFunc:que},Xue=xt(Jd,e=>1/e),Zue={kernelName:Jd,backendName:"cpu",kernelFunc:Xue};function Yue(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a;Se(r,"resizeBilinear");let l=k.computeStrides(r.shape),[u,d]=o,[h,p,c,m]=r.shape,f=n.data.get(r.dataId).values,g=new Float32Array(k.sizeFromShape([h,u,d,m])),y=[s&&u>1?p-1:p,s&&d>1?c-1:c],A=[s&&u>1?u-1:u,s&&d>1?d-1:d],x=0,v=y[0]/A[0],b=y[1]/A[1];for(let w=0;w1?u-1:u,i&&c>1?d-1:d],g=[i&&p>1?p-1:p,i&&c>1?c-1:c],y=f[0]/g[0],A=f[1]/g[1],x=n.data.get(s.dataId).values,v=0;for(let b=0;b1?p-1:p,s&&d>1?c-1:c],A=[s&&u>1?u-1:u,s&&d>1?d-1:d],x=y[0]/A[0],v=y[1]/A[1],b=0;for(let w=0;w1?d-1:d,i&&m>1?h-1:h],A=[i&&c>1?c-1:c,i&&m>1?m-1:m],x=y[0]/A[0],v=y[1]/A[1],b=1/x,w=1/v,I=Math.ceil(b)*2+2,T=Math.ceil(w)*2+2;for(let C=0;C=c)continue;let te=z+de*l[1],ce=de*x,he=Math.min(d-1,i?Math.round(ce):Math.floor(ce));if($===he)for(let ve=0;ve=m)continue;let Ee=te+xe*l[2],Fe=xe*v,We=Math.min(h-1,i?Math.round(Fe):Math.floor(Fe));W===We&&(ie+=g[Ee+ee])}}f[X+ee]=ie}}}}return n.makeTensorInfo(r.shape,r.dtype,f)}var rde={kernelName:G1,backendName:"cpu",kernelFunc:ade};function sde(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dims:s}=a;Se(r,"reverse");let i=r.shape.length,o=k.parseAxisParam(s,r.shape);if(i===0)return zr({inputs:{x:r},backend:n});let l=new Qt(r.shape,r.dtype),u=n.bufferSync(r);for(let d=0;dp[c]=r.shape[c]-1-p[c]),l.set(u.get(...p),...h)}return n.makeTensorInfo(l.shape,l.dtype,l.values)}var ide={kernelName:Cl,backendName:"cpu",kernelFunc:sde},ode={kernelName:ch,backendName:"cpu",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:a}=e,{radians:r,fillValue:s,center:i}=t,o=n,l=k.getTypedArrayFromDType(a.dtype,k.sizeFromShape(a.shape)),[u,d,h,p]=a.shape,[c,m]=M.getImageCenter(i,d,h),f=255,g=Math.sin(r),y=Math.cos(r),A=o.data.get(a.dataId).values;for(let x=0;x=0&&D=0&&_{let t=Math.floor(e);return e-t<.5?Math.floor(e):e-t>.5?Math.ceil(e):t%2==0?t:t+1}),ude={kernelName:Ml,backendName:"cpu",kernelFunc:lde};function GN(e,t,n,a,r,s,i,o,l,u){let d=[a/r,r],h=e.values,p=t.values;if(a===0)return Pe(n,t.dtype);let c=Pe(d,t.dtype);c.values.fill(l);for(let m=0;m=a/r)throw new Error(`Invalid indices: ${f} does not index into ${n}`);for(let y=0;y1||r.shape.length===1?1:k.sizeFromShape(r.shape.slice(1));for(let m=0;me>=0?mde*e:fde*(Math.exp(e)-1)),yde={kernelName:nh,backendName:"cpu",kernelFunc:gde},Ade=xt(sh,e=>e<0?-1:e>0?1:0),xde={kernelName:sh,backendName:"cpu",kernelFunc:Ade},bde=xt($l,e=>Math.sin(e)),vde={kernelName:$l,backendName:"cpu",kernelFunc:bde},wde=xt(rh,e=>Math.sinh(e)),kde={kernelName:rh,backendName:"cpu",kernelFunc:wde},Ide=11920928955078125e-23,qN=Math.log(Ide)+2,Sde=xt(ih,e=>{let t=e>-qN,n=eNumber(g)))),n.makeTensorInfo([f.length],a.dtype,new Int32Array(f))]}var Mde={kernelName:K1,backendName:"cpu",kernelFunc:Cde};function $de(e){let{inputs:t,backend:n}=e,{inputIndices:a,inputShape:r,newShape:s}=t;if(a.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape ${a.shape}`);if(r.shape.length!==1)throw new Error(`Input shape should be a vector but received shape ${r.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=Array.from(n.data.get(r.dataId).values),o=n.data.get(a.dataId).values,l=Array.from(n.data.get(s.dataId).values),[u,d,h]=xN(o,a.shape,a.dtype,i,l);return[n.makeTensorInfo(d,a.dtype,u),n.makeTensorInfo([h.length],s.dtype,new Int32Array(h))]}var Rde={kernelName:X1,backendName:"cpu",kernelFunc:$de};function Fde(e){let{inputs:t,backend:n}=e,{data:a,indices:r,segmentIds:s}=t;if(a.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape ${r.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape ${s.shape}`);let i=n.data.get(a.dataId).values,o=n.data.get(r.dataId).values,l=n.data.get(s.dataId).values,[u,d]=D5(i,a.shape,a.dtype,o,l,!0);return n.makeTensorInfo(d,a.dtype,u)}var Ode={kernelName:Z1,backendName:"cpu",kernelFunc:Fde};function Dde(e){let{inputs:t,backend:n}=e,{data:a,indices:r,segmentIds:s}=t;if(a.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape ${r.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape ${s.shape}`);let i=n.data.get(a.dataId).values,o=n.data.get(r.dataId).values,l=n.data.get(s.dataId).values,[u,d]=D5(i,a.shape,a.dtype,o,l);return n.makeTensorInfo(d,a.dtype,u)}var _de={kernelName:Y1,backendName:"cpu",kernelFunc:Dde};function zde(e){let{inputs:t,backend:n,attrs:a}=e,{sparseIndices:r,sparseValues:s,defaultValue:i}=t,{outputShape:o}=a,{sliceRank:l,numUpdates:u,sliceSize:d,strides:h,outputSize:p}=M.calculateShapes(s,r,o),c=!1,m=n.bufferSync(r),f=n.bufferSync(s),g=n.data.get(i.dataId).values[0],y=GN(m,f,o,p,d,u,l,h,g,c);return n.makeTensorInfo(o,y.dtype,y.values)}var Pde={kernelName:J1,backendName:"cpu",kernelFunc:zde};function Lde(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{numOrSizeSplits:s,axis:i}=a,o=k.parseAxisParam(i,r.shape)[0],l=M.prepareSplitSize(r,s,o),u=new Array(r.shape.length).fill(0),d=r.shape.slice();return l.map(h=>{let p=[...d];p[o]=h;let c=fo({inputs:{x:r},backend:n,attrs:{begin:u,size:p}});return u[o]+=h,c})}var Wde={kernelName:oh,backendName:"cpu",kernelFunc:Lde},Bde=xt(Fl,e=>Math.sqrt(e)),Vde={kernelName:Fl,backendName:"cpu",kernelFunc:Bde},Ude={kernelName:lf,backendName:"cpu",kernelFunc:({inputs:e,backend:t})=>{let{x:n}=e,a=t;Se(n,"square");let r=a.data.get(n.dataId).values,s=new Float32Array(r.length);for(let i=0;i{let n=t;return isNaN(e)?NaN:e>0?1:n.alpha}),Hde={kernelName:Li,backendName:"cpu",kernelFunc:jde};function Gde(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:d,newAxisMask:h,shrinkAxisMask:p}=a;Se(r,"stridedSlice");let{nonStrided:c,$begin:m,$strides:f,size:g,newShape:y,outShape:A}=Cn.sliceInfo(r.shape,s,i,o,l,u,d,h,p),x=Ot({inputs:{x:r},backend:n,attrs:{shape:y}}),v;if(c){let w=fo({inputs:{x},backend:n,attrs:{begin:m,size:g}});v=Ot({inputs:{x:w},backend:n,attrs:{shape:A}}),n.disposeIntermediateTensorInfo(w)}else if(A.some(w=>w===0))v=n.makeTensorInfo(A,r.dtype,[]);else{let w=n.bufferSync(x),I=vN(A,w,f,m);v=n.makeTensorInfo(I.shape,I.dtype,I.values)}let b=Ot({inputs:{x:v},backend:n,attrs:{shape:A}});return n.disposeIntermediateTensorInfo(x),n.disposeIntermediateTensorInfo(v),b}var qde={kernelName:lh,backendName:"cpu",kernelFunc:Gde};function Kde(e){let{inputs:t,backend:n,attrs:a}=e,{separator:r,nGramWidths:s,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=a,{data:d,dataSplits:h}=t,p=n.data.get(d.dataId).values,c=n.data.get(h.dataId).values,[m,f]=wN(p,c,r,s,i,o,l,u);return[n.makeTensorInfo([m.length],"string",m),n.makeTensorInfo(h.shape,"int32",f)]}var Xde={kernelName:Q1,backendName:"cpu",kernelFunc:Kde};function Zde(e){let{inputs:t,backend:n,attrs:a}=e,{skipEmpty:r}=a,{input:s,delimiter:i}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(s.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${s.shape}`);if(i.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);let o=n.data.get(s.dataId).values,l=n.data.get(i.dataId).values[0],[u,d,h]=kN(o,l,r),p=d.length;return[n.makeTensorInfo([p,2],"int32",u),n.makeTensorInfo([p],"string",d),n.makeTensorInfo([2],"int32",new Int32Array(h))]}var Yde={kernelName:eA,backendName:"cpu",kernelFunc:Zde};function Jde(e){let{inputs:t,backend:n,attrs:a}=e,{numBuckets:r}=a,{input:s}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(r<=0)throw new Error("Number of buckets must be at least 1");let i=n.data.get(s.dataId).values,o=IN(i,r);return n.makeTensorInfo(s.shape,"int32",o)}var Qde={kernelName:tA,backendName:"cpu",kernelFunc:Jde},ehe=xt(_l,e=>Math.tan(e)),the={kernelName:_l,backendName:"cpu",kernelFunc:ehe},nhe=xt(zl,e=>Math.tanh(e)),ahe={kernelName:zl,backendName:"cpu",kernelFunc:nhe};function rhe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{reps:s}=a;Se(r,"tile");let i=NN(n.bufferSync(r),s);return n.makeTensorInfo(i.shape,i.dtype,i.values)}var she={kernelName:Pi,backendName:"cpu",kernelFunc:rhe};function ihe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{k:s,sorted:i}=a;Se(r,"topk");let o=n.data.get(r.dataId).values,[l,u]=TN(o,r.shape,r.dtype,s,i);return[n.makeTensorInfo(l.shape,l.dtype,l.values),n.makeTensorInfo(u.shape,u.dtype,u.values)]}var ohe={kernelName:uh,backendName:"cpu",kernelFunc:ihe};function lhe(e){let{inputs:t,attrs:n,backend:a}=e,{image:r,transforms:s}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=n,[d,h,p,c]=r.shape,[m,f]=u!=null?u:[h,p],g=[d,m,f,c],y=k.computeStrides(r.shape),A=y[0],x=y[1],v=y[2],b=k.getTypedArrayFromDType(r.dtype,k.sizeFromShape(g));b.fill(l);let w=a.data.get(r.dataId).values,I=a.data.get(s.dataId).values;for(let T=0;Tt-1)if(t<=1)n=0;else{let a=2*t;n-=a*Math.trunc(n/a),n>=t&&(n=a-n-1)}return k.clamp(0,n,t-1)}function hhe(e,t){let n=e;if(n<0)if(t<=1)n=0;else{let a=t-1;n+=t*(Math.trunc(-n/a)+1)}else if(n>t-1)if(t<=1)n=0;else{let a=t-1;n-=t*Math.trunc(n/a)}return k.clamp(0,n,t-1)}function phe(e,t){return e}function che(e,t){return k.clamp(0,e,t-1)}function ap(e,t,n,a,r,s,i,o,l,u,d){let h=i*a+o*r+l*s+u;return 0<=o&&on.disposeIntermediateTensorInfo(m)),c}var vhe={kernelName:uf,backendName:"cpu",kernelFunc:bhe},whe=[Cie,Sse,$ie,Fie,$se,Die,zie,Lie,Bie,Uie,Hie,qie,Xie,Jie,eoe,aoe,soe,ooe,uoe,Tie,hoe,coe,moe,Cse,Fse,yoe,Nse,xoe,voe,Ioe,Noe,woe,Moe,Roe,Eoe,Ooe,_oe,Poe,Woe,Voe,joe,Hoe,qoe,Xoe,Yoe,Joe,ele,Qoe,W5,ale,xie,sle,Ose,cle,Dse,fle,zse,ble,vle,kle,Lse,Nle,Ele,Mle,Rle,Ole,Bse,Use,Tse,_le,boe,Ple,Wle,Vle,bie,Hse,qse,jle,Xse,Gle,Xle,Yle,eue,nue,rue,Yse,oue,uue,hue,cue,mue,sue,yue,xue,Qse,vue,Iue,Eue,tie,aie,$ue,Oue,zue,sie,Lue,Bue,Vue,HN,Gue,wie,lie,Kue,Ese,Zue,kie,Iie,Nie,Jue,ede,nde,rde,ide,ode,ude,die,hde,cde,yde,Sie,xde,vde,kde,hie,Nue,Nde,Ede,Mde,Rde,Ode,_de,Pde,Wde,Vde,Ude,cie,Hde,qde,Xde,Yde,Qde,yie,tle,the,ahe,she,ohe,iie,uhe,yhe,xhe,vhe,Wue];for(let e of whe)iA(e);var XN={};$e(XN,{assertNotComplex:()=>mu,bindCanvasToFramebuffer:()=>Ohe,bindColorTextureToFramebuffer:()=>D0,bindTextureToProgramUniformSampler:()=>dT,bindTextureUnit:()=>oT,bindVertexBufferToProgramAttribute:()=>H5,callAndCheck:()=>ke,canBeRepresented:()=>ZN,createFragmentShader:()=>QN,createFramebuffer:()=>iT,createProgram:()=>eT,createStaticIndexBuffer:()=>aT,createStaticVertexBuffer:()=>nT,createTexture:()=>rT,createVertexShader:()=>JN,getBatchDim:()=>go,getExtensionOrThrow:()=>op,getFramebufferErrorMessage:()=>hT,getMaxTexturesInShader:()=>mT,getNumChannels:()=>Rhe,getProgramUniformLocation:()=>uT,getProgramUniformLocationOrThrow:()=>lT,getRowsCols:()=>yo,getShapeAs3D:()=>_0,getTextureShapeFromLogicalShape:()=>cT,getWebGLDisjointQueryTimerVersion:()=>gT,getWebGLErrorMessage:()=>YN,getWebGLMaxTextureSize:()=>fT,hasExtension:()=>za,isCapableOfRenderingToFloatTexture:()=>yT,isDownloadFloatTextureEnabled:()=>AT,isReshapeFree:()=>up,isWebGLFenceEnabled:()=>xT,isWebGLVersionEnabled:()=>q5,linkProgram:()=>tT,resetMaxTextureSize:()=>Dhe,resetMaxTexturesInShader:()=>_he,unbindColorTextureFromFramebuffer:()=>G5,unbindTextureUnit:()=>Fhe,validateFramebuffer:()=>lp,validateProgram:()=>O0,validateTextureSize:()=>sT});var mo={},U5={alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!0};function F0(e,t){mo[e]=t}function Pr(e){if(!(e in mo)){let n=Ihe(e);if(n!==null)mo[e]=n;else return console.log("Could not get context for WebGL version",e),null}let t=mo[e];return t.isContextLost()?(delete mo[e],Pr(e)):(t.disable(t.DEPTH_TEST),t.disable(t.STENCIL_TEST),t.disable(t.BLEND),t.disable(t.DITHER),t.disable(t.POLYGON_OFFSET_FILL),t.disable(t.SAMPLE_COVERAGE),t.enable(t.SCISSOR_TEST),t.enable(t.CULL_FACE),t.cullFace(t.BACK),mo[e])}function khe(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 Ihe(e){if(e!==1&&e!==2)throw new Error("Cannot get WebGL rendering context, WebGL is disabled.");let t=khe(e);return t.addEventListener("webglcontextlost",n=>{n.preventDefault(),delete mo[e]},!1),e===1?t.getContext("webgl",U5)||t.getContext("experimental-webgl",U5):t.getContext("webgl2",U5)}var rp;(function(e){e[e.DENSE=0]="DENSE",e[e.SHARED_BATCH=1]="SHARED_BATCH"})(rp||(rp={}));var _a;(function(e){e[e.RENDER=0]="RENDER",e[e.UPLOAD=1]="UPLOAD",e[e.PIXELS=2]="PIXELS",e[e.DOWNLOAD=3]="DOWNLOAD"})(_a||(_a={}));var Nn;(function(e){e[e.UNPACKED_FLOAT16=0]="UNPACKED_FLOAT16",e[e.UNPACKED_FLOAT32=1]="UNPACKED_FLOAT32",e[e.PACKED_4X1_UNSIGNED_BYTE=2]="PACKED_4X1_UNSIGNED_BYTE",e[e.PACKED_2X2_FLOAT32=3]="PACKED_2X2_FLOAT32",e[e.PACKED_2X2_FLOAT16=4]="PACKED_2X2_FLOAT16"})(Nn||(Nn={}));function sp(e,t){return[t,e]}function She(e,t){return e*t}function ip(e){let t=k.sizeFromShape(e),n=Math.ceil(t/4);return k.sizeToSquarishShape(n)}function fu(e,t){return[Math.max(1,Math.ceil(t/2)),Math.max(1,Math.ceil(e/2))]}function Nhe(e,t){let[n,a]=fu(e,t);return n*a*4}function j5(e,t){let n=e,a,r,s,i,o,l,u,d,h,p;return se().getNumber("WEBGL_VERSION")===2?(a=n.R32F,r=n.R16F,s=n.RGBA16F,i=n.RGBA32F,o=n.RED,u=4,d=1,h=n.HALF_FLOAT,p=n.FLOAT):(a=e.RGBA,r=e.RGBA,s=e.RGBA,i=n.RGBA,o=e.RGBA,u=4,d=4,h=t!=null?t.HALF_FLOAT_OES:null,p=e.FLOAT),l=e.RGBA,{internalFormatFloat:a,internalFormatHalfFloat:r,internalFormatPackedHalfFloat:s,internalFormatPackedFloat:i,textureFormatFloat:o,downloadTextureFormat:l,downloadUnpackNumChannels:u,defaultNumChannels:d,textureTypeHalfFloat:h,textureTypeFloat:p}}function ke(e,t){let n=t();return se().getBool("DEBUG")&&The(e),n}function The(e){let t=e.getError();if(t!==e.NO_ERROR)throw new Error("WebGL Error: "+YN(e,t))}var Ehe=596e-10,Che=65504;function ZN(e){return!!(se().getBool("WEBGL_RENDER_FLOAT32_ENABLED")||e===0||Ehee.getExtension(t),'Extension "'+t+'" not supported on this browser.')}function JN(e,t){let n=gs(e,()=>e.createShader(e.VERTEX_SHADER),"Unable to create vertex WebGLShader.");if(ke(e,()=>e.shaderSource(n,t)),ke(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 QN(e,t){let n=gs(e,()=>e.createShader(e.FRAGMENT_SHADER),"Unable to create fragment WebGLShader.");if(ke(e,()=>e.shaderSource(n,t)),ke(e,()=>e.compileShader(n)),e.getShaderParameter(n,e.COMPILE_STATUS)===!1)throw $he(t,e.getShaderInfoLog(n)),new Error("Failed to compile fragment shader.");return n}var Mhe=/ERROR: [0-9]+:([0-9]+):/g;function $he(e,t){let n=Mhe.exec(t);if(n==null){console.log(`Couldn't parse line number in error: ${t}`),console.log(e);return}let a=+n[1],r=e.split(` `),s=r.length.toString().length+2,i=r.map((h,p)=>k.rightPad((p+1).toString(),s)+h),o=0;for(let h=0;he.createProgram(),"Unable to create WebGLProgram.")}function tT(e,t){if(ke(e,()=>e.linkProgram(t)),e.getProgramParameter(t,e.LINK_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Failed to link vertex and fragment shaders.")}function O0(e,t){if(ke(e,()=>e.validateProgram(t)),e.getProgramParameter(t,e.VALIDATE_STATUS)===!1)throw console.log(e.getProgramInfoLog(t)),new Error("Shader program validation failed.")}function nT(e,t){let n=gs(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return ke(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),ke(e,()=>e.bufferData(e.ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function aT(e,t){let n=gs(e,()=>e.createBuffer(),"Unable to create WebGLBuffer");return ke(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,n)),ke(e,()=>e.bufferData(e.ELEMENT_ARRAY_BUFFER,t,e.STATIC_DRAW)),n}function Rhe(){return se().getNumber("WEBGL_VERSION")===2?1:4}function rT(e){return gs(e,()=>e.createTexture(),"Unable to create WebGLTexture.")}function sT(e,t){let n=se().getNumber("WEBGL_MAX_TEXTURE_SIZE");if(e<=0||t<=0){let a=`[${e}x${t}]`;throw new Error("Requested texture size "+a+" is invalid.")}if(e>n||t>n){let a=`[${e}x${t}]`,r=`[${n}x${n}]`;throw new Error("Requested texture size "+a+" greater than WebGL maximum on this browser / GPU "+r+".")}}function iT(e){return gs(e,()=>e.createFramebuffer(),"Unable to create WebGLFramebuffer.")}function H5(e,t,n,a,r,s,i){let o=e.getAttribLocation(t,n);return o===-1?!1:(ke(e,()=>e.bindBuffer(e.ARRAY_BUFFER,a)),ke(e,()=>e.vertexAttribPointer(o,r,e.FLOAT,!1,s,i)),ke(e,()=>e.enableVertexAttribArray(o)),!0)}function oT(e,t,n){pT(e,n),ke(e,()=>e.activeTexture(e.TEXTURE0+n)),ke(e,()=>e.bindTexture(e.TEXTURE_2D,t))}function Fhe(e,t){pT(e,t),ke(e,()=>e.activeTexture(e.TEXTURE0+t)),ke(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function lT(e,t,n){return gs(e,()=>e.getUniformLocation(t,n),'uniform "'+n+'" not present in program.')}function uT(e,t,n){return e.getUniformLocation(t,n)}function dT(e,t,n,a){ke(e,()=>oT(e,t,a)),ke(e,()=>e.uniform1i(n,a))}function Ohe(e){ke(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),ke(e,()=>e.viewport(0,0,e.canvas.width,e.canvas.height)),ke(e,()=>e.scissor(0,0,e.canvas.width,e.canvas.height))}function D0(e,t,n){ke(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,n)),ke(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,t,0))}function G5(e,t){ke(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,t)),ke(e,()=>e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,null,0))}function lp(e){let t=e.checkFramebufferStatus(e.FRAMEBUFFER);if(t!==e.FRAMEBUFFER_COMPLETE)throw new Error("Error binding framebuffer: "+hT(e,t))}function hT(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 gs(e,t,n){let a=ke(e,()=>t());if(a==null)throw new Error(n);return a}function pT(e,t){let n=e.MAX_COMBINED_TEXTURE_IMAGE_UNITS-1,a=t+e.TEXTURE0;if(an){let r=`[gl.TEXTURE0, gl.TEXTURE${n}]`;throw new Error(`textureUnit must be in ${r}.`)}}function go(e,t=2){return k.sizeFromShape(e.slice(0,e.length-t))}function yo(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 _0(e){let t=[1,1,1];return e.length===0||e.length===1&&e[0]===1||(t=[go(e),...yo(e)]),t}function cT(e,t=!1){let n=se().getNumber("WEBGL_MAX_TEXTURE_SIZE");t&&(n=n*2,e=e.map((r,s)=>s>=e.length-2?k.nearestLargerEven(e[s]):e[s]),e.length===1&&(e=[2,e[0]])),e.length!==2&&(e=k.squeezeShape(e).newShape);let a=k.sizeFromShape(e);if(e.length<=1&&a<=n)return[1,a];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 r=go(e),s=2,i=2;return e.length&&([s,i]=yo(e)),a=r*(s/2)*(i/2),k.sizeToSquarishShape(a).map(o=>o*2)}return k.sizeToSquarishShape(a)}function z0(e){return e%2==0}function up(e,t){if(e=e.slice(-2),t=t.slice(-2),k.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],a=t.slice(-1)[0];if(n===a||z0(n)&&z0(a)&&(e[0]===1||t[0]===1))return!0}return e[1]===t[1]&&z0(e[0])&&z0(t[0])}var P0,L0;function fT(e){if(P0==null){let t=Pr(e);P0=t.getParameter(t.MAX_TEXTURE_SIZE)}return P0}function Dhe(){P0=null}function _he(){L0=null}function mT(e){if(L0==null){let t=Pr(e);L0=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS)}return Math.min(16,L0)}function gT(e){if(e===0)return 0;let t,n=Pr(e);return za(n,"EXT_disjoint_timer_query_webgl2")&&e===2?t=2:za(n,"EXT_disjoint_timer_query")?t=1:t=0,t}function za(e,t){return e.getExtension(t)!=null}function q5(e){try{if(Pr(e)!=null)return!0}catch(t){return console.log("Error when getting WebGL context: ",t),!1}return!1}function yT(e){if(e===0)return!1;let t=Pr(e);if(e===1){if(!za(t,"OES_texture_float"))return!1}else if(!za(t,"EXT_color_buffer_float"))return!1;return K5(t)}function AT(e){if(e===0)return!1;let t=Pr(e);if(e===1){if(!za(t,"OES_texture_float")||!za(t,"WEBGL_color_buffer_float"))return!1}else{if(za(t,"EXT_color_buffer_float"))return K5(t);let n="EXT_color_buffer_half_float";if(za(t,n)){let a=t.getExtension(n);return zhe(t,a)}return!1}return K5(t)}function K5(e){let t=j5(e),n=e.createTexture();e.bindTexture(e.TEXTURE_2D,n);let a=1,r=1;e.texImage2D(e.TEXTURE_2D,0,t.internalFormatFloat,a,r,0,t.textureFormatFloat,t.textureTypeFloat,null);let s=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,n,0);let i=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(n),e.deleteFramebuffer(s),i}function zhe(e,t){let n=j5(e,t),a=e.createTexture();e.bindTexture(e.TEXTURE_2D,a);let r=1,s=1;e.texImage2D(e.TEXTURE_2D,0,n.internalFormatHalfFloat,r,s,0,n.textureFormatFloat,n.textureTypeHalfFloat,null);let i=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,i),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,a,0);let o=e.checkFramebufferStatus(e.FRAMEBUFFER)===e.FRAMEBUFFER_COMPLETE;return e.bindTexture(e.TEXTURE_2D,null),e.bindFramebuffer(e.FRAMEBUFFER,null),e.deleteTexture(a),e.deleteFramebuffer(i),o}function xT(e){return e!==2?!1:Pr(e).fenceSync!=null}function mu(e,t){Array.isArray(e)||(e=[e]),e.forEach(n=>{n!=null&&k.assert(n.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the WebGL backend.`)})}var ze=se();ze.registerFlag("HAS_WEBGL",()=>ze.getNumber("WEBGL_VERSION")>0);ze.registerFlag("WEBGL_VERSION",()=>q5(2)?2:q5(1)?1:0);ze.registerFlag("WEBGL_CHECK_NUMERICAL_PROBLEMS",()=>!1);ze.registerFlag("WEBGL_BUFFER_SUPPORTED",()=>ze.get("WEBGL_VERSION")===2);ze.registerFlag("WEBGL_CPU_FORWARD",()=>!0);ze.registerFlag("WEBGL_FORCE_F16_TEXTURES",()=>!1);ze.registerFlag("WEBGL_PACK",()=>ze.getBool("HAS_WEBGL"));ze.registerFlag("WEBGL_PACK_NORMALIZATION",()=>ze.getBool("WEBGL_PACK"));ze.registerFlag("WEBGL_PACK_CLIP",()=>ze.getBool("WEBGL_PACK"));ze.registerFlag("WEBGL_PACK_DEPTHWISECONV",()=>ze.getBool("WEBGL_PACK"));ze.registerFlag("WEBGL_PACK_BINARY_OPERATIONS",()=>ze.getBool("WEBGL_PACK"));ze.registerFlag("WEBGL_PACK_UNARY_OPERATIONS",()=>ze.getBool("WEBGL_PACK"));ze.registerFlag("WEBGL_PACK_ARRAY_OPERATIONS",()=>ze.getBool("WEBGL_PACK"));ze.registerFlag("WEBGL_PACK_IMAGE_OPERATIONS",()=>ze.getBool("WEBGL_PACK"));ze.registerFlag("WEBGL_PACK_REDUCE",()=>ze.getBool("WEBGL_PACK"));ze.registerFlag("WEBGL_LAZILY_UNPACK",()=>ze.getBool("WEBGL_PACK"));ze.registerFlag("WEBGL_CONV_IM2COL",()=>ze.getBool("WEBGL_PACK"));ze.registerFlag("WEBGL_MAX_TEXTURE_SIZE",()=>fT(ze.getNumber("WEBGL_VERSION")));ze.registerFlag("WEBGL_MAX_TEXTURES_IN_SHADER",()=>mT(ze.getNumber("WEBGL_VERSION")));ze.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION",()=>{let e=ze.getNumber("WEBGL_VERSION");return e===0?0:gT(e)});ze.registerFlag("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE",()=>ze.getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0&&!yf.isMobile());ze.registerFlag("WEBGL_RENDER_FLOAT32_CAPABLE",()=>yT(ze.getNumber("WEBGL_VERSION")));ze.registerFlag("WEBGL_RENDER_FLOAT32_ENABLED",()=>ze.getBool("WEBGL_FORCE_F16_TEXTURES")?!1:ze.getBool("WEBGL_RENDER_FLOAT32_CAPABLE"));ze.registerFlag("WEBGL_DOWNLOAD_FLOAT_ENABLED",()=>AT(ze.getNumber("WEBGL_VERSION")));ze.registerFlag("WEBGL_FENCE_API_ENABLED",()=>xT(ze.getNumber("WEBGL_VERSION")));ze.registerFlag("WEBGL_SIZE_UPLOAD_UNIFORM",()=>ze.getBool("WEBGL_RENDER_FLOAT32_ENABLED")?4:0);ze.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}.`)});ze.registerFlag("WEBGL_FLUSH_THRESHOLD",()=>yf.isMobile()&&ze.getBool("IS_CHROME")?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}.`)});ze.registerFlag("CPU_HANDOFF_SIZE_THRESHOLD",()=>128);function Wn(){let e,t,n,a,r,s,i,o,l,u;return se().getNumber("WEBGL_VERSION")===2?(e="#version 300 es",t="in",n="out",a="in",r="texture",s="outputColor",i="out vec4 outputColor;",o=` bool isnan_custom(float val) { return (val > 0.0 || val < 0.0) ? false : val != 0.0; } bvec4 isnan_custom(vec4 val) { return bvec4(isnan_custom(val.x), isnan_custom(val.y), isnan_custom(val.z), isnan_custom(val.w)); } #define isnan(value) isnan_custom(value) `,l="",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",a="varying",r="texture2D",s="gl_FragColor",i="",o=` #define isnan(value) isnan_custom(value) bool isnan_custom(float val) { return (val > 0. || val < 1. || val == 0.) ? false : true; } bvec4 isnan_custom(vec4 val) { return bvec4(isnan(val.x), isnan(val.y), isnan(val.z), isnan(val.w)); } `,l=` uniform float INFINITY; bool isinf(float val) { return abs(val) == INFINITY; } bvec4 isinf(vec4 val) { return equal(abs(val), vec4(INFINITY)); } `,u=` int round(float value) { return int(floor(value + 0.5)); } ivec4 round(vec4 value) { return ivec4(floor(value + vec4(0.5))); } `),{version:e,attribute:t,varyingVs:n,varyingFs:a,texture2D:r,output:s,defineOutput:i,defineSpecialNaN:o,defineSpecialInf:l,defineRound:u}}function Ao(e,t,n="index"){let a=k.computeStrides(t);return a.map((r,s)=>{let i=`int ${e[s]} = ${n} / ${r}`,o=s===a.length-1?`int ${e[s+1]} = ${n} - ${e[s]} * ${r}`:`index -= ${e[s]} * ${r}`;return`${i}; ${o};`}).join("")}function X5(e){let t=k.computeStrides(e).map(n=>n.toString());return` int getFlatIndex(ivec3 coords) { return coords.x * ${t[0]} + coords.y * ${t[1]} + coords.z; } `}var bT=` 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; } `,Phe=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0,this.outPackingScheme=rp.DENSE;let t=ip(e),n=Wn();this.outputShape=e,this.userCode=` ivec3 outCoordsFromFlatIndex(int index) { ${Ao(["r","c","d"],e)} return ivec3(r, c, d); } void main() { ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]})); int index = 4 * (resTexRC.x * ${t[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); } ${n.output} = result; } `}},Lhe=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outPackingScheme=rp.DENSE;let t=ip(e),n=Wn();this.outputShape=e,this.userCode=` ivec3 outCoordsFromFlatIndex(int index) { ${Ao(["r","c","d"],e)} return ivec3(r, c, d); } void main() { ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]})); int index = 4 * (resTexRC.x * ${t[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)); } ${n.output} = result; } `}},Whe=class{constructor(e){this.variableNames=["A"],this.outTexUsage=_a.DOWNLOAD;let t=Wn();this.outputShape=e,this.userCode=` ${bT} void main() { float x = getAAtOutCoords(); ${t.output} = encode_float(x); } `}},Bhe=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outTexUsage=_a.DOWNLOAD;let t=Wn();this.outputShape=e,this.userCode=` ${bT} void main() { ivec3 coords = getOutputCoords(); float x = getChannel(getAAtOutCoords(), vec2(coords.y, coords.z)); ${t.output} = encode_float(x); } `}},Vhe=class{constructor(e,t,n=!1){this.variableNames=["A"];let a=Wn(),[r,s]=t;this.outputShape=e;let i="result";n&&(i="floor(result * 255. + 0.5)"),this.userCode=` ${X5(e)} void main() { ivec3 coords = getOutputCoords(); int flatIndex = getFlatIndex(coords); int offset = imod(flatIndex, 4); flatIndex = idiv(flatIndex, 4, 1.); int r = flatIndex / ${s}; int c = imod(flatIndex, ${s}); vec2 uv = (vec2(c, r) + halfCR) / vec2(${s}.0, ${r}.0); vec4 values = ${a.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]; } ${a.output} = vec4(${i}, 0., 0., 0.); } `}},Uhe=class{constructor(e,t,n=!1){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let a=Wn(),[r,s]=t;this.outputShape=e;let i="",o="result";n&&(o="floor(result * 255. + 0.5)");for(let l=0;l<=1;l++)for(let u=0;u<=1;u++){let d=l*2+u;i+=` localCoords = coords; if(localCoords[2] + ${u} < ${e[2]}) { localCoords[2] += ${u}; if(localCoords[1] + ${l} < ${e[1]}) { localCoords[1] += ${l}; flatIndex = getFlatIndex(localCoords); offset = imod(flatIndex, 4); flatIndex = idiv(flatIndex, 4, 1.); r = flatIndex / ${s}; c = imod(flatIndex, ${s}); uv = (vec2(c, r) + halfCR) / vec2(${s}.0, ${r}.0); values = ${a.texture2D}(A, uv); if(offset == 0) { result[${d}] = values[0]; } else if(offset == 1) { result[${d}] = values[1]; } else if(offset == 2) { result[${d}] = values[2]; } else { result[${d}] = values[3]; } } } `}this.userCode=` ${X5(e)} void main() { ivec3 coords = getOutputCoords(); vec4 result = vec4(0.); int flatIndex, r, c, offset; ivec3 localCoords; vec2 uv; vec4 values; ${i} ${a.output} = ${o}; } `}},vT={};$e(vT,{bindVertexProgramAttributeStreams:()=>MT,createBufferFromOutputTexture:()=>FT,createFloat16MatrixTexture:()=>NT,createFloat16PackedMatrixTexture:()=>CT,createFloat32MatrixTexture:()=>ST,createIndexBuffer:()=>IT,createPackedMatrixTexture:()=>ET,createUnsignedBytesMatrixTexture:()=>TT,createVertexBuffer:()=>kT,createVertexShader:()=>wT,downloadByteEncodedFloatMatrixFromOutputTexture:()=>DT,downloadFloat32MatrixFromBuffer:()=>OT,downloadMatrixFromPackedOutputTexture:()=>zT,downloadPackedMatrixFromBuffer:()=>_T,getInternalFormatForFloat16MatrixTexture:()=>Y5,getInternalFormatForFloat16PackedMatrixTexture:()=>eb,getInternalFormatForFloat32MatrixTexture:()=>Z5,getInternalFormatForPackedMatrixTexture:()=>Q5,getInternalFormatForUnsignedBytesMatrixTexture:()=>J5,uploadDenseMatrixToTexture:()=>$T,uploadPixelDataToTexture:()=>RT});function wT(e){let t=Wn(),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 JN(e,n)}function kT(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 nT(e,t)}function IT(e){let t=new Uint16Array([0,1,2,2,1,3]);return aT(e,t)}function dp(e,t,n,a,r,s){sT(t,n);let i=rT(e),o=e.TEXTURE_2D;return ke(e,()=>e.bindTexture(o,i)),ke(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_S,e.CLAMP_TO_EDGE)),ke(e,()=>e.texParameteri(o,e.TEXTURE_WRAP_T,e.CLAMP_TO_EDGE)),ke(e,()=>e.texParameteri(o,e.TEXTURE_MIN_FILTER,e.NEAREST)),ke(e,()=>e.texParameteri(o,e.TEXTURE_MAG_FILTER,e.NEAREST)),ke(e,()=>e.texImage2D(o,0,a,t,n,0,r,s,null)),ke(e,()=>e.bindTexture(e.TEXTURE_2D,null)),i}function Z5(e){return e.internalFormatFloat}function ST(e,t,n,a){let[r,s]=sp(t,n);return dp(e,r,s,Z5(a),a.textureFormatFloat,e.FLOAT)}function Y5(e){return e.internalFormatHalfFloat}function NT(e,t,n,a){let[r,s]=sp(t,n);return dp(e,r,s,Y5(a),a.textureFormatFloat,a.textureTypeHalfFloat)}function J5(e){return e.downloadTextureFormat}function TT(e,t,n,a){let[r,s]=sp(t,n);return dp(e,r,s,J5(a),e.RGBA,e.UNSIGNED_BYTE)}function Q5(e){return e.internalFormatPackedFloat}function ET(e,t,n,a){let[r,s]=fu(t,n);return dp(e,r,s,Q5(a),e.RGBA,e.FLOAT)}function eb(e){return e.internalFormatPackedHalfFloat}function CT(e,t,n,a){let[r,s]=fu(t,n);return dp(e,r,s,eb(a),e.RGBA,a.textureTypeHalfFloat)}function MT(e,t,n){let a=0,r=3*4,s=3*4+2*4;return ke(e,()=>e.bindBuffer(e.ARRAY_BUFFER,n)),H5(e,t,"clipSpacePos",n,3,s,a)&&H5(e,t,"uv",n,2,s,r)}function $T(e,t,n,a,r,s){ke(e,()=>e.bindTexture(e.TEXTURE_2D,t));let i,o,l;r instanceof Uint8Array?(i=new Uint8Array(n*a*4),o=e.UNSIGNED_BYTE,l=e.RGBA):(i=new Float32Array(n*a*4),o=e.FLOAT,l=s.internalFormatPackedFloat),i.set(r),ke(e,()=>e.texImage2D(e.TEXTURE_2D,0,l,n,a,0,e.RGBA,o,i)),ke(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function RT(e,t,n){ke(e,()=>e.bindTexture(e.TEXTURE_2D,t)),n.data instanceof Uint8Array?ke(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,n.width,n.height,0,e.RGBA,e.UNSIGNED_BYTE,n.data)):ke(e,()=>e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,n)),ke(e,()=>e.bindTexture(e.TEXTURE_2D,null))}function FT(e,t,n,a){let r=e.createBuffer();ke(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,r));let s=4*4*t*n;return ke(e,()=>e.bufferData(e.PIXEL_PACK_BUFFER,s,e.STREAM_READ)),ke(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,0)),ke(e,()=>e.bindBuffer(e.PIXEL_PACK_BUFFER,null)),r}function OT(e,t,n){let a=e,r=new Float32Array(n);return a.bindBuffer(a.PIXEL_PACK_BUFFER,t),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,r),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),r}function DT(e,t,n,a){let[r,s]=sp(t,n),i=4,o=new Uint8Array(She(t*n,i));return ke(e,()=>e.readPixels(0,0,r,s,a.downloadTextureFormat,e.UNSIGNED_BYTE,o)),new Float32Array(o.buffer)}function _T(e,t,n,a,r,s,i,o){let l=e,u=new Float32Array(Nhe(s,i));return l.bindBuffer(l.PIXEL_PACK_BUFFER,t),l.getBufferSubData(l.PIXEL_PACK_BUFFER,0,u),l.bindBuffer(l.PIXEL_PACK_BUFFER,null),u}function zT(e,t,n){let a=new Float32Array(t*n*4);return ke(e,()=>e.readPixels(0,0,n,t,e.RGBA,e.FLOAT,a)),a}var W0=class{constructor(e){this.outputTexture=null,this.program=null,this.disposed=!1,this.vertexAttrsAreBound=!1,this.itemsToPoll=[];let t=se().getNumber("WEBGL_VERSION");e!=null?(this.gl=e,F0(t,e)):this.gl=Pr(t);let n="WEBGL_color_buffer_float",a="EXT_color_buffer_half_float";if(se().getNumber("WEBGL_VERSION")===1){let r="OES_texture_float",s="OES_texture_half_float";if(this.textureFloatExtension=op(this.gl,r),za(this.gl,s))this.textureHalfFloatExtension=op(this.gl,s);else if(se().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),za(this.gl,a))this.colorBufferHalfFloatExtension=op(this.gl,a);else if(se().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",za(this.gl,n))this.colorBufferFloatExtension=this.gl.getExtension(n);else if(za(this.gl,a))this.colorBufferHalfFloatExtension=this.gl.getExtension(a);else throw new Error("GL context does not support color renderable floats");this.vertexBuffer=kT(this.gl),this.indexBuffer=IT(this.gl),this.framebuffer=iT(this.gl),this.textureConfig=j5(this.gl,this.textureHalfFloatExtension)}get debug(){return se().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;ke(e,()=>e.finish()),ke(e,()=>e.bindFramebuffer(e.FRAMEBUFFER,null)),ke(e,()=>e.deleteFramebuffer(this.framebuffer)),ke(e,()=>e.bindBuffer(e.ARRAY_BUFFER,null)),ke(e,()=>e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null)),ke(e,()=>e.deleteBuffer(this.indexBuffer)),this.disposed=!0}createFloat32MatrixTexture(e,t){return this.throwIfDisposed(),ST(this.gl,e,t,this.textureConfig)}createFloat16MatrixTexture(e,t){return this.throwIfDisposed(),NT(this.gl,e,t,this.textureConfig)}createUnsignedBytesMatrixTexture(e,t){return this.throwIfDisposed(),TT(this.gl,e,t,this.textureConfig)}uploadPixelDataToTexture(e,t){this.throwIfDisposed(),RT(this.gl,e,t)}uploadDenseMatrixToTexture(e,t,n,a){this.throwIfDisposed(),$T(this.gl,e,t,n,a,this.textureConfig)}createFloat16PackedMatrixTexture(e,t){return this.throwIfDisposed(),CT(this.gl,e,t,this.textureConfig)}createPackedMatrixTexture(e,t){return this.throwIfDisposed(),ET(this.gl,e,t,this.textureConfig)}deleteMatrixTexture(e){this.throwIfDisposed(),this.outputTexture===e&&(G5(this.gl,this.framebuffer),this.outputTexture=null),ke(this.gl,()=>this.gl.deleteTexture(e))}downloadByteEncodedFloatMatrixFromOutputTexture(e,t,n){return this.downloadMatrixDriver(e,()=>DT(this.gl,t,n,this.textureConfig))}downloadPackedMatrixFromBuffer(e,t,n,a,r,s){return _T(this.gl,e,t,n,a,r,s,this.textureConfig)}downloadFloat32MatrixFromBuffer(e,t){return OT(this.gl,e,t)}createBufferFromTexture(e,t,n){this.bindTextureToFrameBuffer(e);let a=FT(this.gl,t,n,this.textureConfig);return this.unbindTextureToFrameBuffer(),a}createAndWaitForFence(){let e=this.createFence(this.gl);return this.pollFence(e)}createFence(e){let t,n;if(se().getBool("WEBGL_FENCE_API_ENABLED")){let a=e,r=a.fenceSync(a.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),n=()=>{let s=a.clientWaitSync(r,0,0);return s===a.ALREADY_SIGNALED||s===a.CONDITION_SATISFIED},t=r}else se().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")>0?(t=this.beginQuery(),this.endQuery(),n=()=>this.isQueryAvailable(t,se().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))):n=()=>!0;return{query:t,isFencePassed:n}}downloadMatrixFromPackedTexture(e,t,n){return this.downloadMatrixDriver(e,()=>zT(this.gl,t,n))}createProgram(e){this.throwIfDisposed();let t=this.gl,n=QN(t,e);this.vertexShader==null&&(this.vertexShader=wT(t));let a=eT(t);return ke(t,()=>t.attachShader(a,this.vertexShader)),ke(t,()=>t.attachShader(a,n)),tT(t,a),this.debug&&O0(t,a),this.vertexAttrsAreBound||(this.setProgram(a),this.vertexAttrsAreBound=MT(t,this.program,this.vertexBuffer)),a}deleteProgram(e){this.throwIfDisposed(),e===this.program&&(this.program=null),e!=null&&ke(this.gl,()=>this.gl.deleteProgram(e))}setProgram(e){this.throwIfDisposed(),this.program=e,this.program!=null&&this.debug&&O0(this.gl,this.program),ke(this.gl,()=>this.gl.useProgram(e))}getUniformLocation(e,t,n=!0){return this.throwIfDisposed(),n?lT(this.gl,e,t):uT(this.gl,e,t)}getAttributeLocation(e,t){return this.throwIfDisposed(),ke(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(),dT(this.gl,e,t,n)}setOutputMatrixTexture(e,t,n){this.setOutputMatrixTextureDriver(e,n,t)}setOutputPackedMatrixTexture(e,t,n){this.throwIfDisposed();let[a,r]=fu(t,n);this.setOutputMatrixTextureDriver(e,a,r)}setOutputMatrixWriteRegion(e,t,n,a){this.setOutputMatrixWriteRegionDriver(n,e,a,t)}setOutputPackedMatrixWriteRegion(e,t,n,a){throw new Error("setOutputPackedMatrixWriteRegion not implemented.")}debugValidate(){this.program!=null&&O0(this.gl,this.program),lp(this.gl)}executeProgram(){this.throwIfDisposed(),this.throwIfNoProgram();let e=this.gl;this.debug&&this.debugValidate(),ke(e,()=>e.drawElements(e.TRIANGLES,6,e.UNSIGNED_SHORT,0))}blockUntilAllProgramsCompleted(){this.throwIfDisposed(),ke(this.gl,()=>this.gl.finish())}getQueryTimerExtension(){return this.disjointQueryTimerExtension==null&&(this.disjointQueryTimerExtension=op(this.gl,se().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(se().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION")===2){let n=this.gl,a=this.getQueryTimerExtensionWebGL2(),r=n.createQuery();return n.beginQuery(a.TIME_ELAPSED_EXT,r),r}let e=this.getQueryTimerExtensionWebGL1(),t=e.createQueryEXT();return e.beginQueryEXT(e.TIME_ELAPSED_EXT,t),t}endQuery(){if(se().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 k.repeatedTry(()=>this.disposed||this.isQueryAvailable(e,se().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_VERSION"))),this.getQueryTime(e,se().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,a=this.getQueryTimerExtensionWebGL2(),r=n.getQueryParameter(e,n.QUERY_RESULT_AVAILABLE);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(a.GPU_DISJOINT_EXT)),r&&!this.disjoint}else{let n=this.getQueryTimerExtensionWebGL1(),a=n.getQueryObjectEXT(e,n.QUERY_RESULT_AVAILABLE_EXT);return this.disjoint==null&&(this.disjoint=this.gl.getParameter(n.GPU_DISJOINT_EXT)),a&&!this.disjoint}}pollFence(e){return new Promise(t=>{this.addItemToPoll(()=>e.isFencePassed(),()=>t())})}pollItems(){let e=jhe(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)&&k.repeatedTry(()=>(this.pollItems(),this.itemsToPoll.length===0))}bindTextureToFrameBuffer(e){this.throwIfDisposed(),D0(this.gl,e,this.framebuffer),this.debug&&lp(this.gl)}unbindTextureToFrameBuffer(){this.outputTexture!=null?(D0(this.gl,this.outputTexture,this.framebuffer),this.debug&&lp(this.gl)):G5(this.gl,this.framebuffer)}downloadMatrixDriver(e,t){this.bindTextureToFrameBuffer(e);let n=t();return this.unbindTextureToFrameBuffer(),n}setOutputMatrixTextureDriver(e,t,n){this.throwIfDisposed();let a=this.gl;D0(a,e,this.framebuffer),this.debug&&lp(a),this.outputTexture=e,ke(a,()=>a.viewport(0,0,t,n)),ke(a,()=>a.scissor(0,0,t,n))}setOutputMatrixWriteRegionDriver(e,t,n,a){this.throwIfDisposed(),ke(this.gl,()=>this.gl.scissor(e,t,n,a))}throwIfDisposed(){if(this.disposed)throw new Error("Attempted to use disposed GPGPUContext.")}throwIfNoProgram(){if(this.program==null)throw new Error("No GPU program is currently set.")}};function jhe(e){let t=0;for(;t{let m=k.sizeFromShape(c.shapeInfo.logicalShape);c.shapeInfo.isUniform?r.push(`uniform float ${c.name}${m>1?`[${m}]`:""};`):(r.push(`uniform sampler2D ${c.name};`),r.push(`uniform int offset${c.name};`))});let s=r.join(` `),i=e.map(c=>Ghe(c,t,a)).join(` `),o=t.texShape,l=Wn(),u=Xhe(l),d,h,p=Jhe(l);return t.isPacked?(d=qhe(t.logicalShape,o),h=Yhe(l)):(d=Khe(t.logicalShape,o),h=Zhe(l)),a&&(p+=npe),[p,u,h,s,d,i,n].join(` `)}function gu(e){let t=e.shapeInfo.logicalShape;switch(t.length){case 0:return fpe(e);case 1:return gpe(e);case 2:return Ape(e);case 3:return bpe(e);case 4:return wpe(e);case 5:return kpe(e);case 6:return Ipe(e);default:throw new Error(`${t.length}-D input sampling is not yet supported`)}}function LT(e){switch(e.shapeInfo.logicalShape.length){case 0:return cpe(e);case 1:return mpe(e);case 2:return ype(e);case 3:return xpe(e);default:return vpe(e)}}function Ghe(e,t,n=!1){let a="";n?a+=LT(e):a+=gu(e);let r=e.shapeInfo.logicalShape,s=t.logicalShape;return r.length<=s.length&&(n?a+=Spe(e,t):a+=Npe(e,t)),a}function qhe(e,t){switch(e.length){case 0:return WT();case 1:return ape(e,t);case 2:return hpe(e,t);case 3:return spe(e,t);default:return ope(e,t)}}function Khe(e,t){switch(e.length){case 0:return WT();case 1:return rpe(e,t);case 2:return ppe(e,t);case 3:return ipe(e,t);case 4:return lpe(e,t);case 5:return upe(e,t);case 6:return dpe(e,t);default:throw new Error(`${e.length}-D output sampling is not yet supported`)}}function Xhe(e){return` float sampleTexture(sampler2D textureSampler, vec2 uv) { return ${e.texture2D}(textureSampler, uv).r; } `}function Zhe(e){return` void setOutput(float val) { ${e.output} = vec4(val, 0, 0, 0); } `}function Yhe(e){return` void setOutput(vec4 val) { ${e.output} = val; } `}function Jhe(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); } ${Qhe} ${epe} ${tpe} `}var Qhe=` 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); } `,epe=` 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); } `,tpe=` 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); } `,npe=` 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 WT(){return` int getOutputCoords() { return 0; } `}function ape(e,t){let n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)];return n[0]===1?` int getOutputCoords() { return 2 * int(resultUV.x * ${n[1]}.0); } `:n[1]===1?` int getOutputCoords() { return 2 * int(resultUV.y * ${n[0]}.0); } `:` int getOutputCoords() { ivec2 resTexRC = ivec2(resultUV.yx * vec2(${n[0]}, ${n[1]})); return 2 * (resTexRC.x * ${n[1]} + resTexRC.y); } `}function rpe(e,t){return t[0]===1?` int getOutputCoords() { return int(resultUV.x * ${t[1]}.0); } `:t[1]===1?` int getOutputCoords() { return int(resultUV.y * ${t[0]}.0); } `:` int getOutputCoords() { ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]})); return resTexRC.x * ${t[1]} + resTexRC.y; } `}function spe(e,t){let n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],a=Math.ceil(e[2]/2),r=a*Math.ceil(e[1]/2);return` ivec3 getOutputCoords() { ivec2 resTexRC = ivec2(resultUV.yx * vec2(${n[0]}, ${n[1]})); int index = resTexRC.x * ${n[1]} + resTexRC.y; int b = index / ${r}; index -= b * ${r}; int r = 2 * (index / ${a}); int c = imod(index, ${a}) * 2; return ivec3(b, r, c); } `}function ipe(e,t){let n=Ao(["r","c","d"],e);return` ivec3 getOutputCoords() { ivec2 resTexRC = ivec2(resultUV.yx * vec2(${t[0]}, ${t[1]})); int index = resTexRC.x * ${t[1]} + resTexRC.y; ${n} return ivec3(r, c, d); } `}function ope(e,t){let n=[Math.ceil(t[0]/2),Math.ceil(t[1]/2)],a=Math.ceil(e[e.length-1]/2),r=a*Math.ceil(e[e.length-2]/2),s=r,i="",o="b, r, c";for(let l=2;l=1?d="coords = 0;":d=o.map(g=>`coords.${h[g+u]} = 0;`).join(` `);let p="";i<2&&s>0?p="coords":p=e.shapeInfo.logicalShape.map((g,y)=>`coords.${h[y+u]}`).join(", ");let c="return outputValue;",m=k.sizeFromShape(e.shapeInfo.logicalShape)===1,f=k.sizeFromShape(t.logicalShape)===1;if(s===1&&!m&&!f)c=` return vec4(outputValue.xy, outputValue.xy); `;else if(m&&!f)i===1?c=` return vec4(outputValue.x, outputValue.x, 0., 0.); `:c=` return vec4(outputValue.x); `;else if(o.length){let g=s-2,y=s-1;o.indexOf(g)>-1&&o.indexOf(y)>-1?c="return vec4(outputValue.x);":o.indexOf(g)>-1?c="return vec4(outputValue.x, outputValue.y, outputValue.x, outputValue.y);":o.indexOf(y)>-1&&(c="return vec4(outputValue.xx, outputValue.zz);")}return` vec4 ${r}() { ${l} coords = getOutputCoords(); ${d} vec4 outputValue = get${a}(${p}); ${c} } `}function Npe(e,t){let n=e.name,a=n.charAt(0).toUpperCase()+n.slice(1),r="get"+a+"AtOutCoords",s=t.texShape,i=e.shapeInfo.texShape,o=e.shapeInfo.logicalShape.length,l=t.logicalShape.length;if(!e.shapeInfo.isUniform&&o===l&&e.shapeInfo.flatOffset==null&&k.arraysEqual(i,s))return` float ${r}() { return sampleTexture(${n}, resultUV); } `;let u=kt(l),d=PT(e.shapeInfo.logicalShape,t.logicalShape),h=l-o,p,c=["x","y","z","w","u","v"];o===0?p="":l<2&&d.length>=1?p="coords = 0;":p=d.map(f=>`coords.${c[f+h]} = 0;`).join(` `);let m="";return l<2&&o>0?m="coords":m=e.shapeInfo.logicalShape.map((f,g)=>`coords.${c[g+h]}`).join(", "),` float ${r}() { ${u} coords = getOutputCoords(); ${p} return get${a}(${m}); } `}function kt(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 Au(e,t){let n=JSON.parse(JSON.stringify(e));return n.shapeInfo.logicalShape=t,n}function xu(e,t){return t.map(n=>e[n]).join(", ")}function Tpe(e,t,n,a){let r=t.userCode,s=n.map((c,m)=>{let f={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&&(f.flatOffset=c.texData.slice.flatOffset),{name:t.variableNames[m],shapeInfo:f}}),i=s.map(c=>c.shapeInfo),o={logicalShape:a.shape,texShape:a.texData.texShape,isUniform:!1,isPacked:a.texData.isPacked,flatOffset:null},l=Hhe(s,o,r,t.packedInputs),u=e.createProgram(l),d=null,h=e.getUniformLocation(u,"NAN",!1);se().getNumber("WEBGL_VERSION")===1&&(d=e.getUniformLocation(u,"INFINITY",!1));let p={};for(let c=0;c{let r=n.logicalShape,s=t[a],i=s.shape;if(!k.arraysEqual(r,i))throw Error(`Binary was compiled with different shapes than the current args. Shapes ${r} and ${i} must match`);if(n.isUniform&&s.isUniform)return;let o=n.texShape,l=s.isUniform?null:s.texData.texShape;if(!k.arraysEqual(o,l))throw Error(`Binary was compiled with different texture shapes than the current args. Shape ${o} and ${l} must match`)})}function Epe(e,t,n,a,r){BT(t.inShapeInfos,n),BT([t.outShapeInfo],[a]);let s=a.texData.texture,i=a.texData.texShape;a.texData.isPacked?e.setOutputPackedMatrixTexture(s,i[0],i[1]):e.setOutputMatrixTexture(s,i[0],i[1]),e.setProgram(t.webGLProgram),se().getNumber("WEBGL_VERSION")===1&&t.infLoc!==null&&e.gl.uniform1f(t.infLoc,Infinity),t.nanLoc!==null&&e.gl.uniform1f(t.nanLoc,NaN),n.forEach((o,l)=>{let u=t.program.variableNames[l],d=t.uniformLocations[u],h=t.uniformLocations[`offset${u}`];if(d!=null){if(o.isUniform){if(k.sizeFromShape(o.shape)<2)e.gl.uniform1f(d,o.uniformValues[0]);else{let p=o.uniformValues;p instanceof Float32Array||(p=new Float32Array(p)),e.gl.uniform1fv(d,p)}return}o.texData.slice!=null&&h!=null&&e.gl.uniform1i(h,o.texData.slice.flatOffset),e.setInputMatrixTexture(o.texData.texture,d,l)}}),r!=null&&r(e,t.webGLProgram),e.executeProgram()}function Cpe(e,t,n){let a="";t.concat(n).forEach(i=>{let o=i.texData!=null&&i.texData.slice!=null&&i.texData.slice.flatOffset>0,l=i.isUniform?"uniform":i.texData.texShape;a+=`${i.shape}_${l}_${o}`});let r=e.userCode,s=e.constructor.name;return s+="_"+a+"_"+r,s}var VT={};$e(VT,{addImpl:()=>HT,bincountImpl:()=>Fpe,bincountReduceImpl:()=>Ope,ceilImpl:()=>GT,concatImpl:()=>qT,equalImpl:()=>KT,expImpl:()=>XT,expm1Impl:()=>ZT,floorImpl:()=>YT,gatherNdImpl:()=>Dpe,gatherV2Impl:()=>_pe,greaterEqualImpl:()=>QT,greaterImpl:()=>JT,lessEqualImpl:()=>tE,lessImpl:()=>eE,linSpaceImpl:()=>zpe,logImpl:()=>nE,maxImpl:()=>Ppe,maximumImpl:()=>aE,minimumImpl:()=>rE,multiplyImpl:()=>rb,negImpl:()=>Wpe,notEqualImpl:()=>sE,prodImpl:()=>Vpe,rangeImpl:()=>iE,rsqrtImpl:()=>oE,simpleAbsImpl:()=>Mpe,sliceImpl:()=>sb,sparseFillEmptyRowsImpl:()=>Upe,sparseReshapeImpl:()=>jpe,sparseSegmentReductionImpl:()=>Hpe,squaredDifferenceImpl:()=>lE,stridedSliceImpl:()=>Gpe,stringNGramsImpl:()=>Kpe,stringSplitImpl:()=>Zpe,stringToHashBucketFastImpl:()=>Ype,subImpl:()=>uE,tileImpl:()=>Qpe,topKImpl:()=>ece,transposeImpl:()=>Bpe,uniqueImpl:()=>tce});function UT(e,t){Array.isArray(e)||(e=[e]),e.forEach(n=>{n!=null&&k.assert(n.dtype!=="complex64",()=>`${t} does not support complex64 tensors in the CPU backend.`)})}function Mpe(e){let t=new Float32Array(e.length);for(let n=0;n{let i=M.assertAndGetBroadcastShape(t,n),o=i.length,l=k.computeStrides(i),u=k.sizeFromShape(i),d=k.getTypedArrayFromDType(s,u),h=t.length,p=n.length,c=k.computeStrides(t),m=k.computeStrides(n),f=M.getBroadcastDims(t,i),g=M.getBroadcastDims(n,i);if(f.length+g.length===0)for(let y=0;yx[I]=0);let v=k.locToIndex(x,h,c),b=A.slice(-p);g.forEach(I=>b[I]=0);let w=k.locToIndex(b,p,m);d[y]=e(a[v],r[w])}return[d,i]}}function tb(e){let{inputs:t,backend:n}=e,{real:a,imag:r}=t,s=n.data.get(a.dataId).values,i=n.data.get(r.dataId).values,o=n.makeTensorInfo(a.shape,"complex64"),l=n.data.get(o.dataId);return l.complexTensorInfos={real:n.makeTensorInfo(a.shape,"float32",s),imag:n.makeTensorInfo(r.shape,"float32",i)},o}function nb(e,t,n="float32"){if(n==="complex64"){let r=nb(e,t,"float32"),s=nb(e,t,"float32");return tb({inputs:{real:r,imag:s},backend:e})}let a=k.makeZerosTypedArray(k.sizeFromShape(t),n);return e.makeTensorInfo(t,n,a)}function jT(e){let{inputs:t,backend:n}=e,{x:a}=t;return n.incRef(a.dataId),{dataId:a.dataId,shape:a.shape,dtype:a.dtype}}function $pe(e){let{inputs:t,backend:n}=e,{input:a}=t,r=n.data.get(a.dataId).complexTensorInfos.real,s=n.data.get(r.dataId).values;return n.makeTensorInfo(r.shape,r.dtype,s)}function B0(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dtype:s}=a;if(s==="complex64"){if(r.dtype==="complex64")return jT({inputs:{x:r},backend:n});let i=nb(n,r.shape,r.dtype),o=B0({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),l=tb({inputs:{real:o,imag:i},backend:n});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}if(r.dtype==="complex64"){let i=$pe({inputs:{input:r},backend:n}),o=B0({inputs:{x:i},backend:n,attrs:{dtype:s}});return n.disposeIntermediateTensorInfo(i),o}if(!k.hasEncodingLoss(r.dtype,s)){let i=jT({inputs:{x:r},backend:n});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(s==="int32"){let i=n.data.get(r.dataId).values,o=Int32Array.from(i);return n.makeTensorInfo(r.shape,"int32",o)}if(s==="bool"){let i=n.data.get(r.dataId).values,o=k.toTypedArray([0],r.dtype),[l,u]=Pa((d,h)=>d!==h?1:0)(r.shape,[],i,o,"bool");return n.makeTensorInfo(u,"bool",l)}throw new Error(`Error in Cast: failed to cast ${r.dtype} to ${s}`)}function Ya(e,t,n,a){return n==null?({inputs:r,backend:s})=>{let{a:i,b:o}=r,l=s;UT([i,o],e);let u=l.data.get(i.dataId).values,d=l.data.get(o.dataId).values,h=i.dtype==="string"?M.fromUint8ToStringArray(u):u,p=i.dtype==="string"?M.fromUint8ToStringArray(d):d,c=a||i.dtype,[m,f]=t(i.shape,o.shape,h,p,c);return l.makeTensorInfo(f,c,m)}:({inputs:r,backend:s})=>{let{a:i,b:o}=r,l=s;if(i.dtype==="complex64"||o.dtype==="complex64"){let u=B0({inputs:{x:i},backend:l,attrs:{dtype:"complex64"}}),d=l.data.get(u.dataId),h=d.complexTensorInfos.real,p=d.complexTensorInfos.imag,c=l.data.get(h.dataId).values,m=l.data.get(p.dataId).values,f=B0({inputs:{x:o},backend:l,attrs:{dtype:"complex64"}}),g=l.data.get(f.dataId),y=g.complexTensorInfos.real,A=g.complexTensorInfos.imag,x=l.data.get(y.dataId).values,v=l.data.get(A.dataId).values,[b,w,I]=n(i.shape,o.shape,c,m,x,v),T=l.makeTensorInfo(I,"float32",b),C=l.makeTensorInfo(I,"float32",w),z=tb({inputs:{real:T,imag:C},backend:l});return l.disposeIntermediateTensorInfo(u),l.disposeIntermediateTensorInfo(f),l.disposeIntermediateTensorInfo(T),l.disposeIntermediateTensorInfo(C),z}else{let u=l.data.get(i.dataId).values,d=l.data.get(o.dataId).values,h=a||i.dtype,[p,c]=t(i.shape,o.shape,u,d,h);return l.makeTensorInfo(c,h,p)}}}function ab(e){return(t,n,a,r,s,i)=>{let o=M.assertAndGetBroadcastShape(t,n),l=k.sizeFromShape(o),u=o.length,d=k.computeStrides(o),h=k.getTypedArrayFromDType("float32",l),p=k.getTypedArrayFromDType("float32",l),c=M.getBroadcastDims(t,o),m=M.getBroadcastDims(n,o),f=M.mergeRealAndImagArrays(a,r),g=M.mergeRealAndImagArrays(s,i),y=t.length,A=k.computeStrides(t),x=n.length,v=k.computeStrides(n);if(c.length+m.length===0)for(let b=0;bI[S]=0);let T=k.locToIndex(I,y,A),C=w.slice(-x);m.forEach(S=>C[S]=0);let z=k.locToIndex(C,x,v),$=e(f[T*2],f[T*2+1],g[z*2],g[z*2+1]);h[b]=$.real,p[b]=$.imag}return[h,p,o]}}var HT=Pa((e,t)=>e+t),Rpe=ab((e,t,n,a)=>({real:e+n,imag:t+a})),Vwe=Ya(Os,HT,Rpe);function Fpe(e,t,n,a,r){let s=k.sizeFromShape(a),i=k.makeZerosTypedArray(r,n);for(let o=0;o=r||(s>0?i[l]+=t[o]:i[l]+=1)}return i}function Ope(e,t,n,a=!1){let r=e.shape[0],s=e.shape[1],i=Pe([r,n],t.dtype);for(let o=0;o=n||(a?i.set(1,o,u):t.size>0?i.set(i.get(o,u)+t.get(o,l),o,u):i.set(i.get(o,u)+1,o,u))}return i}function bu(e){return(t,n,a)=>{let r=k.getTypedArrayFromDType(n,t.length);for(let s=0;s{let{x:i}=a;if(UT(i,e),i.dtype==="string"||n==="string")throw new Error("unaryKernelFunc does not support string input/output");let o=s,l=o.data.get(i.dataId).values,u=n||i.dtype,d=t(l,u,r);return o.makeTensorInfo(i.shape,u,d)}}var GT=bu(e=>Math.ceil(e)),Uwe=vu(Ni,GT);function qT(e,t,n,a){let r=k.getArrayFromDType(n,k.sizeFromShape(t));if(a&&n!=="string"){let s=0;e.forEach(i=>{let o=k.sizeFromShape(i.shape);r.set(i.vals,s),s+=o})}else{let s=0;e.forEach(i=>{let o=n==="string"?M.fromUint8ToStringArray(i.vals):i.vals,l=0;for(let u=0;ue===t?1:0),jwe=Ya(ol,KT,null,"bool"),XT=bu(e=>Math.exp(e)),Hwe=vu(Ei,XT),ZT=bu(e=>Math.expm1(e)),Gwe=vu(ll,ZT),YT=bu(e=>Math.floor(e)),qwe=vu(Ci,YT);function Dpe(e,t,n,a,r,s,i,o,l){let u=Pe([a,s],n);for(let d=0;d=l/s)throw new Error(`Invalid indices: ${h} does not index into ${o}`);for(let c=0;ce>t?1:0),Kwe=Ya(hl,JT,null,"bool"),QT=Pa((e,t)=>e>=t?1:0),Xwe=Ya(Mi,QT,null,"bool"),eE=Pa((e,t)=>ee<=t?1:0),Ywe=Ya(ml,tE,null,"bool");function zpe(e,t,n){let a=(t-e)/(n-1),r=k.makeZerosTypedArray(n,"float32");r[0]=e;for(let s=1;sMath.log(e)),Jwe=vu($i,nE);function Ppe(e,t,n,a){let r=k.getTypedArrayFromDType(a,k.sizeFromShape(n));for(let s=0;so)&&(o=u)}r[s]=o}return r}var aE=Pa((e,t)=>Math.max(e,t)),Qwe=Ya(Ri,aE),rE=Pa((e,t)=>Math.min(e,t)),e7e=Ya(Fi,rE),rb=Pa((e,t)=>e*t),Lpe=ab((e,t,n,a)=>({real:e*n-t*a,imag:e*a+t*n})),t7e=Ya(Oi,rb,Lpe);function Wpe(e,t,n){let a=k.createScalarValue(-1,n);return rb([],t,a,e,n)}var sE=Pa((e,t)=>e!==t?1:0),n7e=Ya(vl,sE,null,"bool");function Bpe(e,t,n,a,r){let s=t.length,i=k.sizeFromShape(t),o=k.computeStrides(t),l=k.computeStrides(r),u=k.getTypedArrayFromDType(n,k.sizeFromShape(r));for(let d=0;d1;if(r||s||i)return k.makeZerosTypedArray(0,a);let o=Math.abs(Math.ceil((t-e)/n)),l=k.makeZerosTypedArray(o,a);t1/Math.sqrt(e)),a7e=vu(Di,oE);function sb(e,t,n,a,r){let s=Cn.isSliceContinous(a,t,n),i=k.sizeFromShape(n),o=k.computeStrides(a);if(s){let h=Cn.computeFlatOffset(t,o);return r==="string"?e.slice(h,h+i):e.subarray(h,h+i)}let l=r==="string"?M.fromUint8ToStringArray(e):e,u=Pe(a,r,l),d=Pe(n,r);for(let h=0;hm+t[f]);d.set(u.get(...c),...p)}return r==="string"?M.fromStringArrayToUint8(d.values):d.values}function Upe(e,t,n,a,r,s,i){let o=t[0],l=s[0],u=new Array(l),d=new Array(o),h=t[1];if(l===0){if(o!==0)throw new Error(`Received SparseTensor with denseShape[0] = 0 but indices.shape[0] = ${o}`);let g=k.getArrayFromDType(n,0),y=k.getArrayFromDType(r,0);return[g,[0,h],y,u,d]}let p=!0,c=0,m=new Array(l).fill(0);for(let g=0;g=l)throw new Error(`indices(${g}, 0) is invalid: ${y} >= ${l}`);++m[y],p=p&&y>=c,c=y}let f=!0;for(let g=0;g0&&(m[g]+=m[g-1])}if(f&&p){let g=e,y=a;for(let A=0;A0){c[p-1]=1;for(let g=p-2;g>=0;--g)c[g]=c[g+1]*a[g+1]}let m=[];if(o>0){m[o-1]=1;for(let g=o-2;g>=0;--g)m[g]=m[g+1]*l[g+1]}let f=k.getArrayFromDType(n,i*o);for(let g=0;g0?r[o-1]+1:0;if(d<0)throw new Error("segment ids must be >= 0");let h=t.slice();h[0]=d;let p=h.reduce((A,x)=>A*x,1),c=k.getArrayFromDType(n,p);if(o===0)return d>0&&c.fill(i),[c,h];if(d<=0)throw new Error("segment ids must be >= 0");let m=0,f=1,g=0,y=r[m];for(;;){let A=0;if(f=A)throw new Error("segment ids are not increasing")}if(y<0||y>=d)throw new Error(`Segment id ${y} out of range [0, ${d}), possibly because segmentIds input is not sorted.`);y>g&&c.fill(i,g*u,y*u);for(let x=m;x=l[0])throw new Error(`Bad: indices[${x}] == ${a[x]} out of range [0, ${l[0]})`);for(let b=0;bo)break}return g{let n=e-t;return n*n}),r7e=Ya(_i,lE);function Gpe(e,t,n,a){let r=Pe(e,t.dtype);for(let s=0;s0?0:i-o),p=0;p+=l*this.leftPad.length;for(let g=0;gg.forEach(y=>c[m++]=y);for(let g=0;g0){f(e[h+d-1]);for(let g=0;g0){let o=t[0];if(o!==0)throw new Error(`First split value must be 0, got ${o}`);for(let l=1;l=o;if(u=u&&t[l]<=n,!u)throw new Error(`Invalid split value ${t[l]}, must be in [${o}, ${n}]`);o=t[l]}if(o!==n)throw new Error(`Last split value must be data size. Expected ${n}, got ${o}`)}let r=a-1,s=k.getArrayFromDType("int32",a);if(n===0||a===0){let o=new Array(n);for(let l=0;l<=r;++l)s[l]=0;return[o,s]}s[0]=0;for(let o=1;o<=r;++o){let l=t[o]-t[o-1],u=0;this.nGramWidths.forEach(d=>{u+=this.getNumNGrams(l,d)}),this.preserveShort&&l>0&&u===0&&(u=1),s[o]=s[o-1]+u}let i=new Array(s[r]);for(let o=0;o{let h=t[o+1]-t[o],p=this.getNumNGrams(h,d);this.createNGrams(e,l,i,u,p,d),u+=p}),this.preserveShort&&u===s[o]){let d=t[o+1]-t[o];if(d===0)continue;let h=d+2*this.padWidth,p=1;this.createNGrams(e,l,i,u,p,h)}}return[i,s]}};function Kpe(e,t,n,a,r,s,i,o){return new qpe(n,a,r,s,i,o).compute(e,t)}function Xpe(e,t,n){if(!e.length)return[];if(t.length===0){let s=new Array(e.length);for(let i=0;ie-t),Jpe=ab((e,t,n,a)=>({real:e-n,imag:t-a})),s7e=Ya(zi,uE,Jpe);function Qpe(e,t){let n=new Array(e.rank);for(let r=0;rx.value-A.value);let f=h*a,g=l.subarray(f,f+a),y=u.subarray(f,f+a);for(let A=0;A{for(let g=0;g`${e}.${n}`)}function Bn(e,t){return t===1?[e]:cE(e,t)}function Pce(e,t){if(e===1)return"rc";let n="";for(let a=0;a ${t[0]}`;let a="";for(let r=e-2;r= ${t[r]}`,r= ${t}; bool rEdge = rp1 >= ${n}; `}function Uce(e,t){let n=e.length,a=Wce(n,t);return n===1?`getA(rc), rc + 1 >= ${e[0]} ? 0. : getA(rc + 1), 0, 0`:`getA(${a[0]}), cEdge ? 0. : getA(${a[1]}), rEdge ? 0. : getA(${a[2]}), rEdge || cEdge ? 0. : getA(${a[3]})`}var fE=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;let n="";for(let a=0;a<4;a++){let r="thisRC = rc;";a%2==1&&(r+="thisRC.z += 1;"),a>1&&(r+="thisRC.y += 1;"),n+=` ${r} ${a>0?"if(thisRC.y < rows && thisRC.z < cols){":""} int flatIndex = getFlatIndex(thisRC); ivec3 inputRC = inputCoordsFromReshapedOutCoords(flatIndex); vec2 inputRCInnerDims = vec2(float(inputRC.y),float(inputRC.z)); result[${a}] = getChannel(getA(inputRC.x, inputRC.y, inputRC.z), inputRCInnerDims); ${a>0?"}":""} `}this.userCode=` ${jce(t)} ${X5(e)} void main() { ivec3 rc = getOutputCoords(); vec4 result = vec4(0.); ivec3 thisRC; int rows = ${e[1]}; int cols = ${e[2]}; ${n} setOutput(result); } `}};function jce(e){return` ivec3 inputCoordsFromReshapedOutCoords(int index) { ${Ao(["r","c","d"],e)} return ivec3(r, c, d); } `}var Hce=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 a=gE(t,n),r=yE(e,a,n);r in this.freeTextures||(this.freeTextures[r]=[]),r in this.usedTextures||(this.usedTextures[r]=[]);let s=mE(e,a,this.gpgpu.gl,this.gpgpu.textureConfig,n);if(this.freeTextures[r].length>0){this.numFreeTextures--,this.numUsedTextures++,this._numBytesFree-=s,this.log();let o=this.freeTextures[r].shift();return this.usedTextures[r].push(o),o}let i;return a===Nn.PACKED_2X2_FLOAT32?i=this.gpgpu.createPackedMatrixTexture(e[0],e[1]):a===Nn.PACKED_2X2_FLOAT16?i=this.gpgpu.createFloat16PackedMatrixTexture(e[0],e[1]):a===Nn.UNPACKED_FLOAT32?i=this.gpgpu.createFloat32MatrixTexture(e[0],e[1]):a===Nn.UNPACKED_FLOAT16?i=this.gpgpu.createFloat16MatrixTexture(e[0],e[1]):a===Nn.PACKED_4X1_UNSIGNED_BYTE&&(i=this.gpgpu.createUnsignedBytesMatrixTexture(e[0],e[1])),this.usedTextures[r].push(i),this.numUsedTextures++,this._numBytesAllocated+=s,this.log(),i}releaseTexture(e,t,n,a){if(this.freeTextures==null)return;let r=gE(n,a),s=yE(t,r,a);s in this.freeTextures||(this.freeTextures[s]=[]);let i=mE(t,r,this.gpgpu.gl,this.gpgpu.textureConfig,a),o=se().get("WEBGL_DELETE_TEXTURE_THRESHOLD");o!==-1&&this._numBytesAllocated>o?(this.gpgpu.deleteMatrixTexture(e),this._numBytesAllocated-=i):(this.freeTextures[s].push(e),this.numFreeTextures++,this._numBytesFree+=i),this.numUsedTextures--;let l=this.usedTextures[s],u=l.indexOf(e);if(u<0)throw new Error("Cannot release a texture that was never provided by this texture manager");l.splice(u,1),this.log()}log(){if(!this.logEnabled)return;let e=this.numFreeTextures+this.numUsedTextures;console.log("Free/Used",`${this.numFreeTextures} / ${this.numUsedTextures}`,`(${e})`);let t=this._numBytesFree/this._numBytesAllocated;console.log(`Bytes allocated: ${this._numBytesAllocated}`),console.log(`Bytes unused: ${this._numBytesFree} (${Math.round(100*t)}%)`)}get numBytesAllocated(){return this._numBytesAllocated}get numBytesFree(){return this._numBytesFree}getNumUsedTextures(){return this.numUsedTextures}getNumFreeTextures(){return this.numFreeTextures}dispose(){if(this.freeTextures!=null){for(let e in this.freeTextures)this.freeTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});for(let e in this.usedTextures)this.usedTextures[e].forEach(t=>{this.gpgpu.deleteMatrixTexture(t)});this.freeTextures=null,this.usedTextures=null,this.numUsedTextures=0,this.numFreeTextures=0,this._numBytesAllocated=0,this._numBytesFree=0}}};function Gce(e,t){let n=e;if(t===n.R32F)return 4;if(t===n.R16F)return 2;if(t===n.RGBA32F||t===e.RGBA)return 16;if(t===n.RGBA16F)return 8;throw new Error(`Unknown internal format ${t}`)}function mE(e,t,n,a,r){let s=qce(t,a),i;if(r){let[l,u]=fu(e[0],e[1]);i=l*u}else{let[l,u]=sp(e[0],e[1]);i=l*u}let o=Gce(n,s);return i*o}function qce(e,t){switch(e){case Nn.PACKED_2X2_FLOAT32:return Q5(t);case Nn.PACKED_2X2_FLOAT16:return eb(t);case Nn.UNPACKED_FLOAT32:return Z5(t);case Nn.UNPACKED_FLOAT16:return Y5(t);case Nn.PACKED_4X1_UNSIGNED_BYTE:return J5(t);default:throw new Error(`Unknown physical texture type ${e}`)}}function Kce(e){return se().getBool("WEBGL_RENDER_FLOAT32_ENABLED")?e?Nn.PACKED_2X2_FLOAT32:Nn.UNPACKED_FLOAT32:e?Nn.PACKED_2X2_FLOAT16:Nn.UNPACKED_FLOAT16}function gE(e,t){if(e===_a.UPLOAD)return Nn.PACKED_2X2_FLOAT32;if(e===_a.RENDER||e==null)return Kce(t);if(e===_a.DOWNLOAD||e===_a.PIXELS)return Nn.PACKED_4X1_UNSIGNED_BYTE;throw new Error(`Unknown logical texture type ${e}`)}function yE(e,t,n){return`${e[0]}_${e[1]}_${t}_${n}`}var Qs=class{constructor(e,t){this.variableNames=["A"],this.outputShape=e,this.userCode=` float unaryOperation(float x) { ${t} } void main() { float x = getAAtOutCoords(); float y = unaryOperation(x); setOutput(y); } `}},gr="if (isnan(x)) return x;",Xce="return x;",AE="return abs(x);",Zce="return (x >= 0.0) ? x : (exp(x) - 1.0);",Yce=gr+` return (x < 0.0) ? 0.0 : x; `,Jce=gr+` return (x < 0.0) ? 0.0 : min(6.0, x); `,V0="return x;",Qce="return 1.0 / (1.0 + exp(-1.0 * x));",efe="return x;",tfe=` 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; `,nfe=` 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; `,afe=` 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; `,rfe="return 1.0 / (1.0 + exp(-1.0 * x));",wu=class{constructor(e,t){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode=` vec4 unaryOperation(vec4 x) { ${t} } void main() { vec4 x = getAAtOutCoords(); vec4 y = unaryOperation(x); setOutput(y); } `}},sfe=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!1,this.outputShape=e;let t=e.length,n=Bn("rc",t),a=kt(t),r=Pce(t,n),s=n.slice(-2),i=t<=1?"rc":`vec2(${s.join(",")})`;this.userCode=` void main() { ${a} rc = getOutputCoords(); vec4 packedInput = getA(${r}); setOutput(getChannel(packedInput, ${i})); } `}},ife=us.whereImpl,ofe=1e-7,lfe=1e-4,ob={};function ufe(e){return e in ob||(ob[e]={}),ob[e]}var dfe=()=>se().getNumber("CPU_HANDOFF_SIZE_THRESHOLD"),hfe=600;function pfe(){return se().global.screen==null?1024:se().global.screen.height*se().global.screen.width*window.devicePixelRatio*hfe/1024/1024}var xE=class extends Wc{constructor(e){super();if(this.pendingRead=new WeakMap,this.pendingDisposal=new WeakSet,this.dataRefCount=new WeakMap,this.numBytesInGPU=0,this.uploadWaitMs=0,this.downloadWaitMs=0,this.lastGlFlushTime=0,this.warnedAboutMemory=!1,this.pendingDeletes=0,this.disposed=!1,!se().getBool("HAS_WEBGL"))throw new Error("WebGL is not supported on this device");if(e==null){let t=Pr(se().getNumber("WEBGL_VERSION"));this.binaryCache=ufe(se().getNumber("WEBGL_VERSION")),this.gpgpu=new W0(t),this.canvas=t.canvas,this.gpgpuCreatedLocally=!0}else this.gpgpu=e,this.binaryCache={},this.gpgpuCreatedLocally=!1,this.canvas=e.gl.canvas;this.textureManager=new Hce(this.gpgpu),this.numMBBeforeWarning=pfe(),this.texData=new f1(this,Ps())}nextDataId(){return xE.nextDataId++}numDataIds(){return this.texData.numDataIds()-this.pendingDeletes}write(e,t,n){if((se().getBool("WEBGL_CHECK_NUMERICAL_PROBLEMS")||se().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 a={id:this.nextDataId()};return this.texData.set(a,{shape:t,dtype:n,values:e,usage:_a.UPLOAD,refCount:1}),a}refCount(e){return this.texData.has(e)?this.texData.get(e).refCount:0}incRef(e){let t=this.texData.get(e);t.refCount++}decRef(e){if(this.texData.has(e)){let t=this.texData.get(e);t.refCount--}}move(e,t,n,a,r){if(se().getBool("DEBUG")&&this.checkNumericalProblems(t),a==="complex64")throw new Error("Cannot write to a complex64 dtype. Please use tf.complex(real, imag).");this.texData.set(e,{shape:n,dtype:a,values:t,usage:_a.UPLOAD,refCount:r})}disposeIntermediateTensorInfo(e){this.disposeData(e.dataId)}readSync(e){let t=this.texData.get(e),{values:n,dtype:a,complexTensorInfos:r,slice:s,shape:i,isPacked:o}=t;if(s!=null){let h;o?h=new wu(i,V0):h=new Qs(i,V0);let p=this.runWebGLProgram(h,[{dataId:e,shape:i,dtype:a}],a),c=this.readSync(p.dataId);return this.disposeIntermediateTensorInfo(p),c}if(n!=null)return this.convertAndCacheOnCPU(e);if(a==="string")return n;let l=this.activeTimers!=null,u;l&&(u=k.now());let d;if(a==="complex64"){let h=this.readSync(r.real.dataId),p=this.readSync(r.imag.dataId);d=M.mergeRealAndImagArrays(h,p)}else d=this.getValuesFromTexture(e);return l&&(this.downloadWaitMs+=k.now()-u),this.convertAndCacheOnCPU(e,d)}async read(e){if(this.pendingRead.has(e)){let c=this.pendingRead.get(e);return new Promise(m=>c.push(m))}let t=this.texData.get(e),{values:n,shape:a,slice:r,dtype:s,complexTensorInfos:i,isPacked:o}=t;if(r!=null){let c;o?c=new wu(a,V0):c=new Qs(a,V0);let m=this.runWebGLProgram(c,[{dataId:e,shape:a,dtype:s}],s),f=this.read(m.dataId);return this.disposeIntermediateTensorInfo(m),f}if(n!=null)return this.convertAndCacheOnCPU(e);if(!se().getBool("WEBGL_DOWNLOAD_FLOAT_ENABLED")&&se().getNumber("WEBGL_VERSION")===2)throw new Error("tensor.data() with WEBGL_DOWNLOAD_FLOAT_ENABLED=false and WEBGL_VERSION=2 not yet supported.");let l=null,u;if(s!=="complex64"&&se().get("WEBGL_BUFFER_SUPPORTED")){u=this.decode(e);let c=this.texData.get(u.dataId);l=this.gpgpu.createBufferFromTexture(c.texture,...ip(a))}this.pendingRead.set(e,[]),s!=="complex64"&&await this.gpgpu.createAndWaitForFence();let d;if(s==="complex64"){let c=await Promise.all([this.read(i.real.dataId),this.read(i.imag.dataId)]),m=c[0],f=c[1];d=M.mergeRealAndImagArrays(m,f)}else if(l==null)d=this.getValuesFromTexture(e);else{let c=k.sizeFromShape(a);d=this.gpgpu.downloadFloat32MatrixFromBuffer(l,c)}u!=null&&this.disposeIntermediateTensorInfo(u);let h=this.convertAndCacheOnCPU(e,d),p=this.pendingRead.get(e);return this.pendingRead.delete(e),p.forEach(c=>c(h)),this.pendingDisposal.has(e)&&(this.pendingDisposal.delete(e),this.disposeData(e)&&Ps().removeDataId(e,this),this.pendingDeletes--),h}bufferSync(e){let t=this.readSync(e.dataId),n=t;if(e.dtype==="string")try{n=t.map(a=>k.decodeString(a))}catch(a){throw new Error("Failed to decode encoded string bytes into utf-8")}return Pe(e.shape,e.dtype,n)}checkNumericalProblems(e){if(e!=null)for(let t=0;t0}async time(e){let t=this.activeTimers,n=[],a=!1;this.programTimersStack==null?(this.programTimersStack=n,a=!0):this.activeTimers.push(n),this.activeTimers=n,e();let r=k.flatten(this.activeTimers.map(o=>o.query)).filter(o=>o!=null),s=k.flatten(this.activeTimers.map(o=>o.name)).filter(o=>o!=null);this.activeTimers=t,a&&(this.programTimersStack=null);let i={uploadWaitMs:this.uploadWaitMs,downloadWaitMs:this.downloadWaitMs,kernelMs:null,wallMs:null};if(se().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0){let o=await Promise.all(r);i.kernelMs=k.sum(o),i.getExtraProfileInfo=()=>o.map((l,u)=>({name:s[u],ms:l})).map(l=>`${l.name}: ${l.ms}`).join(", ")}else i.kernelMs={error:"WebGL query timers are not supported in this environment."};return this.uploadWaitMs=0,this.downloadWaitMs=0,i}memory(){return{unreliable:!1,numBytesInGPU:this.numBytesInGPU,numBytesInGPUAllocated:this.textureManager.numBytesAllocated,numBytesInGPUFree:this.textureManager.numBytesFree}}startTimer(){return se().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?this.gpgpu.beginQuery():{startMs:k.now(),endMs:null}}endTimer(e){return se().getNumber("WEBGL_DISJOINT_QUERY_TIMER_EXTENSION_RELIABLE")>0?(this.gpgpu.endQuery(),e):(e.endMs=k.now(),e)}async getQueryTime(e){if(se().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:a,usage:r,isPacked:s,slice:i}=this.texData.get(e),o=i&&i.origDataId||e,l=this.dataRefCount.get(o);l>1?this.dataRefCount.set(o,l-1):(this.dataRefCount.delete(o),t!=null&&(this.numBytesInGPU-=this.computeBytes(a,n),this.textureManager.releaseTexture(t,a,r,s)));let u=this.texData.get(e);u.texture=null,u.texShape=null,u.isPacked=!1,u.slice=null}getTexture(e){return this.uploadToGPU(e),this.texData.get(e).texture}getDataInfo(e){return this.texData.get(e)}shouldExecuteOnCPU(e,t=dfe){return se().getBool("WEBGL_CPU_FORWARD")&&e.every(n=>this.texData.get(n.dataId).texture==null&&k.sizeFromShape(n.shape)0&&k.isString(n[0])){let r=n.map(s=>k.encodeString(s));a=this.write(r,e,t)}else a=this.write(n,e,t);return this.texData.get(a).usage=null,{dataId:a,shape:e,dtype:t}}makeOutput(e,t,n){let{dataId:a}=this.makeTensorInfo(e,t,n);return Ps().makeTensorFromDataId(a,e,t,this)}unpackTensor(e){let t=new sfe(e.shape);return this.runWebGLProgram(t,[e],e.dtype)}packTensor(e){let t=new Lce(e.shape),n=!0;return this.runWebGLProgram(t,[e],e.dtype,null,n)}packedReshape(e,t){let n=[go(e.shape),...yo(e.shape)],a={dtype:e.dtype,shape:n,dataId:e.dataId},r=[go(t),...yo(t)],s=new fE(r,n),i=!0,o=this.runWebGLProgram(s,[a],e.dtype,null,i);return{dataId:o.dataId,shape:t,dtype:o.dtype}}decode(e){let t=this.texData.get(e),{isPacked:n,shape:a,dtype:r}=t,s=_0(a),i;n?i=new Lhe(s):i=new Phe(s);let o=!0,l=this.runWebGLProgram(i,[{shape:s,dtype:r,dataId:e}],r,null,o);return{dtype:r,shape:a,dataId:l.dataId}}runWebGLProgram(e,t,n,a,r=!1){let s=this.makeTensorInfo(e.outputShape,n),i=this.texData.get(s.dataId);if(e.packedOutput&&(i.isPacked=!0),e.outPackingScheme===rp.DENSE){let f=ip(e.outputShape);i.texShape=f.map(g=>g*2)}if(e.outTexUsage!=null&&(i.usage=e.outTexUsage),k.sizeFromShape(s.shape)===0)return i.values=k.getTypedArrayFromDType(s.dtype,0),s;let o=[],l=t.map(f=>{if(f.dtype==="complex64")throw new Error("GPGPUProgram does not support complex64 input. For complex64 dtypes, please separate the program into real and imaginary parts.");let g=this.texData.get(f.dataId);if(g.texture==null){if(!e.packedInputs&&k.sizeFromShape(f.shape)<=se().getNumber("WEBGL_SIZE_UPLOAD_UNIFORM"))return{shape:f.shape,texData:null,isUniform:!0,uniformValues:g.values};e.packedInputs&&(g.isPacked=!0,g.shape=f.shape)}else if(!!g.isPacked!=!!e.packedInputs)f=g.isPacked?this.unpackTensor(f):this.packTensor(f),o.push(f),g=this.texData.get(f.dataId);else if(g.isPacked&&!up(g.shape,f.shape)){let y=f,A=f.shape;f.shape=g.shape,f=this.packedReshape(f,A),o.push(f),g=this.texData.get(f.dataId),y.shape=A}return this.uploadToGPU(f.dataId),{shape:f.shape,texData:g,isUniform:!1}});this.uploadToGPU(s.dataId);let u={shape:s.shape,texData:i,isUniform:!1},d=Cpe(e,l,u),h=this.getAndSaveBinary(d,()=>Tpe(this.gpgpu,e,l,u)),p=this.activeTimers!=null,c;p&&(c=this.startTimer()),Epe(this.gpgpu,h,l,u,a),o.forEach(f=>this.disposeIntermediateTensorInfo(f)),p&&(c=this.endTimer(c),this.activeTimers.push({name:e.constructor.name,query:this.getQueryTime(c)}));let m=se().get("WEBGL_FLUSH_THRESHOLD");if(m>0){let f=k.now();f-this.lastGlFlushTime>m&&(this.gpgpu.gl.flush(),this.lastGlFlushTime=f)}if(!se().getBool("WEBGL_LAZILY_UNPACK")&&i.isPacked&&r===!1){let f=this.unpackTensor(s);return this.disposeIntermediateTensorInfo(s),f}return s}compileAndRun(e,t,n,a,r=!1){return n=n||t[0].dtype,this.runWebGLProgram(e,t,n,a,r)}getAndSaveBinary(e,t){return e in this.binaryCache||(this.binaryCache[e]=t()),this.binaryCache[e]}getTextureManager(){return this.textureManager}dispose(){this.disposed||(se().getBool("IS_TEST")||Object.keys(this.binaryCache).forEach(e=>{this.gpgpu.deleteProgram(this.binaryCache[e].webGLProgram),delete this.binaryCache[e]}),this.textureManager.dispose(),this.canvas!=null&&typeof HTMLCanvasElement!="undefined"&&this.canvas instanceof HTMLCanvasElement?this.canvas.remove():this.canvas=null,this.gpgpuCreatedLocally&&(this.gpgpu.program=null,this.gpgpu.dispose()),this.disposed=!0)}floatPrecision(){return this.floatPrecisionValue==null&&(this.floatPrecisionValue=Z(()=>{if(!se().get("WEBGL_RENDER_FLOAT32_ENABLED")){let e=se().getBool("DEBUG");se().set("DEBUG",!1);let t=this.abs(Re(1e-8)).dataSync()[0];if(se().set("DEBUG",e),t>0)return 32}return 16})),this.floatPrecisionValue}epsilon(){return this.floatPrecision()===32?ofe:lfe}uploadToGPU(e){let t=this.texData.get(e),{shape:n,dtype:a,values:r,texture:s,usage:i,isPacked:o}=t;if(s!=null)return;let l=this.activeTimers!=null,u;l&&(u=k.now());let d=t.texShape;if(d==null&&(d=cT(n,o),t.texShape=d),r!=null){let h=_0(n),p,c=d[1],m=d[0],f=r instanceof Uint8Array;o?([c,m]=fu(d[0],d[1]),p=new Uhe(h,[m,c],f)):p=new Vhe(h,[m,c],f);let g=this.makeTensorInfo([m,c],a);f?this.texData.get(g.dataId).usage=_a.PIXELS:this.texData.get(g.dataId).usage=_a.UPLOAD,this.gpgpu.uploadDenseMatrixToTexture(this.getTexture(g.dataId),c,m,r);let y=!0,A=this.runWebGLProgram(p,[g],a,null,y),x=this.texData.get(A.dataId);t.texture=x.texture,t.texShape=x.texShape,t.isPacked=x.isPacked,t.usage=x.usage,this.disposeIntermediateTensorInfo(g),this.texData.delete(A.dataId),t.values=null,l&&(this.uploadWaitMs+=k.now()-u)}else{let h=this.acquireTexture(d,i,a,o);t.texture=h}}convertAndCacheOnCPU(e,t){let n=this.texData.get(e),{dtype:a}=n;return this.releaseGPUData(e),t!=null&&(n.values=cfe(t,a)),n.values}acquireTexture(e,t,n,a){if(this.numBytesInGPU+=this.computeBytes(e,n),!this.warnedAboutMemory&&this.numBytesInGPU>this.numMBBeforeWarning*1024*1024){let r=(this.numBytesInGPU/1024/1024).toFixed(2);this.warnedAboutMemory=!0,console.warn(`High memory usage in GPU: ${r} MB, most likely due to a memory leak`)}return this.textureManager.acquireTexture(e,t,a)}computeBytes(e,t){return e[0]*e[1]*k.bytesPerElement(t)}},hp=xE;hp.nextDataId=0;function cfe(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 a=0;anew hp,2);var mfe={forceHalfFloat:bE},vE=` if (isnan(a)) return a; if (isnan(b)) return b; `,ku=class{constructor(e,t,n){this.variableNames=["A","B"],this.outputShape=M.assertAndGetBroadcastShape(t,n),this.userCode=` float binaryOperation(float a, float b) { ${e} } void main() { float a = getAAtOutCoords(); float b = getBAtOutCoords(); setOutput(binaryOperation(a, b)); } `}},U0=` 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; `,pp=class{constructor(e,t,n,a=!1){this.variableNames=["A","B"],this.supportsBroadcasting=!0,this.packedInputs=!0,this.packedOutput=!0,this.outputShape=M.assertAndGetBroadcastShape(t,n);let r=this.outputShape.length,s="";if(a)if(r===0||k.sizeFromShape(this.outputShape)===1)s=` result.y = 0.; result.z = 0.; result.w = 0.; `;else if(s=` ${kt(r)} coords = getOutputCoords(); `,r===1)s+=` result.y = (coords + 1) >= ${this.outputShape[0]} ? 0. : result.y; result.z = 0.; result.w = 0.; `;else{let i=Bn("coords",r);s+=` bool nextRowOutOfBounds = (${i[r-2]} + 1) >= ${this.outputShape[r-2]}; bool nextColOutOfBounds = (${i[r-1]} + 1) >= ${this.outputShape[r-1]}; result.y = nextColOutOfBounds ? 0. : result.y; result.z = nextRowOutOfBounds ? 0. : result.z; result.w = nextColOutOfBounds || nextRowOutOfBounds ? 0. : result.w; `}this.userCode=` vec4 binaryOperation(vec4 a, vec4 b) { ${e} } void main() { vec4 a = getAAtOutCoords(); vec4 b = getBAtOutCoords(); vec4 result = binaryOperation(a, b); ${s} setOutput(result); } `}};function fa(e){let{inputs:t,backend:n}=e,{x:a}=t;return n.incRef(a.dataId),{dataId:a.dataId,shape:a.shape,dtype:a.dtype}}var gfe={kernelName:pl,backendName:"webgl",kernelFunc:fa};function ei(e){let{inputs:t,backend:n}=e,{real:a,imag:r}=t,s=n.makeTensorInfo(a.shape,"complex64"),i=n.texData.get(s.dataId),o=fa({inputs:{x:a},backend:n}),l=fa({inputs:{x:r},backend:n});return i.complexTensorInfos={real:o,imag:l},s}var yfe={kernelName:I1,backendName:"webgl",kernelFunc:ei},wE="return (a < 0.) ? b * a : a;",kE=` vec4 aLessThanZero = vec4(lessThan(a, vec4(0.))); return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a); `;function Afe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{alpha:s}=a,i=n.makeTensorInfo([],"float32",k.createScalarValue(s,"float32")),o=se().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new pp(kE,r.shape,i.shape):new ku(wE,r.shape,i.shape),l=n.runWebGLProgram(o,[r,i],r.dtype);return n.disposeIntermediateTensorInfo(i),l}var xfe={kernelName:cl,backendName:"webgl",kernelFunc:Afe},IE="return (a < 0.) ? b * a : a;",SE=` vec4 aLessThanZero = vec4(lessThan(a, vec4(0.))); return (aLessThanZero * (b * a)) + ((vec4(1.0) - aLessThanZero) * a); `;function bfe(e){let{inputs:t,backend:n}=e,{x:a,alpha:r}=t,s=se().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new pp(SE,a.shape,r.shape):new ku(IE,a.shape,r.shape);return n.runWebGLProgram(s,[a,r],a.dtype)}var vfe={kernelName:Sl,backendName:"webgl",kernelFunc:bfe},NE="if (isnan(x)) return x;",wfe=` if (isnan(a)) return a; if (isnan(b)) return b; `,kfe=` 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:a}){return({inputs:r,backend:s})=>{let{x:i}=r,o=s,l=a||i.dtype;if(o.shouldExecuteOnCPU([i])&&n!=null){let h=o.texData.get(i.dataId),p=n(h.values,l);return o.makeTensorInfo(i.shape,l,p)}let u=se().getBool("WEBGL_PACK_UNARY_OPERATIONS")&&t!=null,d;return u?d=new wu(i.shape,t):d=new Qs(i.shape,e),o.runWebGLProgram(d,[i],l)}}function Tn({opSnippet:e,packedOpSnippet:t,checkOutOfBounds:n=!1,supportsComplex:a=!1,cpuKernelImpl:r,dtype:s}){return({inputs:i,backend:o})=>{let{a:l,b:u}=i,d=o;if(a&&l.dtype==="complex64"){let m=d.texData.get(l.dataId),f=d.texData.get(u.dataId),[g,y]=[[m.complexTensorInfos.real,f.complexTensorInfos.real],[m.complexTensorInfos.imag,f.complexTensorInfos.imag]].map(x=>{let[v,b]=x,w={dataId:v.dataId,dtype:v.dtype,shape:l.shape},I={dataId:b.dataId,dtype:b.dtype,shape:u.shape},T=new ku(e,l.shape,u.shape);return d.runWebGLProgram(T,[w,I],Ga(v.dtype,b.dtype))}),A=ei({inputs:{real:g,imag:y},backend:d});return d.disposeIntermediateTensorInfo(g),d.disposeIntermediateTensorInfo(y),A}let h=s||Ga(l.dtype,u.dtype);if((l.dtype==="string"||u.dtype==="string"||d.shouldExecuteOnCPU([l,u]))&&r!=null){let m=d.texData.get(l.dataId).values,f=d.texData.get(u.dataId).values,g=l.dtype==="string"?M.fromUint8ToStringArray(m):m,y=l.dtype==="string"?M.fromUint8ToStringArray(f):f,[A,x]=r(l.shape,u.shape,g,y,h),v=d.makeTensorInfo(x,h),b=d.texData.get(v.dataId);return b.values=A,v}let p=se().getBool("WEBGL_PACK_BINARY_OPERATIONS")&&t!=null,c;return p?c=new pp(t,l.shape,u.shape,n):c=new ku(e,l.shape,u.shape),d.runWebGLProgram(c,[l,u],h)}}function j0(e,t=!1){if(e==="linear")return t?efe:Xce;if(e==="relu")return t?nfe:Yce;if(e==="elu")return t?tfe:Zce;if(e==="relu6")return t?afe:Jce;if(e==="prelu")return t?SE:IE;if(e==="leakyrelu")return t?kE:wE;if(e==="sigmoid")return t?rfe:Qce;throw new Error(`Activation ${e} has not been implemented for the WebGL backend.`)}var TE=class{constructor(e,t,n,a=!1,r=!1,s=!1,i=null,o=!1,l=!1){this.variableNames=["matrixA","matrixB"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=n;let u=a?e[1]:e[2],d=Math.ceil(u/2),h=a?"i * 2, rc.y":"rc.y, i * 2",p=r?"rc.z, i * 2":"i * 2, rc.z",c=a?["a.xxyy","a.zzww"]:["a.xxzz","a.yyww"],m=r?["b.xzxz","b.ywyw"]:["b.xyxy","b.zwzw"],f="",g="";i&&(o?f=`vec4 activation(vec4 a) { vec4 b = getPreluActivationWeightsAtOutCoords(); ${i} }`:l?f=`vec4 activation(vec4 a) { vec4 b = getLeakyreluAlphaAtOutCoords(); ${i} }`:f=`vec4 activation(vec4 x) { ${i} }`,g="result = activation(result);");let y=s?"result += getBiasAtOutCoords();":"";s&&this.variableNames.push("bias"),o&&this.variableNames.push("preluActivationWeights"),l&&this.variableNames.push("leakyreluAlpha");let A="rc.x",x="rc.x";e[0]`The new shape (${l}) has ${u} elements and the old shape (${r.shape}) has ${o} elements. The new shape and old shape must have the same number of elements.`);let d=i.texData.get(r.dataId);return d.isPacked&&!up(r.shape,l)&&!(d.texture!==null&&up(d.shape,l))?Sfe(r,l,i):(i.incRef(r.dataId),{dataId:r.dataId,shape:l,dtype:r.dtype})}var Nfe={kernelName:Qd,backendName:"webgl",kernelFunc:be},$E=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:a,inSize:r,outSize:s}=e;this.outputShape=[a,s];let i=Math.floor(n/4)*4,o=n%4,l="sumValue += dot(values, ones);";if(t!=null){let d=1/t;l=`sumValue += dot(values * ${k.isInt(d)?d.toPrecision(2):d}, ones);`}let u="";r%n>0&&(u=` if (inIdx < 0 || inIdx >= ${r}) { return 0.0; } `),this.userCode=` const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); float getValue(int batch, int inIdx) { ${u} return getX(batch, inIdx); } void main() { ivec2 coords = getOutputCoords(); int batch = coords[0]; int outIdx = coords[1]; int inOffset = outIdx * ${n}; float sumValue = 0.0; for (int i = 0; i < ${i}; i += 4) { int inIdx = inOffset + i; vec4 values = vec4( getValue(batch, inIdx), getValue(batch, inIdx + 1), getValue(batch, inIdx + 2), getValue(batch, inIdx + 3) ); ${l} } int inIdx = inOffset + ${i}; if (${o===1}) { vec4 values = vec4(getValue(batch, inIdx), 0.0, 0.0, 0.0); ${l} } else if (${o===2}) { vec4 values = vec4( getValue(batch, inIdx), getValue(batch, inIdx + 1), 0.0, 0.0); ${l} } else if (${o===3}) { vec4 values = vec4( getValue(batch, inIdx), getValue(batch, inIdx + 1), getValue(batch, inIdx + 2), 0.0); ${l} } setOutput(sumValue); } `}},Tfe=class{constructor(e,t){this.variableNames=["x"];let{windowSize:n,batchSize:a,inSize:r,outSize:s}=e;this.outputShape=[a,s];let i="0.0",o="";t==="prod"?i="1.0":t==="min"?(i="1.0 / 1e-20",o="min"):t==="max"&&(i="-1.0 / 1e-20",o="max");let l=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="sum"?l="sumValue":t==="prod"?l="prodValue":t==="all"?l="allValue":t==="any"&&(l="anyValue");let u=Math.floor(n/4)*4,d=n%4,h=` if (${t==="sum"}) { sumValue += dot(values, ones); } else if (${t==="prod"}) { vec2 tmp = vec2(values[0], values[1]) * vec2(values[2], values[3]); prodValue *= tmp[0] * tmp[1]; } else { minMaxValue = ${o}(values, minMaxValue); if (${t==="min"} || ${t==="max"}) { minMaxValue = ${o}(values, minMaxValue); bvec4 isNaN = isnan(values); if (isNaN.r || isNaN.g || isNaN.b || isNaN.a) { minMaxValue = vec4(NAN); } } } `,p="vec4";t==="all"?(i="1.0",h=` bool reducedAllValue = all(values); float floatedReducedAllValue = float(reducedAllValue); allValue = float(allValue >= 1.0 && floatedReducedAllValue >= 1.0); `,p="bvec4"):t==="any"&&(i="0.0",h=` bool reducedAnyValue = any(values); float floatedReducedAnyValue = float(reducedAnyValue); anyValue = float(anyValue >= 1.0 || floatedReducedAnyValue >= 1.0); `,p="bvec4");let c="";r%n>0&&(c=` if (inIdx < 0 || inIdx >= ${r}) { return initializationValue; } `),this.userCode=` const float initializationValue = ${i}; const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); float getValue(int batch, int inIdx) { ${c} return getX(batch, inIdx); } void main() { ivec2 coords = getOutputCoords(); int batch = coords[0]; int outIdx = coords[1]; int inOffset = outIdx * ${n}; vec4 minMaxValue = vec4(${i}); float prodValue = 1.0; float sumValue = 0.0; float allValue = 1.0; float anyValue = 0.0; for (int i = 0; i < ${u}; i += 4) { int inIdx = inOffset + i; ${p} values = ${p}( getValue(batch, inIdx), getValue(batch, inIdx + 1), getValue(batch, inIdx + 2), getValue(batch, inIdx + 3) ); ${h} } int inIdx = inOffset + ${u}; if (${d===1}) { ${p} values = ${p}( getValue(batch, inIdx), initializationValue, initializationValue, initializationValue ); ${h} } else if (${d===2}) { ${p} values = ${p}( getValue(batch, inIdx), getValue(batch, inIdx + 1), initializationValue, initializationValue ); ${h} } else if (${d===3}) { ${p} values = ${p}( getValue(batch, inIdx), getValue(batch, inIdx + 1), getValue(batch, inIdx + 2), initializationValue ); ${h} } setOutput(${l}); } `}};function Efe(e){let t=[];for(;t.length===0||t[t.length-1].outSize!==1;){let n=t.length?t[t.length-1].outSize:e[1],a=M.computeOptimalWindowSize(n);t.push({inSize:n,windowSize:a,outSize:Math.ceil(n/a)})}return t}function bo(e,t,n,a){let r=Efe(e.shape),s=e;for(let i=0;i6)throw Error(`Transpose for rank ${t} is not yet supported`);let n=["resRC.x","resRC.y","resRC.z","resRC.w","resRC.u","resRC.v"],a=new Array(t);for(let r=0;r6)throw Error(`Packed transpose for rank ${this.rank} is not yet supported.`);let a=kt(this.rank),r=cE("rc",this.rank),s=new Array(this.rank);for(let u=0;u=2&&d>=2&&x,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${f}) and (${g}).`);let v=(y>A?e.shape.slice(0,-2):t.shape.slice(0,-2)).concat([c,m]);k.assert(h===p,()=>`Error in matMul: inner shapes (${h}) and (${p}) of Tensors with shapes ${e.shape} and ${t.shape} and transposeA=${n} and transposeB=${a} must match.`);let b=n?[y,h,c]:[y,c,h],w=a?[A,m,p]:[A,p,m],I=be({inputs:{x:e},backend:r,attrs:{shape:b}}),T=be({inputs:{x:t},backend:r,attrs:{shape:w}}),C=[I,T],z=Math.max(y,A),$=n?I.shape[1]:I.shape[2],S=s!=null,D=i!=null,_=l==="leakyrelu",W=l!=null?j0(l,!0):null,X=S||D||_||W!=null,q;if((c===1||m===1)&&$>RE&&X===!1){let ee=I,ie=T;n&&(ee=Vn({inputs:{x:I},backend:r,attrs:{perm:[0,2,1]}}),C.push(ee)),a&&(ie=Vn({inputs:{x:T},backend:r,attrs:{perm:[0,2,1]}}),C.push(ie));let ae=m!==1,de=m===1,te=ee;ae&&(te=be({inputs:{x:ee},backend:r,attrs:{shape:[z,$,1]}}),C.push(te));let ce=m===1?2:1,he=ie;de&&(he=be({inputs:{x:ie},backend:r,attrs:{shape:[z,1,$]}}),C.push(he));let ve=lb({inputs:{a:te,b:he},backend:r});q=G0({inputs:{x:ve},backend:r,attrs:{axis:ce,keepDims:!0}}),C.push(ve)}else{let ee=Ga(e.dtype,t.dtype),ie=new TE(b,w,[z,c,m],n,a,S,W,D,_),ae=[I,T];if(s!=null&&ae.push(s),D&&ae.push(i),_){let de=r.makeTensorInfo([],"float32",k.createScalarValue(o,"float32"));ae.push(de),C.push(de)}q=r.runWebGLProgram(ie,ae,ee)}let Q=be({inputs:{x:q},backend:r,attrs:{shape:v}});C.push(q);for(let ee of C)r.disposeIntermediateTensorInfo(ee);return Q}function Dfe(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s,bias:i,preluActivationWeights:o}=t,{transposeA:l,transposeB:u,activation:d,leakyreluAlpha:h}=a;return q0({a:r,b:s,transposeA:l,transposeB:u,backend:n,bias:i,preluActivationWeights:o,leakyreluAlpha:h,activation:d})}var _fe={kernelName:Ll,backendName:"webgl",kernelFunc:Dfe},FE="return abs(x);";function zfe(e){let{inputs:t,backend:n}=e,{x:a}=t;if(n.shouldExecuteOnCPU([a])&&a.dtype!=="complex64"){let s=n.texData.get(a.dataId),i=hE(s.values);return n.makeTensorInfo(a.shape,a.dtype,i)}let r;return se().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new wu(a.shape,FE):r=new Qs(a.shape,FE),n.runWebGLProgram(r,[a],a.dtype)}var Pfe={kernelName:xd,backendName:"webgl",kernelFunc:zfe},Lfe=gr+` if (abs(x) > 1.) { return NAN; } return acos(x); `,Wfe=ot({opSnippet:Lfe}),Bfe={kernelName:bd,backendName:"webgl",kernelFunc:Wfe},Vfe=gr+` if (x < 1.0) return NAN; return log(x + sqrt(x * x - 1.0));`,Ufe=ot({opSnippet:Vfe}),jfe={kernelName:vd,backendName:"webgl",kernelFunc:Ufe},OE="return a + b;",Hfe=Tn({opSnippet:OE,packedOpSnippet:OE,supportsComplex:!0,cpuKernelImpl:nce}),Gfe={kernelName:Os,backendName:"webgl",kernelFunc:Hfe},qfe=class{constructor(e,t){this.outputShape=[],this.outputShape=e,this.variableNames=t.map((r,s)=>`T${s}`);let n=[];this.variableNames.forEach(r=>{n.push(`float v${r} = get${r}AtOutCoords();`)});let a=this.variableNames.map(r=>`v${r}`).join(" + ");this.userCode=` void main() { ${n.join(` `)} float result = ${a}; setOutput(result); } `}},Kfe=class{constructor(e,t){this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.variableNames=t.map((r,s)=>`T${s}`);let n=[];this.variableNames.forEach(r=>{n.push(`vec4 v${r} = get${r}AtOutCoords();`)});let a=this.variableNames.map(r=>`v${r}`).join(" + ");this.userCode=` void main() { ${n.join(` `)} vec4 result = ${a}; setOutput(result); } `}};function K0(e){let{inputs:t,backend:n}=e,a=t;if(a.length===1)return fa({inputs:{x:a[0]},backend:n});if(a.length>se().get("WEBGL_MAX_TEXTURES_IN_SHADER")){let o=Math.floor(a.length/2),l=K0({inputs:a.slice(0,o),backend:n}),u=K0({inputs:a.slice(o),backend:n});return K0({inputs:[l,u],backend:n})}let r=a.map(o=>o.dtype).reduce((o,l)=>Ga(o,l)),s=a.map(o=>o.shape),i=se().getBool("WEBGL_PACK")?new Kfe(a[0].shape,s):new qfe(a[0].shape,s);return n.runWebGLProgram(i,a,r)}var Xfe={kernelName:Zo,backendName:"webgl",kernelFunc:K0};function Zfe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=r.shape.length,l=k.parseAxisParam(s,r.shape),u=l,d=M.getAxesPermutation(u,o),h=r;d!=null&&(h=Vn({inputs:{x:r},backend:n,attrs:{perm:d}}),u=M.getInnerMostAxes(u.length,o)),M.assertAxesAreInnerMostDims("all",u,o);let[p,c]=M.computeOutAndReduceShapes(h.shape,u),m=k.sizeFromShape(c),f=be({inputs:{x:h},backend:n,attrs:{shape:[-1,m]}}),g=bo(f,f.dtype,"all",n),y;if(i){let A=M.expandShapeToKeepDim(p,l);y=be({inputs:{x:g},backend:n,attrs:{shape:A}})}else y=be({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),d!=null&&n.disposeIntermediateTensorInfo(h),y}var Yfe={kernelName:wd,backendName:"webgl",kernelFunc:Zfe};function Jfe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=r.shape.length,l=k.parseAxisParam(s,r.shape),u=l,d=M.getAxesPermutation(u,o),h=r;d!=null&&(h=Vn({inputs:{x:r},backend:n,attrs:{perm:d}}),u=M.getInnerMostAxes(u.length,o)),M.assertAxesAreInnerMostDims("any",u,o);let[p,c]=M.computeOutAndReduceShapes(h.shape,u),m=k.sizeFromShape(c),f=be({inputs:{x:h},backend:n,attrs:{shape:[-1,m]}}),g=bo(f,f.dtype,"any",n),y;if(i){let A=M.expandShapeToKeepDim(p,l);y=be({inputs:{x:g},backend:n,attrs:{shape:A}})}else y=be({inputs:{x:g},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(f),n.disposeIntermediateTensorInfo(g),d!=null&&n.disposeIntermediateTensorInfo(h),y}var Qfe={kernelName:kd,backendName:"webgl",kernelFunc:Jfe},e0e=class{constructor(e,t,n){this.variableNames=["A"];let{windowSize:a,batchSize:r,outSize:s}=e;n||this.variableNames.push("bestIndicesA"),this.outputShape=[r,s];let i=t==="max"?">":"<",o=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 * ${a}; int bestIndex = inOffset; float bestValue = getA(batch, bestIndex); for (int i = 0; i < ${a}; i++) { int inIdx = ${o}; float candidate = getA(batch, inIdx); if (candidate ${i} bestValue) { bestValue = candidate; bestIndex = inIdx; } } setOutput(float(bestIndex)); } `}},t0e=class{constructor(e,t,n,a){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,k.assert(e.length>2,()=>`Packed arg${n.charAt(0).toUpperCase()+n.slice(1)} supports only inputs with rank above 2.`);let r=e[e.length-1],s=Math.ceil(r/t);this.outputShape=e.slice(0,-1),s>1&&this.outputShape.push(s),a||this.variableNames.push("bestIndicesA");let i=this.outputShape,o=i.length,l=kt(o),u=Bn("coords",o),d,h;if(s===1){h=o+1;let I=kt(h);d=` ${I} sourceLocR = ${I}(${u.join()}, 0); ++${u[o-1]}; ${I} sourceLocG = ${I}(${u.join()}, 0); ++${u[o-2]}; ${I} sourceLocA = ${I}(${u.join()}, 0); --${u[o-1]}; ${I} sourceLocB = ${I}(${u.join()}, 0); --${u[o-2]};`}else h=o,d=` ${l} sourceLocR = coords; ++${u[o-1]}; ${l} sourceLocG = coords; ++${u[o-2]}; ${l} sourceLocA = coords; --${u[o-1]}; ${l} sourceLocB = coords; --${u[o-2]};`;let p=["x","y","z","w","u","v"].slice(0,h),c="."+p[h-1],m=p.map(I=>"int "+I),f=Bn("sourceLocR",h-1).concat("inIdx.r"),g=Bn("sourceLocG",h-1).concat("inIdx.g"),y=Bn("sourceLocB",h-1).concat("inIdx.b"),A=Bn("sourceLocA",h-1).concat("inIdx.a"),x=n==="max"?"greaterThan":"lessThan",v=a?"":` inIdx = round(vec4(getBestIndicesAChannel(${f.join()}), getBestIndicesAChannel(${g.join()}), getBestIndicesAChannel(${y.join()}), getBestIndicesAChannel(${A.join()})));`,b=`vec4( getAChannel(${f.join()}), hasNextCol ? getAChannel(${g.join()}) : 0., hasNextRow ? getAChannel(${y.join()}) : 0., hasNextRow && hasNextCol ? getAChannel(${A.join()}) : 0.)`,w=a?"":` float getBestIndicesAChannel(${m.join()}) { return getChannel(getBestIndicesA(${p.join()}), vec2(${p.slice(-2).join()})); }`;this.userCode=` float getAChannel(${m.join()}) { return getChannel(getA(${p.join()}), vec2(${p.slice(-2).join()})); } ${w} void main() { ${l} coords = getOutputCoords(); bool hasNextCol = ${u[o-1]} < ${i[o-1]-1}; bool hasNextRow = ${u[o-2]} < ${i[o-2]-1}; ${d} ivec4 srcIdx = ivec4(sourceLocR${c}, sourceLocG${c}, sourceLocB${c}, sourceLocA${c}) * ${t}; ivec4 inIdx = srcIdx; vec4 bestIndex = vec4(inIdx); vec4 bestValue = ${b}; for (int i = 0; i < ${t}; i++) { inIdx = srcIdx; ${v} vec4 candidate = ${b}; bvec4 nan = isnan(candidate); bvec4 replace = bvec4( vec4(${x}(candidate, bestValue)) * (vec4(1.0) - vec4(nan))); bestValue = vec4(replace.x ? candidate.x : bestValue.x, replace.y ? candidate.y : bestValue.y, replace.z ? candidate.z : bestValue.z, replace.w ? candidate.w : bestValue.w); bestIndex = mix(bestIndex, vec4(inIdx), vec4(replace)); srcIdx++; } setOutput(bestIndex); } `}};function DE(e,t,n,a=null){let r=t.shape[0],s=t.shape[1];a!=null&&(r=a.shape[0],s=a.shape[1]);let i=M.computeOptimalWindowSize(s),o={windowSize:i,inSize:s,batchSize:r,outSize:Math.ceil(s/i)},l=new e0e(o,n,a==null),u=[t];a!=null&&u.push(a);let d=e.runWebGLProgram(l,u,"int32");if(d.shape[1]===1)return d;let h=DE(e,t,n,d);return e.disposeIntermediateTensorInfo(d),h}function _E(e,t,n,a=null){let r=a!=null?a.shape:t.shape,s=r[r.length-1],i=M.computeOptimalWindowSize(s),o=new t0e(r,i,n,a==null),l=a==null?[t]:[t,a],u=e.runWebGLProgram(o,l,"int32");if(u.shape.length===t.shape.length){let d=_E(e,t,n,u);return e.disposeIntermediateTensorInfo(u),d}return u}function zE(e,t,n,a){let r=[n];if(M.assertAxesAreInnerMostDims("arg"+a.charAt(0).toUpperCase()+a.slice(1),r,t.shape.length),!se().getBool("WEBGL_PACK_REDUCE")||t.shape.length<=2){let s=[],[i,o]=M.computeOutAndReduceShapes(t.shape,r),l=k.sizeFromShape(o),u=be({inputs:{x:t},backend:e,attrs:{shape:[-1,l]}});s.push(u);let d=DE(e,u,a);s.push(d);let h=be({inputs:{x:d},backend:e,attrs:{shape:i}});return s.forEach(p=>e.disposeIntermediateTensorInfo(p)),h}return _E(e,t,a)}function n0e(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a,i=k.parseAxisParam(s,r.shape),o=M.getAxesPermutation(i,r.shape.length),l=r,u=[];o!=null&&(l=Vn({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=M.getInnerMostAxes(i.length,l.shape.length)),M.assertAxesAreInnerMostDims("argMax",[i[0]],l.shape.length);let d=zE(n,l,i[0],"max");return u.forEach(h=>n.disposeIntermediateTensorInfo(h)),d}var a0e={kernelName:Yo,backendName:"webgl",kernelFunc:n0e};function r0e(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s}=a,i=k.parseAxisParam(s,r.shape),o=M.getAxesPermutation(i,r.shape.length),l=r,u=[];o!=null&&(l=Vn({inputs:{x:r},backend:n,attrs:{perm:o}}),u.push(l),i=M.getInnerMostAxes(i.length,l.shape.length)),M.assertAxesAreInnerMostDims("argMin",[i[0]],l.shape.length);let d=zE(n,l,i[0],"min");return u.forEach(h=>n.disposeIntermediateTensorInfo(h)),d}var s0e={kernelName:qc,backendName:"webgl",kernelFunc:r0e},i0e=gr+` if (abs(x) > 1.) { return NAN; } return asin(x); `,o0e=ot({opSnippet:i0e}),l0e={kernelName:Id,backendName:"webgl",kernelFunc:o0e},u0e=gr+"return log(x + sqrt(x * x + 1.0));",d0e=ot({opSnippet:u0e}),h0e={kernelName:Sd,backendName:"webgl",kernelFunc:d0e},p0e=gr+` return atan(x); `,c0e=ot({opSnippet:p0e}),f0e={kernelName:Nd,backendName:"webgl",kernelFunc:c0e},m0e=wfe+` return atan(a, b); `,g0e=` vec4 result = atan(a, b); vec4 isNaN = min(vec4(isnan(a)) + vec4(isnan(b)), vec4(1.0)); `+kfe+` return result; `,y0e=Tn({opSnippet:m0e,packedOpSnippet:g0e}),A0e={kernelName:Ed,backendName:"webgl",kernelFunc:y0e},x0e=gr+` if ((x < -1.0) || (x > 1.0)) return NAN; return (log(1.0 + x) - log(1.0 - x)) / 2.0;`,b0e=ot({opSnippet:x0e}),v0e={kernelName:Td,backendName:"webgl",kernelFunc:b0e},cp=class{constructor(e,t,n,a=!1,r=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let s=e.filterWidth,i=e.strideHeight,o=e.strideWidth,l=e.dilationHeight,u=e.dilationWidth,d=e.effectiveFilterHeight,h=e.effectiveFilterWidth,p=e.padInfo.top,c=e.padInfo.left;this.outputShape=e.outShape;let m=t==="avg",f=`((batch * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + d`,g=`(xR * ${e.inWidth} + xC) * ${e.inChannels} + d`,y="0.0";if(m||(y="-1.0 / 1e-20"),n){let I=">=";this.userCode=` const ivec2 strides = ivec2(${i}, ${o}); const ivec2 pads = ivec2(${p}, ${c}); void main() { ivec4 coords = getOutputCoords(); int batch = coords[0]; int d = coords[3]; ivec2 xRCCorner = coords.yz * strides - pads; int xRCorner = xRCCorner.x; int xCCorner = xRCCorner.y; // max/min x(?, ?, d) to get y(yR, yC, d). // ? = to be determined float minMaxValue = 0.0; float minMaxValueFound = 0.0; int minMaxPosition = 0; float avgValue = 0.0; for (int wR = 0; wR < ${d}; wR += ${l}) { int xR = xRCorner + wR; if (xR < 0 || xR >= ${e.inHeight}) { continue; } for (int wC = 0; wC < ${h}; wC += ${u}) { int xC = xCCorner + wC; if (xC < 0 || xC >= ${e.inWidth}) { continue; } float value = getX(batch, xR, xC, d); // If a min / max value has already been found, use it. If not, // use the current value. float currMinMaxValue = mix( value, minMaxValue, minMaxValueFound); if (value ${I} currMinMaxValue) { minMaxValue = value; minMaxValueFound = 1.0; minMaxPosition = ${a?r?f:g:`wR * ${h} + wC`}; } } } setOutput(float(minMaxPosition)); } `;return}let A="max",x=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(x="avgValue / count");let v=Math.floor(s/4)*4,b=s%4,w=` if (${m}) { avgValue += dot(values, ones); } else { minMaxValue = ${A}(values, minMaxValue); } `;this.userCode=` const ivec2 strides = ivec2(${i}, ${o}); const ivec2 pads = ivec2(${p}, ${c}); const float initializationValue = ${y}; const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); float count = 0.0; float getValue(int batch, int xR, int xC, int d) { if (xC < 0 || xC >= ${e.inWidth}) { return initializationValue; } count += 1.0; return getX(batch, xR, xC, d); } void main() { ivec4 coords = getOutputCoords(); int batch = coords[0]; int d = coords[3]; ivec2 xRCCorner = coords.yz * strides - pads; int xRCorner = xRCCorner.x; int xCCorner = xRCCorner.y; // max/min x(?, ?, d) to get y(yR, yC, d). // ? = to be determined vec4 minMaxValue = vec4(${y}); float avgValue = 0.0; count = 0.0; for (int wR = 0; wR < ${d}; wR += ${l}) { int xR = xRCorner + wR; if (xR < 0 || xR >= ${e.inHeight}) { continue; } for (int wC = 0; wC < ${v}; 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) ); ${w} } int xC = xCCorner + ${v}; if (${b===1}) { vec4 values = vec4( getValue(batch, xR, xC, d), initializationValue, initializationValue, initializationValue ); ${w} } else if (${b===2}) { vec4 values = vec4( getValue(batch, xR, xC, d), getValue(batch, xR, xC + ${u}, d), initializationValue, initializationValue ); ${w} } else if (${b===3}) { vec4 values = vec4( getValue(batch, xR, xC, d), getValue(batch, xR, xC + ${u}, d), getValue(batch, xR, xC + 2 * ${u}, d), initializationValue ); ${w} } } setOutput(${x}); } `}},ub=class{constructor(e,t,n,a=!1,r=!1){if(this.variableNames=["x"],t==="avg"&&n)throw new Error("Cannot compute positions for average pool.");let s=e.filterWidth,i=e.strideDepth,o=e.strideHeight,l=e.strideWidth,u=e.dilationDepth,d=e.dilationHeight,h=e.dilationWidth,p=e.effectiveFilterDepth,c=e.effectiveFilterHeight,m=e.effectiveFilterWidth,f=e.padInfo.front,g=e.padInfo.top,y=e.padInfo.left;this.outputShape=e.outShape;let A=t==="avg",x="0.0";if(A||(x="-1.0 / 1e-20"),n){let C=">=";this.userCode=` const ivec3 strides = ivec3(${i}, ${o}, ${l}); const ivec3 pads = ivec3(${f}, ${g}, ${y}); void main() { ivec5 coords = getOutputCoords(); int batch = coords.x; int ch = coords.u; ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads; int xDCorner = xCorner.x; int xRCorner = xCorner.y; int xCCorner = xCorner.z; // max/min x(?, ?, ?, ch) to get y(yD, yR, yC, ch). // ? = to be determined float minMaxValue = 0.0; float minMaxValueFound = 0.0; int minMaxPosition = 0; for (int wD = 0; wD < ${p}; wD += ${u}) { int xD = xDCorner + wD; if (xD < 0 || xD >= ${e.inDepth}) { continue; } for (int wR = 0; wR < ${c}; wR += ${d}) { int xR = xRCorner + wR; if (xR < 0 || xR >= ${e.inHeight}) { continue; } for (int wC = 0; wC < ${m}; wC += ${h}) { int xC = xCCorner + wC; if (xC < 0 || xC >= ${e.inWidth}) { continue; } float value = getX(batch, xD, xR, xC, ch); // If a min / max value has already been found, use it. If not, // use the current value. float currMinMaxValue = mix( value, minMaxValue, minMaxValueFound); if (value ${C} currMinMaxValue) { minMaxValue = value; minMaxValueFound = 1.0; minMaxPosition = ${a?r?`(((batch * ${e.inDepth} + xD) * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`((xD * ${e.inHeight} + xR) * ${e.inWidth} + xC) * ${e.inChannels} + ch`:`wD * ${c} * ${m} + wR * ${m} + wC`}; } } } } setOutput(float(minMaxPosition)); } `;return}let v="max",b=`${t}(${t}(${t}(minMaxValue[0], minMaxValue[1]), minMaxValue[2]), minMaxValue[3])`;t==="avg"&&(b="avgValue / count");let w=Math.floor(s/4)*4,I=s%4,T=` if (${A}) { avgValue += dot(values, ones); } else { minMaxValue = ${v}(values, minMaxValue); } `;this.userCode=` const ivec3 strides = ivec3(${i}, ${o}, ${l}); const ivec3 pads = ivec3(${f}, ${g}, ${y}); const float initializationValue = ${x}; const vec4 ones = vec4(1.0, 1.0, 1.0, 1.0); float count = 0.0; float getValue(int batch, int xD, int xR, int xC, int ch) { if (xC < 0 || xC >= ${e.inWidth}) { return initializationValue; } count += 1.0; return getX(batch, xD, xR, xC, ch); } void main() { ivec5 coords = getOutputCoords(); int batch = coords.x; int ch = coords.u; ivec3 xCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads; int xDCorner = xCorner.x; int xRCorner = xCorner.y; int xCCorner = xCorner.z; // max/min x(?, ?, ?, d) to get y(yD, yR, yC, ch). // ? = to be determined vec4 minMaxValue = vec4(${x}); float avgValue = 0.0; count = 0.0; for (int wD = 0; wD < ${p}; wD += ${u}) { int xD = xDCorner + wD; if (xD < 0 || xD >= ${e.inDepth}) { continue; } for (int wR = 0; wR < ${c}; wR += ${d}) { int xR = xRCorner + wR; if (xR < 0 || xR >= ${e.inHeight}) { continue; } for (int wC = 0; wC < ${w}; wC += 4) { int xC = xCCorner + wC * ${h}; vec4 values = vec4( getValue(batch, xD, xR, xC, ch), getValue(batch, xD, xR, xC + ${h}, ch), getValue(batch, xD, xR, xC + 2 * ${h}, ch), getValue(batch, xD, xR, xC + 3 * ${h}, ch) ); ${T} } int xC = xCCorner + ${w}; if (${I===1}) { vec4 values = vec4( getValue(batch, xD, xR, xC, ch), initializationValue, initializationValue, initializationValue ); ${T} } else if (${I===2}) { vec4 values = vec4( getValue(batch, xD, xR, xC, ch), getValue(batch, xD, xR, xC + ${h}, ch), initializationValue, initializationValue ); ${T} } else if (${I===3}) { vec4 values = vec4( getValue(batch, xD, xR, xC, ch), getValue(batch, xD, xR, xC + ${h}, ch), getValue(batch, xD, xR, xC + 2 * ${h}, ch), initializationValue ); ${T} } } setOutput(${b}); } } `}};function w0e(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t;mu(r,"avgPool");let{filterSize:s,strides:i,pad:o,dimRoundingMode:l}=a,u=1;k.assert(M.eitherStridesOrDilationsAreOne(i,u),()=>`Error in avgPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let d=M.computePool2DInfo(r.shape,s,i,u,o,l);if(d.filterWidth===1&&d.filterHeight===1&&k.arraysEqual(d.inShape,d.outShape))return fa({inputs:{x:r},backend:n});let h=new cp(d,"avg",!1);return n.runWebGLProgram(h,[r],"float32")}var k0e={kernelName:Jo,backendName:"webgl",kernelFunc:w0e};function I0e(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dimRoundingMode:l,dataFormat:u}=a,d=[1,1,1],h=M.computePool3DInfo(r.shape,s,i,d,o,l,u),p=new ub(h,"avg",!1);return n.runWebGLProgram(p,[r],"float32")}var S0e={kernelName:Kc,backendName:"webgl",kernelFunc:I0e},N0e=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,a=e.strideHeight,r=e.strideWidth,s=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterHeight,l=e.effectiveFilterWidth,u=o-1-e.padInfo.top,d=l-1-e.padInfo.left,h=1/(t*n);this.userCode=` const ivec2 pads = ivec2(${u}, ${d}); const float avgMultiplier = float(${h}); void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; int d = coords[3]; ivec2 dyRCCorner = coords.yz - pads; int dyRCorner = dyRCCorner.x; int dyCCorner = dyRCCorner.y; // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d). // ? = to be determined. : = across all values in that axis. float dotProd = 0.0; for (int wR = 0; wR < ${o}; wR += ${s}) { float dyR = float(dyRCorner + wR) / ${a}.0; if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); for (int wC = 0; wC < ${l}; wC+= ${i}) { float dyC = float(dyCCorner + wC) / ${r}.0; if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); float dyValue = getDy(b, idyR, idyC, d); dotProd += dyValue * avgMultiplier; } } setOutput(dotProd); } `}},T0e=class{constructor(e){this.variableNames=["dy"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,a=e.filterWidth,r=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,u=e.dilationWidth,d=e.effectiveFilterDepth,h=e.effectiveFilterHeight,p=e.effectiveFilterWidth,c=d-1-e.padInfo.front,m=h-1-e.padInfo.top,f=p-1-e.padInfo.left,g=1/(t*n*a);this.userCode=` const ivec3 pads = ivec3(${c}, ${m}, ${f}); const float avgMultiplier = float(${g}); void main() { ivec5 coords = getOutputCoords(); int batch = coords.x; int ch = coords.u; ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads; int dyDCorner = dyCorner.x; int dyRCorner = dyCorner.y; int dyCCorner = dyCorner.z; // Convolve dy(?, ?, ?, d) with pos mask(:, :, :, ch) to get // dx(xD, xR, xC, ch). // ? = to be determined. : = across all values in that axis. float dotProd = 0.0; for (int wD = 0; wD < ${d}; wD += ${o}) { float dyD = float(dyDCorner + wD) / ${r}.0; if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) { continue; } int idyD = int(dyD); for (int wR = 0; wR < ${h}; wR += ${l}) { float dyR = float(dyRCorner + wR) / ${s}.0; if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); for (int wC = 0; wC < ${p}; wC += ${u}) { float dyC = float(dyCCorner + wC) / ${i}.0; if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); float dyValue = getDy(batch, idyD, idyR, idyC, ch); dotProd += dyValue * avgMultiplier; } } } setOutput(dotProd); } `}};function E0e(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s,{filterSize:o,strides:l,pad:u,dimRoundingMode:d}=a,h=[1,1,1],p=M.computePool3DInfo(i.shape,o,l,h,u,d),c=new T0e(p);return n.runWebGLProgram(c,[r],i.dtype)}var C0e={kernelName:w1,backendName:"webgl",kernelFunc:E0e};function M0e(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s;mu([r,s],"avgPoolGrad");let{filterSize:o,strides:l,pad:u}=a,d=M.computePool2DInfo(i.shape,o,l,1,u),h=new N0e(d);return n.runWebGLProgram(h,[r],i.dtype)}var $0e={kernelName:v1,backendName:"webgl",kernelFunc:M0e};function R0e(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s}=t,{transposeA:i,transposeB:o}=a;return q0({a:r,b:s,transposeA:i,transposeB:o,backend:n})}var F0e={kernelName:Qo,backendName:"webgl",kernelFunc:R0e},O0e=class{constructor(e,t,n,a,r,s){this.outputShape=[],this.variableNames=["x","mean","variance"],M.assertAndGetBroadcastShape(e,t),M.assertAndGetBroadcastShape(e,n);let i="0.0";a!=null&&(M.assertAndGetBroadcastShape(e,a),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="1.0";r!=null&&(M.assertAndGetBroadcastShape(e,r),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=` void main() { float x = getXAtOutCoords(); float mean = getMeanAtOutCoords(); float variance = getVarianceAtOutCoords(); float offset = ${i}; float scale = ${o}; float inv = scale * inversesqrt(variance + float(${s})); setOutput(dot(vec3(x, -mean, offset), vec3(inv, inv, 1))); } `}},D0e=class{constructor(e,t,n,a,r,s){this.packedInputs=!0,this.packedOutput=!0,this.variableNames=["x","mean","variance"],M.assertAndGetBroadcastShape(e,t),M.assertAndGetBroadcastShape(e,n);let i="vec4(0.0)";a!=null&&(M.assertAndGetBroadcastShape(e,a),this.variableNames.push("offset"),i="getOffsetAtOutCoords()");let o="vec4(1.0)";r!=null&&(M.assertAndGetBroadcastShape(e,r),this.variableNames.push("scale"),o="getScaleAtOutCoords()"),this.outputShape=e,this.userCode=` void main() { vec4 offset = ${i}; vec4 scale = ${o}; vec4 x = getXAtOutCoords(); vec4 mean = getMeanAtOutCoords(); vec4 variance = getVarianceAtOutCoords(); vec4 inv = scale * inversesqrt(variance + vec4(${s})); setOutput((x - mean) * inv + offset); } `}},_0e=({inputs:e,backend:t,attrs:n})=>{let{x:a,mean:r,variance:s,offset:i,scale:o}=e;k.assert(r.shape.length===s.shape.length,()=>"Batch normalization gradient requires mean and variance to have equal ranks."),k.assert(i==null||r.shape.length===i.shape.length,()=>"Batch normalization gradient requires mean and offset to have equal ranks."),k.assert(o==null||r.shape.length===o.shape.length,()=>"Batch normalization gradient requires mean and scale to have equal ranks.");let{varianceEpsilon:l}=n;l==null&&(l=.001);let u=[a,r,s],d=null;i!=null&&(d=i.shape,u.push(i));let h=null;o!=null&&(h=o.shape,u.push(o));let p=se().getBool("WEBGL_PACK_NORMALIZATION")?new D0e(a.shape,r.shape,s.shape,d,h,l):new O0e(a.shape,r.shape,s.shape,d,h,l);return t.runWebGLProgram(p,u,u[0].dtype)},z0e={kernelName:dl,backendName:"webgl",kernelFunc:_0e},P0e=class{constructor(e){this.variableNames=["source"],this.outputShape=e,this.rank=e.length;let t=kt(this.rank),n=`uniform int start[${this.rank}];`,a=L0e(this.rank),r,s=e.map((i,o)=>`sourceLoc.${db[o]} = start[${o}] + coords.${db[o]};`);r=` ${t} sourceLoc; ${t} coords = getOutputCoords(); ${s.join(` `)} `,this.userCode=` ${n} void main() { ${r} setOutput(getSource(${a})); } `}getCustomSetupFunc(e){if(e.length!==this.rank)throw Error(`The rank (${this.rank}) of the program must match the length of start (${e.length})`);return(t,n)=>{this.startLoc==null&&(this.startLoc=t.getUniformLocationNoThrow(n,"start"),this.startLoc==null)||t.gl.uniform1iv(this.startLoc,e)}}},db=["x","y","z","w","u","v"];function L0e(e){if(e===1)return"sourceLoc";if(e<=6)return db.slice(0,e).map(t=>"sourceLoc."+t).join(",");throw Error(`Slicing for rank ${e} is not yet supported`)}var W0e=class{constructor(e){this.variableNames=["source"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.rank=e.length;let t=kt(this.rank),n=Bn("coords",this.rank),a=Bn("sourceLoc",this.rank),r=this.rank===1?"sourceLoc":`vec2(${a.slice(-2).join()})`,s=`getChannel(getSource(${a.join()}), ${r})`,i=` result.x = ${s}; if (++${n[this.rank-1]} < ${e[this.rank-1]}) { ++${a[this.rank-1]}; result.y = ${s}; --${a[this.rank-1]}; } `,o=this.rank===1?"":` --${n[this.rank-1]}; if (++${n[this.rank-2]} < ${e[this.rank-2]}) { ++${a[this.rank-2]}; result.z = ${s}; if (++${n[this.rank-1]} < ${e[this.rank-1]}) { ++${a[this.rank-1]}; result.w = ${s}; } } `,l=this.rank<=4?`sourceLoc = coords + ${t}(${e.map((u,d)=>`start[${d}]`).join()});`:e.map((u,d)=>`${a[d]} = ${n[d]} + start[${d}];`).join(` `);this.userCode=` uniform int start[${this.rank}]; void main() { ${t} coords = getOutputCoords(); ${t} sourceLoc; ${l} vec4 result = vec4(0.); ${i} ${o} setOutput(result); } `}getCustomSetupFunc(e){if(e.length!==this.rank)throw Error(`The rank (${this.rank}) of the program must match the length of start (${e.length})`);return(t,n)=>{this.startLoc==null&&(this.startLoc=t.getUniformLocationNoThrow(n,"start"),this.startLoc==null)||t.gl.uniform1iv(this.startLoc,e)}}};function B0e(e,t,n,a){let r=a.texData.get(e.dataId),s=a.makeTensorInfo(n,e.dtype),i=a.texData.get(s.dataId);Object.assign(i,r),i.refCount=1,i.shape=n,i.dtype=e.dtype;let o=Cn.computeFlatOffset(t,k.computeStrides(e.shape));r.slice&&(o+=r.slice.flatOffset),i.slice={flatOffset:o,origDataId:r.slice&&r.slice.origDataId||e.dataId};let l=a.dataRefCount.get(i.slice.origDataId)||1;return a.dataRefCount.set(i.slice.origDataId,l+1),s}function fp(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{begin:s,size:i}=a,[o,l]=Cn.parseSliceParams(r,s,i);if(Cn.assertParamsValid(r,o,l),k.sizeFromShape(l)===0)return n.makeTensorInfo(l,r.dtype,[]);if(n.shouldExecuteOnCPU([r])||r.dtype==="string"){let h=n.texData.get(r.dataId),p=Tce(h.values,o,l,r.shape,r.dtype);return n.makeTensorInfo(l,r.dtype,p)}let{isPacked:u}=n.texData.get(r.dataId),d=Cn.isSliceContinous(r.shape,o,l);if(u||!d){let h=se().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new W0e(l):new P0e(l),p=h.getCustomSetupFunc(o);return n.runWebGLProgram(h,[r],r.dtype,p)}return n.uploadToGPU(r.dataId),B0e(r,o,l,n)}var V0e={kernelName:ah,backendName:"webgl",kernelFunc:fp},U0e=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,crops:i}=a;k.assert(r.shape.length<=4,()=>"batchToSpaceND for rank > 4 with a WebGL backend not implemented yet");let o=s.reduce((A,x)=>A*x),l=M.getReshaped(r.shape,s,o),u=M.getPermuted(l.length,s.length),d=M.getReshapedPermuted(r.shape,s,o),h=M.getSliceBeginCoords(i,s.length),p=M.getSliceSize(d,i,s.length),c=[],m=be({inputs:{x:r},backend:n,attrs:{shape:l}}),f=Vn({inputs:{x:m},backend:n,attrs:{perm:u}}),g=be({inputs:{x:f},backend:n,attrs:{shape:d}}),y=fp({inputs:{x:g},backend:n,attrs:{begin:h,size:p}});return c.push(m),c.push(f),c.push(g),c.forEach(A=>n.disposeIntermediateTensorInfo(A)),y},j0e={kernelName:Xc,backendName:"webgl",kernelFunc:U0e};function H0e(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,weights:s}=t,{size:i}=a,o=n.readSync(r.dataId),l=n.readSync(s.dataId),u=dE(o,l,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,u)}var G0e={kernelName:k1,backendName:"webgl",kernelFunc:H0e},q0e="return float(a != b);",PE=Tn({opSnippet:q0e,cpuKernelImpl:kce,dtype:"bool"}),K0e={kernelName:vl,backendName:"webgl",kernelFunc:PE};function mp(e){let{inputs:t,backend:n}=e,{input:a}=t,r=n.texData.get(a.dataId);return fa({inputs:{x:r.complexTensorInfos.real},backend:n})}var X0e={kernelName:H1,backendName:"webgl",kernelFunc:mp},Z0e="return float(int(x));";function Y0e(e,t){let n=new Qs(e.shape,Z0e),a=t.runWebGLProgram(n,[e],"int32");return{dataId:a.dataId,shape:a.shape,dtype:a.dtype}}function hb(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dtype:s}=a;if(s==="complex64"){if(r.dtype==="complex64")return fa({inputs:{x:r},backend:n});let i=un(r.shape),o=hb({inputs:{x:r},backend:n,attrs:{dtype:"float32"}}),l=ei({inputs:{real:o,imag:i},backend:n});return i.dispose(),n.disposeIntermediateTensorInfo(o),l}if(r.dtype==="complex64"){let i=mp({inputs:{input:r},backend:n}),o=hb({inputs:{x:i},backend:n,attrs:{dtype:s}});return n.disposeIntermediateTensorInfo(i),o}if(!k.hasEncodingLoss(r.dtype,s)){let i=fa({inputs:{x:r},backend:n});return{dataId:i.dataId,shape:i.shape,dtype:s}}if(s==="int32")return Y0e(r,n);if(s==="bool"){let i=n.makeTensorInfo([],"bool",k.getTypedArrayFromDType("bool",1)),o=PE({inputs:{a:r,b:i},backend:n});return n.disposeIntermediateTensorInfo(i),o}throw new Error(`Error in Cast: failed to cast ${r.dtype} to ${s}`)}var J0e={kernelName:el,backendName:"webgl",kernelFunc:hb},LE="return ceil(x);",Q0e=ot({opSnippet:LE,packedOpSnippet:LE,cpuKernelImpl:rce}),eme={kernelName:Ni,backendName:"webgl",kernelFunc:Q0e},tme=class{constructor(e){this.variableNames=["A"],this.outputShape=e,this.userCode=` uniform float minVal; uniform float maxVal; void main() { float value = getAAtOutCoords(); if (isnan(value)) { setOutput(value); return; } setOutput(clamp(value, minVal, maxVal)); } `}getCustomSetupFunc(e,t){return(n,a)=>{this.minLoc==null&&(this.minLoc=n.getUniformLocationNoThrow(a,"minVal"),this.maxLoc=n.getUniformLocationNoThrow(a,"maxVal")),n.gl.uniform1f(this.minLoc,e),n.gl.uniform1f(this.maxLoc,t)}}},nme=class{constructor(e){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e,this.userCode=` uniform float minVal; uniform float maxVal; void main() { vec4 value = getAAtOutCoords(); if (any(isnan(value))) { setOutput(value); return; } setOutput(clamp(value, vec4(minVal), vec4(maxVal))); } `}getCustomSetupFunc(e,t){return(n,a)=>{this.minLoc==null&&(this.minLoc=n.getUniformLocationNoThrow(a,"minVal"),this.maxLoc=n.getUniformLocationNoThrow(a,"maxVal")),n.gl.uniform1f(this.minLoc,e),n.gl.uniform1f(this.maxLoc,t)}}};function ame(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{clipValueMin:s,clipValueMax:i}=a,o;se().getBool("WEBGL_PACK_CLIP")?o=new nme(r.shape):o=new tme(r.shape);let l=o.getCustomSetupFunc(s,i);return n.runWebGLProgram(o,[r],r.dtype,l)}var rme={kernelName:Ti,backendName:"webgl",kernelFunc:ame},sme=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 WE(e,t){return{dataId:t.dataId,dtype:t.dtype,shape:e.shape}}function ime(e){let{inputs:t,backend:n}=e,{x:a}=t,r=n.texData.get(a.dataId),s=new sme(a.shape),i=[WE(a,r.complexTensorInfos.real),WE(a,r.complexTensorInfos.imag)];return n.runWebGLProgram(s,i,i[0].dtype)}var ome={kernelName:Zc,backendName:"webgl",kernelFunc:ime},lme=class{constructor(e){this.outputShape=[],this.outputShape=M.computeOutShape(e,1),this.variableNames=e.map((s,i)=>`T${i}`);let t=new Array(e.length-1);t[0]=e[0][1];for(let s=1;s`T${f}`);let o=new Array(e.length-1);o[0]=e[0][t];for(let m=1;m= ${o[m-1]}) { return getChannel( getT${m}(${X0(i,l,f)}), vec2(${X0(u,l,f)})); }`}let p=o.length,c=o[o.length-1];h+=` return getChannel( getT${p}(${X0(i,l,c)}), vec2(${X0(u,l,c)}));`,this.userCode=` float getValue(${i.map(m=>"int "+m)}) { ${h} } void main() { ${r} coords = getOutputCoords(); vec4 result = vec4(getValue(${s}), 0., 0., 0.); ${s[a-1]} = ${s[a-1]} + 1; if (${s[a-1]} < ${n[a-1]}) { result.g = getValue(${s}); } ${s[a-2]} = ${s[a-2]} + 1; if (${s[a-2]} < ${n[a-2]}) { result.a = getValue(${s}); } ${s[a-1]} = ${s[a-1]} - 1; if (${s[a-2]} < ${n[a-2]} && ${s[a-1]} < ${n[a-1]}) { result.b = getValue(${s}); } setOutput(result); } `}};function X0(e,t,n){let a=e.indexOf(t);return e.map((r,s)=>s===a?`${r} - ${n}`:r).join()}function Z0(e){let{inputs:t,backend:n}=e,{input:a}=t,r=n.texData.get(a.dataId);return fa({inputs:{x:r.complexTensorInfos.imag},backend:n})}var dme={kernelName:P1,backendName:"webgl",kernelFunc:Z0};function Iu(e,t,n){let a=e[0].dtype;if(a==="complex64"){let d=e.map(f=>mp({inputs:{input:f},backend:n})),h=e.map(f=>Z0({inputs:{input:f},backend:n})),p=Iu(d,t,n),c=Iu(h,t,n),m=ei({inputs:{real:p,imag:c},backend:n});return d.forEach(f=>n.disposeIntermediateTensorInfo(f)),h.forEach(f=>n.disposeIntermediateTensorInfo(f)),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(c),m}let r=n.shouldExecuteOnCPU(e);if(a==="string"&&(r=!0),r){let d=e.map(y=>{let A=k.sizeFromShape(y.shape.slice(t));return be({inputs:{x:y},backend:n,attrs:{shape:[-1,A]}})}),h=d.map(y=>({vals:n.readSync(y.dataId),shape:y.shape})),p=M.computeOutShape(d.map(y=>y.shape),1),c=d[0].shape[0]===1,m=sce(h,p,a,c),f=M.computeOutShape(e.map(y=>y.shape),t),g=n.makeTensorInfo(f,a,m);return d.forEach(y=>n.disposeIntermediateTensorInfo(y)),g}if(e.length>se().getNumber("WEBGL_MAX_TEXTURES_IN_SHADER")){let d=Math.floor(e.length/2),h=Iu(e.slice(0,d),t,n),p=Iu(e.slice(d),t,n),c=Iu([h,p],t,n);return n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(p),c}if(se().getBool("WEBGL_PACK_ARRAY_OPERATIONS")&&e[0].shape.length>1){let d=new ume(e.map(h=>h.shape),t);return n.runWebGLProgram(d,e,a)}let{tensors2D:s,outShape:i}=hme(e,t,n),o=new lme(s.map(d=>d.shape)),l=n.runWebGLProgram(o,s,a);s.forEach(d=>n.disposeIntermediateTensorInfo(d));let u=be({inputs:{x:l},attrs:{shape:i},backend:n});return n.disposeIntermediateTensorInfo(l),u}function hme(e,t,n){let a=M.computeOutShape(e.map(r=>r.shape),t);return{tensors2D:e.map(r=>be({inputs:{x:r},attrs:{shape:[-1,k.sizeFromShape(r.shape.slice(t))]},backend:n})),outShape:a}}function BE(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a,s=k.parseAxisParam(r,t[0].shape)[0],i=M.computeOutShape(t.map(u=>u.shape),s);if(k.sizeFromShape(i)===0)return n.makeTensorInfo(i,t[0].dtype,[]);let o=t.filter(u=>k.sizeFromShape(u.shape)>0);if(o.length===1)return fa({inputs:{x:o[0]},backend:n});let l=o.map(u=>u.shape);return M.assertParamsConsistent(l,s),Iu(o,s,n)}var pme={kernelName:Cd,backendName:"webgl",kernelFunc:BE},VE=class{constructor(e,t=!1,n=null,a=!1,r=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let s=e.padInfo.top,i=e.padInfo.left,o=e.strideHeight,l=e.strideWidth,u=e.dilationHeight,d=e.dilationWidth,h=e.filterHeight,p=e.filterWidth,c=Math.floor(e.inChannels/4)*4,m=e.inChannels%4,f=e.dataFormat==="channelsLast",g=f?1:2,y=f?2:3,A=f?3:1,x="",v="";n&&(a?x=`float activation(float a) { float b = getPreluActivationWeightsAtOutCoords(); ${n} }`:r?x=`float activation(float a) { float b = getLeakyreluAlphaAtOutCoords(); ${n} }`:x=` float activation(float x) { ${n} } `,v="result = activation(result);");let b=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=` ${x} const ivec2 strides = ivec2(${o}, ${l}); const ivec2 pads = ivec2(${s}, ${i}); void main() { ivec4 coords = getOutputCoords(); int batch = coords[0]; int d2 = coords[${A}]; ivec2 xRCCorner = ivec2(coords[${g}], coords[${y}]) * strides - pads; int xRCorner = xRCCorner.x; int xCCorner = xRCCorner.y; // Convolve x(?, ?, d1) with w(:, :, d1, d2) to get y(yR, yC, d2). // ? = to be determined. : = across all values in that axis. float dotProd = 0.0; for (int wR = 0; wR < ${h}; wR++) { int xR = xRCorner + wR * ${u}; if (xR < 0 || xR >= ${e.inHeight}) { continue; } for (int wC = 0; wC < ${p}; wC++) { int xC = xCCorner + wC * ${d}; if (xC < 0 || xC >= ${e.inWidth}) { continue; } for (int d1 = 0; d1 < ${c}; d1 += 4) { vec4 wValues = vec4( getW(wR, wC, d1, d2), getW(wR, wC, d1 + 1, d2), getW(wR, wC, d1 + 2, d2), getW(wR, wC, d1 + 3, d2) ); if (${f}) { vec4 xValues = vec4( getX(batch, xR, xC, d1), getX(batch, xR, xC, d1 + 1), getX(batch, xR, xC, d1 + 2), getX(batch, xR, xC, d1 + 3) ); dotProd += dot(xValues, wValues); } else { vec4 xValues = vec4( getX(batch, d1, xR, xC), getX(batch, d1 + 1, xR, xC), getX(batch, d1 + 2, xR, xC), getX(batch, d1 + 3, xR, xC) ); dotProd += dot(xValues, wValues); } } if (${m===1}) { if (${f}) { dotProd += getX(batch, xR, xC, ${c}) * getW(wR, wC, ${c}, d2); } else { dotProd += getX(batch, ${c}, xR, xC) * getW(wR, wC, ${c}, d2); } } else if (${m===2}) { vec2 wValues = vec2( getW(wR, wC, ${c}, d2), getW(wR, wC, ${c} + 1, d2) ); if (${f}) { vec2 xValues = vec2( getX(batch, xR, xC, ${c}), getX(batch, xR, xC, ${c} + 1) ); dotProd += dot(xValues, wValues); } else { vec2 xValues = vec2( getX(batch, ${c}, xR, xC), getX(batch, ${c} + 1, xR, xC) ); dotProd += dot(xValues, wValues); } } else if (${m===3}) { vec3 wValues = vec3( getW(wR, wC, ${c}, d2), getW(wR, wC, ${c} + 1, d2), getW(wR, wC, ${c} + 2, d2) ); if (${f}) { vec3 xValues = vec3( getX(batch, xR, xC, ${c}), getX(batch, xR, xC, ${c} + 1), getX(batch, xR, xC, ${c} + 2) ); dotProd += dot(xValues, wValues); } else { vec3 xValues = vec3( getX(batch, ${c}, xR, xC), getX(batch, ${c} + 1, xR, xC), getX(batch, ${c} + 2, xR, xC) ); dotProd += dot(xValues, wValues); } } } } float result = dotProd; ${b} ${v} setOutput(result); } `}},cme=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let t=e.padInfo.front,n=e.padInfo.top,a=e.padInfo.left,r=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=e.dilationDepth,l=e.dilationHeight,u=e.dilationWidth,d=e.filterDepth,h=e.filterHeight,p=e.filterWidth,c=Math.floor(e.inChannels/4)*4,m=e.inChannels%4;this.userCode=` const ivec3 strides = ivec3(${r}, ${s}, ${i}); const ivec3 pads = ivec3(${t}, ${n}, ${a}); void main() { ivec5 coords = getOutputCoords(); int batch = coords.x; int d2 = coords.u; ivec3 xFRCCorner = ivec3(coords.y, coords.z, coords.w) * strides - pads; int xFCorner = xFRCCorner.x; int xRCorner = xFRCCorner.y; int xCCorner = xFRCCorner.z; // Convolve x(?, ?, ?, d1) with w(:, :, :, d1, d2) to get // y(yF, yR, yC, d2). ? = to be determined. : = across all // values in that axis. float dotProd = 0.0; for (int wF = 0; wF < ${d}; wF++) { int xF = xFCorner + wF * ${o}; if (xF < 0 || xF >= ${e.inDepth}) { continue; } for (int wR = 0; wR < ${h}; wR++) { int xR = xRCorner + wR * ${l}; if (xR < 0 || xR >= ${e.inHeight}) { continue; } for (int wC = 0; wC < ${p}; wC++) { int xC = xCCorner + wC * ${u}; if (xC < 0 || xC >= ${e.inWidth}) { continue; } for (int d1 = 0; d1 < ${c}; d1 += 4) { vec4 xValues = vec4( getX(batch, xF, xR, xC, d1), getX(batch, xF, xR, xC, d1 + 1), getX(batch, xF, xR, xC, d1 + 2), getX(batch, xF, xR, xC, d1 + 3) ); vec4 wValues = vec4( getW(wF, wR, wC, d1, d2), getW(wF, wR, wC, d1 + 1, d2), getW(wF, wR, wC, d1 + 2, d2), getW(wF, wR, wC, d1 + 3, d2) ); dotProd += dot(xValues, wValues); } if (${m===1}) { dotProd += getX(batch, xF, xR, xC, ${c}) * getW(wF, wR, wC, ${c}, d2); } else if (${m===2}) { vec2 xValues = vec2( getX(batch, xF, xR, xC, ${c}), getX(batch, xF, xR, xC, ${c} + 1) ); vec2 wValues = vec2( getW(wF, wR, wC, ${c}, d2), getW(wF, wR, wC, ${c} + 1, d2) ); dotProd += dot(xValues, wValues); } else if (${m===3}) { vec3 xValues = vec3( getX(batch, xF, xR, xC, ${c}), getX(batch, xF, xR, xC, ${c} + 1), getX(batch, xF, xR, xC, ${c} + 2) ); vec3 wValues = vec3( getW(wF, wR, wC, ${c}, d2), getW(wF, wR, wC, ${c} + 1, d2), getW(wF, wR, wC, ${c} + 2, d2) ); dotProd += dot(xValues, wValues); } } } } setOutput(dotProd); } `}},fme=class{constructor(e,t,n){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e;let{filterWidth:a,inChannels:r,strideWidth:s,strideHeight:i,padInfo:o,outWidth:l,dilationWidth:u,dilationHeight:d,dataFormat:h}=n,{left:p,top:c}=o,m=r*a,f=Wn(),g=h==="channelsLast",y=g?0:1,A=g?1:2,x="";for(let v=0;v<=1;v++)for(let b=0;b<=1;b++)x+=` blockIndex = rc.y + ${b}; pos = rc.x + ${v}; if(blockIndex < ${e[1]} && pos < ${e[0]}) { offsetY = int(blockIndex / (${l})) * ${i} - ${c}; d0 = offsetY + ${d} * (pos / ${m}); if(d0 < ${t[y]} && d0 >= 0) { offsetX = int(mod(float(blockIndex), ${l}.) * ${s}. - ${p}.); d1 = offsetX + ${u} * (int(mod(float(pos), ${m}.) / ${r}.)); if(d1 < ${t[A]} && d1 >= 0) { ch = int(mod(float(pos), ${r}.)); if (${g}) { innerDims = vec2(d1, ch); result[${v*2+b}] = getChannel( getA(d0, int(innerDims.x), int(innerDims.y)), innerDims); } else { innerDims = vec2(d0, d1); result[${v*2+b}] = 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; ${x} ${f.output} = result; } `}};function UE({x:e,filter:t,convInfo:n,backend:a,bias:r=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let l=e.shape,u=a.texData.get(e.dataId),d=n.inChannels,h=l[0]*l[1]*l[2],p=n.outChannels,c=n.dataFormat==="channelsLast",m=!1,f=!1,g,y=[],A=(h===1||p===1)&&d>RE,x=l[2]%2!=0&&!!u.isPacked;if(A||!se().getBool("WEBGL_LAZILY_UNPACK")||!se().getBool("WEBGL_PACK_BINARY_OPERATIONS")||!x){let v=c?l[0]*l[1]*l[2]:l[0]*l[2]*l[3],b=be({inputs:{x:e},backend:a,attrs:{shape:[1,v,n.inChannels]}}),w=be({inputs:{x:t},backend:a,attrs:{shape:[1,n.inChannels,n.outChannels]}}),I=q0({a:b,b:w,transposeA:m,transposeB:f,backend:a,bias:r,activation:o,preluActivationWeights:s,leakyreluAlpha:i});g=be({inputs:{x:I},backend:a,attrs:{shape:n.outShape}}),y.push(b),y.push(w),y.push(I)}else{let v=c?l[0]*l[1]*(l[2]+1):l[0]*l[2]*(l[3]+1),b={dataId:e.dataId,shape:[1,v,n.inChannels],dtype:e.dtype},w=u.shape;u.shape=u.shape.slice(),u.shape[u.shape.length-2]++,k.assert(up(u.shape,b.shape),()=>`packed reshape ${u.shape} to ${b.shape} isn't free`);let I=be({inputs:{x:t},backend:a,attrs:{shape:[1,n.inChannels,n.outChannels]}});y.push(I);let T=q0({a:b,b:I,backend:a,transposeA:m,transposeB:f,bias:r,activation:o,preluActivationWeights:s,leakyreluAlpha:i}),C=a.texData.get(T.dataId);k.assert(C.isPacked,()=>"batchMatMul result is expected to be packed"),u.shape=w,C.shape=n.outShape,g=fa({inputs:{x:T},backend:a}),g.shape=n.outShape,y.push(T)}for(let v of y)a.disposeIntermediateTensorInfo(v);return g}function jE({x:e,filter:t,convInfo:n,backend:a,bias:r=null,preluActivationWeights:s=null,leakyreluAlpha:i=0,activation:o=null}){let{filterWidth:l,filterHeight:u,inChannels:d,outWidth:h,outHeight:p,dataFormat:c}=n,m=c==="channelsLast",f=l*u*d,g=p*h,y=[f,g],A=!0,x=!1,v=[],b=be({inputs:{x:e},backend:a,attrs:{shape:e.shape.slice(1)}}),w=be({inputs:{x:t},backend:a,attrs:{shape:[1,f,k.sizeFromShape(t.shape)/f]}});v.push(b),v.push(w);let I=new fme(y,b.shape,n),T=a.runWebGLProgram(I,[b],"float32"),C=be({inputs:{x:T},backend:a,attrs:{shape:[1,y[0],y[1]]}});v.push(T),v.push(C);let z=r!=null,$=s!=null,S=o==="leakyrelu",D=o?j0(o,!0):null,_=new TE(C.shape,w.shape,[1,g,n.outChannels],A,x,z,D,$,S),W=[C,w];if(r&&W.push(r),$&&W.push(s),S){let ee=a.makeTensorInfo([],"float32",k.createScalarValue(i,"float32"));W.push(ee),v.push(ee)}let X=a.runWebGLProgram(_,W,"float32"),q=m?[1,p,h,n.outChannels]:[1,n.outChannels,p,h],Q=be({inputs:{x:X},backend:a,attrs:{shape:q}});v.push(X);for(let ee of v)a.disposeIntermediateTensorInfo(ee);return Q}function mme(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dataFormat:l,dilations:u,dimRoundingMode:d}=a,h=M.convertConv2DDataFormat(l),p=M.computeConv2DInfo(r.shape,s.shape,i,u,o,d,!1,h),c;if(p.filterHeight===1&&p.filterWidth===1&&p.dilationHeight===1&&p.dilationWidth===1&&p.strideHeight===1&&p.strideWidth===1&&(p.padInfo.type==="SAME"||p.padInfo.type==="VALID"))c=UE({x:r,filter:s,convInfo:p,backend:n});else if(se().getBool("WEBGL_CONV_IM2COL")&&r.shape[0]===1)c=jE({x:r,filter:s,convInfo:p,backend:n});else{let f=new VE(p);c=n.runWebGLProgram(f,[r,s],"float32")}let m=be({inputs:{x:c},backend:n,attrs:{shape:p.outShape}});return n.disposeIntermediateTensorInfo(c),m}var gme={kernelName:tl,backendName:"webgl",kernelFunc:mme},yme=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,a=e.padInfo.top,r=e.padInfo.left,s=e.dataFormat==="channelsLast";this.userCode=` void main() { ivec4 coords = getOutputCoords(); int wR = coords.x; int wC = coords.y; int d1 = coords.z; int d2 = coords.w; // Convolve x(?, ?, d1) with dy(:, :, d2) to get dw(wR, wC, d1, d2). // ? = to be determined. : = across all values in that axis. float dotProd = 0.0; for (int b = 0; b < ${e.batchSize}; b++) { for (int yR = 0; yR < ${e.outHeight}; yR++) { int xR = wR + yR * ${t} - ${a}; if (xR < 0 || xR >= ${e.inHeight}) { continue; } for (int yC = 0; yC < ${e.outWidth}; yC++) { int xC = wC + yC * ${n} - ${r}; if (xC < 0 || xC >= ${e.inWidth}) { continue; } if (${s}) { float dyValue = getDy(b, yR, yC, d2); float xValue = getX(b, xR, xC, d1); dotProd += (xValue * dyValue); } else { float dyValue = getDy(b, d2, yR, yC); float xValue = getX(b, d1, xR, xC); dotProd += (xValue * dyValue); } } } } setOutput(dotProd); } `}},Ame=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,a=e.strideHeight,r=e.strideWidth,s=e.dataFormat==="channelsLast",i=t-1-e.padInfo.top,o=n-1-e.padInfo.left,l=s?1:2,u=s?2:3,d=s?3:1;this.userCode=` const ivec2 pads = ivec2(${i}, ${o}); void main() { ivec4 coords = getOutputCoords(); int batch = coords[0]; int d1 = coords[${d}]; ivec2 dyCorner = ivec2(coords[${l}], coords[${u}]) - pads; int dyRCorner = dyCorner.x; int dyCCorner = dyCorner.y; // Convolve dy(?, ?, d2) with w(:, :, d1, d2) to compute dx(xR, xC, d1). // ? = to be determined. : = across all values in that axis. float dotProd = 0.0; for (int wR = 0; wR < ${t}; wR++) { float dyR = float(dyRCorner + wR) / ${a}.0; if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); int wRPerm = ${t} - 1 - wR; for (int wC = 0; wC < ${n}; wC++) { float dyC = float(dyCCorner + wC) / ${r}.0; if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); int wCPerm = ${n} - 1 - wC; for (int d2 = 0; d2 < ${e.outChannels}; d2++) { if (${s}) { float xValue = getDy(batch, idyR, idyC, d2); float wValue = getW(wRPerm, wCPerm, d1, d2); dotProd += xValue * wValue; } else { float xValue = getDy(batch, d2, idyR, idyC); float wValue = getW(wRPerm, wCPerm, d1, d2); dotProd += xValue * wValue; } } } } setOutput(dotProd); } `}},xme=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideDepth,n=e.strideHeight,a=e.strideWidth,r=e.padInfo.front,s=e.padInfo.top,i=e.padInfo.left;this.userCode=` void main() { ivec5 coords = getOutputCoords(); int wF = coords.x; int wR = coords.y; int wC = coords.z; int d1 = coords.w; int d2 = coords.u; float dotProd = 0.0; for (int b = 0; b < ${e.batchSize}; b++) { for (int yF = 0; yF < ${e.outDepth}; yF++) { int xF = wF + yF * ${t} - ${r}; if (xF < 0 || xF >= ${e.inDepth}) { continue; } for (int yR = 0; yR < ${e.outHeight}; yR++) { int xR = wR + yR * ${n} - ${s}; if (xR < 0 || xR >= ${e.inHeight}) { continue; } for (int yC = 0; yC < ${e.outWidth}; yC++) { int xC = wC + yC * ${a} - ${i}; if (xC < 0 || xC >= ${e.inWidth}) { continue; } float dyValue = getDy(b, yF, yR, yC, d2); float xValue = getX(b, xF, xR, xC, d1); dotProd += (xValue * dyValue); } } } } setOutput(dotProd); } `}},bme=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterDepth,n=e.filterHeight,a=e.filterWidth,r=e.strideDepth,s=e.strideHeight,i=e.strideWidth,o=t-1-e.padInfo.front,l=n-1-e.padInfo.top,u=a-1-e.padInfo.left;this.userCode=` const ivec3 pads = ivec3(${o}, ${l}, ${u}); void main() { ivec5 coords = getOutputCoords(); int batch = coords.x; int d1 = coords.u; ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads; int dyFCorner = dyCorner.x; int dyRCorner = dyCorner.y; int dyCCorner = dyCorner.z; float dotProd = 0.0; for (int wF = 0; wF < ${t}; wF++) { float dyF = float(dyFCorner + wF) / ${r}.0; if (dyF < 0.0 || dyF >= ${e.outDepth}.0 || fract(dyF) > 0.0) { continue; } int idyF = int(dyF); int wFPerm = ${t} - 1 - wF; for (int wR = 0; wR < ${n}; wR++) { float dyR = float(dyRCorner + wR) / ${s}.0; if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); int wRPerm = ${n} - 1 - wR; for (int wC = 0; wC < ${a}; wC++) { float dyC = float(dyCCorner + wC) / ${i}.0; if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); int wCPerm = ${a} - 1 - wC; for (int d2 = 0; d2 < ${e.outChannels}; d2++) { float xValue = getDy(batch, idyF, idyR, idyC, d2); float wValue = getW(wFPerm, wRPerm, wCPerm, d1, d2); dotProd += xValue * wValue; } } } } setOutput(dotProd); } `}};function vme(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,pad:o,dataFormat:l,dimRoundingMode:u,filterShape:d}=a,h=M.convertConv2DDataFormat(l),p=M.computeConv2DInfo(r.shape,d,i,1,o,u,!1,h),c=new yme(p);return n.runWebGLProgram(c,[r,s],"float32")}var wme={kernelName:S1,backendName:"webgl",kernelFunc:vme};function kme(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{inputShape:i,strides:o,pad:l,dataFormat:u,dimRoundingMode:d}=a,h=M.convertConv2DDataFormat(u),p=M.computeConv2DInfo(i,s.shape,o,1,l,d,!1,h),c=new Ame(p);return n.runWebGLProgram(c,[r,s],"float32")}var Ime={kernelName:nl,backendName:"webgl",kernelFunc:kme};function Sme(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=a,u=M.computeConv3DInfo(r.shape,s.shape,i,l,o),d=new cme(u);return n.runWebGLProgram(d,[r,s],"float32")}var Nme={kernelName:Yc,backendName:"webgl",kernelFunc:Sme};function Tme(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,pad:o,filterShape:l}=a,u=M.computeConv3DInfo(r.shape,l,i,1,o),d=new xme(u);return n.runWebGLProgram(d,[r,s],"float32")}var Eme={kernelName:N1,backendName:"webgl",kernelFunc:Tme};function Cme(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{pad:i,strides:o,inputShape:l}=a,u=M.computeConv3DInfo(l,s.shape,o,1,i),d=new bme(u);return n.runWebGLProgram(d,[r,s],"float32")}var Mme={kernelName:T1,backendName:"webgl",kernelFunc:Cme},$me=NE+` return cos(x); `,Rme=ot({opSnippet:$me}),Fme={kernelName:al,backendName:"webgl",kernelFunc:Rme},Ome=` float e2x = exp(-x); return (e2x + 1.0 / e2x) / 2.0; `,Dme=ot({opSnippet:Ome}),_me={kernelName:Md,backendName:"webgl",kernelFunc:Dme},zme=class{constructor(e,t,n,a,r){this.variableNames=["Image","Boxes","BoxInd"],this.outputShape=[];let[s,i,o,l]=e,[u]=t,[d,h]=n;this.outputShape=[u,d,h,l];let p=a==="bilinear"?1:0,[c,m]=[`${i-1}.0`,`${o-1}.0`],[f,g,y]=d>1?[`${(i-1)/(d-1)}`,"(y2-y1) * height_ratio",`y1*${c} + float(y)*(height_scale)`]:["0.0","0.0",`0.5 * (y1+y2) * ${c}`],[A,x,v]=h>1?[`${(o-1)/(h-1)}`,"(x2-x1) * width_ratio",`x1*${m} + float(x)*(width_scale)`]:["0.0","0.0",`0.5 * (x1+x2) * ${m}`];this.userCode=` const float height_ratio = float(${f}); const float width_ratio = float(${A}); void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; int y = coords[1]; int x = coords[2]; int d = coords[3]; // get box vals float y1 = getBoxes(b,0); float x1 = getBoxes(b,1); float y2 = getBoxes(b,2); float x2 = getBoxes(b,3); // get image in batch index int bInd = round(getBoxInd(b)); if(bInd < 0 || bInd >= ${s}) { return; } float height_scale = ${g}; float width_scale = ${x}; float in_y = ${y}; if( in_y < 0.0 || in_y > ${c} ) { setOutput(float(${r})); return; } float in_x = ${v}; if( in_x < 0.0 || in_x > ${m} ) { setOutput(float(${r})); return; } vec2 sourceFracIndexCR = vec2(in_x,in_y); if(${p} == 1) { // Compute the four integer indices. ivec2 sourceFloorCR = ivec2(sourceFracIndexCR); ivec2 sourceCeilCR = ivec2(ceil(sourceFracIndexCR)); float topLeft = getImage(b, sourceFloorCR.y, sourceFloorCR.x, d); float bottomLeft = getImage(b, sourceCeilCR.y, sourceFloorCR.x, d); float topRight = getImage(b, sourceFloorCR.y, sourceCeilCR.x, d); float bottomRight = getImage(b, sourceCeilCR.y, sourceCeilCR.x, d); vec2 fracCR = sourceFracIndexCR - vec2(sourceFloorCR); float top = topLeft + (topRight - topLeft) * fracCR.x; float bottom = bottomLeft + (bottomRight - bottomLeft) * fracCR.x; float newValue = top + (bottom - top) * fracCR.y; setOutput(newValue); } else { // Compute the coordinators of nearest neighbor point. ivec2 sourceNearestCR = ivec2(floor( sourceFracIndexCR + vec2(0.5,0.5))); float newValue = getImage(b, sourceNearestCR.y, sourceNearestCR.x, d); setOutput(newValue); } } `}},Pme=e=>{let{inputs:t,backend:n,attrs:a}=e,{image:r,boxes:s,boxInd:i}=t,{cropSize:o,method:l,extrapolationValue:u}=a,d=new zme(r.shape,s.shape,o,l,u);return n.runWebGLProgram(d,[r,s,i],"float32")},Lme={kernelName:$d,backendName:"webgl",kernelFunc:Pme},HE=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=e;let a=e.length,r=t?"0.0":`getX(${GE(a,"coords")})`,s=e[e.length-1],i="",o="";t?(i=n?`end != ${s-1}`:"end != 0",o=n?"end + 1":"end - 1"):(i=n?`end + pow2 < ${s}`:"end >= pow2",o=n?"end + pow2":"end - pow2"),this.userCode=` uniform float index; void main() { ${kt(a)} coords = getOutputCoords(); int end = ${qE(a,"coords")}; float val = ${r}; int pow2 = int(pow(2.0, index)); if (${i}) { int idx = ${o}; ${qE(a,"coords")} = idx; val += getX(${GE(a,"coords")}); } setOutput(val); } `}getCustomSetupFunc(e){return(t,n)=>{this.index==null&&(this.index=t.getUniformLocation(n,"index")),t.gl.uniform1f(this.index,e)}}};function GE(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 qE(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 Wme(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,exclusive:i,reverse:o}=a,l=r.shape.length,u=M.getAxesPermutation([s],l),d=r;u!=null&&(d=Vn({inputs:{x:r},backend:n,attrs:{perm:u}}));let h=M.getInnerMostAxes(1,l)[0];if(h!==l-1)throw new Error(`WebGL cumsum shader expects an inner-most axis=${r.shape.length-1} but got axis=${s}`);let p=d.shape[h],c=fa({inputs:{x:d},backend:n});for(let m=0;m<=Math.ceil(Math.log2(p))-1;m++){let f=new HE(d.shape,!1,o),g=f.getCustomSetupFunc(m),y=c;c=n.runWebGLProgram(f,[c],c.dtype,g),n.disposeIntermediateTensorInfo(y)}if(i){let m=new HE(d.shape,i,o),f=c;c=n.runWebGLProgram(m,[c],c.dtype),n.disposeIntermediateTensorInfo(f)}if(u!=null){let m=M.getUndoAxesPermutation(u),f=Vn({inputs:{x:c},backend:n,attrs:{perm:m}});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(d),f}return c}var Bme={kernelName:rl,backendName:"webgl",kernelFunc:Wme};function Vme(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,weights:s}=t,{size:i,binaryOutput:o}=a;if(r.shape.length===1){let l=n.readSync(r.dataId),u=n.readSync(s.dataId),d=dE(l,u,s.dtype,s.shape,i);return n.makeTensorInfo([i],s.dtype,d)}else if(r.shape.length===2){let l=n.bufferSync(r),u=n.bufferSync(s),d=ace(l,u,i,o);return n.makeTensorInfo(d.shape,s.dtype,d.values)}throw new Error(`Error in denseBincount: input must be at most rank 2, but got rank${r.shape.length}.`)}var Ume={kernelName:E1,backendName:"webgl",kernelFunc:Vme},jme=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 Hme(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockSize:s,dataFormat:i}=a;k.assert(s>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${s}`);let o=r.shape[0],l=i==="NHWC"?r.shape[1]:r.shape[2],u=i==="NHWC"?r.shape[2]:r.shape[3],d=i==="NHWC"?r.shape[3]:r.shape[1],h=l*s,p=u*s,c=d/(s*s),m=i==="NHWC"?[o,h,p,c]:[o,c,h,p],f=new jme(m,s,i);return n.runWebGLProgram(f,[r],r.dtype)}var Gme={kernelName:Rd,backendName:"webgl",kernelFunc:Hme},KE=class{constructor(e,t=!1,n=null,a=!1,r=!1){this.variableNames=["x","W"],this.outputShape=e.outShape;let s=e.inHeight,i=e.inWidth,o=e.padInfo.top,l=e.padInfo.left,u=e.strideHeight,d=e.strideWidth,h=e.dilationHeight,p=e.dilationWidth,c=e.filterHeight,m=e.filterWidth,f=e.outChannels/e.inChannels,g="",y="";n&&(a?g=`float activation(float a) { float b = getPreluActivationWeightsAtOutCoords(); ${n} }`:r?g=`float activation(float a) { float b = getLeakyreluAlphaAtOutCoords(); ${n} }`:g=` float activation(float x) { ${n} } `,y="result = activation(result);");let A=t?"result += getBiasAtOutCoords();":"";t&&this.variableNames.push("bias"),a&&this.variableNames.push("preluActivationWeights"),r&&this.variableNames.push("leakyreluAlpha"),this.userCode=` ${g} const ivec2 strides = ivec2(${u}, ${d}); const ivec2 pads = ivec2(${o}, ${l}); void main() { ivec4 coords = getOutputCoords(); int batch = coords.x; ivec2 xRCCorner = coords.yz * strides - pads; int d2 = coords.w; int d1 = d2 / ${f}; int q = d2 - d1 * ${f}; 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 < ${c}; wR++) { int xR = xRCorner + wR * ${h}; if (xR < 0 || xR >= ${s}) { continue; } for (int wC = 0; wC < ${m}; wC++) { int xC = xCCorner + wC * ${p}; if (xC < 0 || xC >= ${i}) { continue; } float xVal = getX(batch, xR, xC, d1); float wVal = getW(wR, wC, d1, q); dotProd += xVal * wVal; } } float result = dotProd; ${A} ${y} setOutput(result); } `}},XE=class{constructor(e,t=!1,n=null,a=!1,r=!1){this.variableNames=["x","W"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=e.outShape;let s=e.outChannels/e.inChannels,i=e.inHeight,o=e.inWidth,l=e.padInfo.top,u=e.padInfo.left,d=e.strideHeight,h=e.strideWidth,p=e.dilationHeight,c=e.dilationWidth,m=e.filterHeight,f=e.filterWidth,g=f,y=` int xR; int xC; int xCOffset; vec4 wTexel; vec4 previous; vec4 final;`;for(let b=0;b=0 && xR < ${i}) { `;for(let w=0;w<(g+1)/2;w++){let I=w*2,T=I*c;if(y+=` xC = xCCorner + ${T}; `,h===1){if(I= 0 && xCOffset < ${o} && xTexelC${T}Ready == 0) { xTexelC${T} = getX(batch, xR, xCOffset, d1); // Need to manually clear unused channels in case // we're reading from recycled texture. if (xCOffset + 1 >= ${o}) { xTexelC${T}.zw = vec2(0.0); } xTexelC${T}Ready = 1; } `,c===1&&T>0?y+=` xC${I} = vec4(xTexelC${T-2}.zw, xTexelC${T}.xy); `:y+=` xCOffset = xC + 1 - 2; if (xCOffset >= 0 && xCOffset < ${o}) { previous = getX(batch, xR, xCOffset, d1); // Need to manually clear unused channels in case // we're reading from recycled texture. if (xCOffset + 1 >= ${o}) { previous.zw = vec2(0.0); } xC${I} = vec4(previous.zw, xTexelC${T}.xy); } else { xC${I} = vec4(0.0, 0.0, xTexelC${T}.xy); } `):y+=` if (xC >= 0 && xC < ${o} && xTexelC${T}Ready == 0) { xTexelC${T} = getX(batch, xR, xC, d1); if (xC + 1 >= ${o}) { xTexelC${T}.zw = vec2(0.0); } xTexelC${T}Ready = 1; } xC${I} = xTexelC${T}; `,T+1= 0 && xCOffset < ${o} && xTexelC${T+2}Ready == 0) { xTexelC${T+2} = getX(batch, xR, xCOffset, d1); // Need to manually clear unused channels in case // we're reading from recycled texture. if (xCOffset + 1 >= ${o}) { xTexelC${T+2}.zw = vec2(0.0); } xTexelC${T+2}Ready = 1; } `,c>1&&(y+=` xCOffset -= 2; if (xCOffset >= 0 && xCOffset < ${o} && xTexelC${T}Ready == 0) { xTexelC${T} = getX(batch, xR, xCOffset, d1); xTexelC${T}Ready = 1; } `),y+=` xC${I+1} = vec4(xTexelC${T}.zw, xTexelC${T+2}.xy); `):C===1?y+=` xC${I+1} = xTexelC${T}; `:y+=` xCOffset = xC + ${C}; if (xCOffset >= 0 && xCOffset < ${o} && xTexelC${T+2}Ready == 0) { xTexelC${T+2} = getX(batch, xR, xCOffset, d1); if (xCOffset + 1 >= ${o}) { xTexelC${T+2}.zw = vec2(0.0); } xTexelC${T+2}Ready = 1; } xC${I+1} = xTexelC${T+2}; `}}else T= 0 && xCOffset < ${o} && xTexelC${T}Ready == 0) { xTexelC${T} = getX(batch, xR, xCOffset, d1); // Need to manually clear unused channels in case // we're reading from recycled texture. if (xCOffset + 1 >= ${o}) { xTexelC${T}.zw = vec2(0.0); } xTexelC${T}Ready = 1; } if(xC + 1 >= 0 && xC + 1 < ${o} && xTexelC${T+2}Ready == 0) { xTexelC${T+2} = getX(batch, xR, xC + 1, d1); // Need to manually clear unused channels in case // we're reading from recycled texture. if (xC + 2 >= ${o}) { xTexelC${T+2}.zw = vec2(0.0); } xTexelC${T+2}Ready = 1; } xC${I} = vec4(xTexelC${T}.zw, xTexelC${T+2}.zw); `,T+1= 0 && xCOffset < ${o}) { final = getX(batch, xR, xCOffset, d1); } xC${I+1} = vec4(xTexelC${T+2}.xy, final.xy); `)):(y+=` if(xC >= 0 && xC < ${o} && xTexelC${T}Ready == 0) { xTexelC${T} = getX(batch, xR, xC, d1); if (xC + 1 >= ${o}) { xTexelC${T}.zw = vec2(0.0); } xTexelC${T}Ready = 1; } xCOffset = xC + ${h}; if(xCOffset >= 0 && xCOffset < ${o} && xTexelC${T+2}Ready == 0) { xTexelC${T+2} = getX(batch, xR, xCOffset, d1); if (xCOffset + 1 >= ${o}) { xTexelC${T+2}.zw = vec2(0.); } xTexelC${T+2}Ready = 1; } xC${I} = vec4( xTexelC${T}.xy, xTexelC${T+2}.xy); `,T+1`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${i} and dilations '${d}'`);let h=M.computeConv2DInfo(r.shape,s.shape,i,d,o,u,!0),p;return se().getBool("WEBGL_PACK_DEPTHWISECONV")&&h.strideWidth<=2&&h.outChannels/h.inChannels==1?p=new XE(h):p=new KE(h),n.runWebGLProgram(p,[r,s],"float32")}var Kme={kernelName:sl,backendName:"webgl",kernelFunc:qme},Xme=class{constructor(e){this.variableNames=["x","dy"],this.outputShape=e.filterShape;let t=e.strideHeight,n=e.strideWidth,a=e.padInfo.top,r=e.padInfo.left,s=e.outChannels/e.inChannels;this.userCode=` void main() { ivec4 coords = getOutputCoords(); int wR = coords.x; int wC = coords.y; int d1 = coords.z; int dm = coords.w; int d2 = d1 * ${s} + dm; float dotProd = 0.0; // TO DO: Vec4 over the batch size for (int b = 0; b < ${e.batchSize}; b++) { for (int yR = 0; yR < ${e.outHeight}; yR++) { int xR = wR + yR * ${t} - ${a}; if (xR < 0 || xR >= ${e.inHeight}) { continue; } for (int yC = 0; yC < ${e.outWidth}; yC++) { int xC = wC + yC * ${n} - ${r}; if (xC < 0 || xC >= ${e.inWidth}) { continue; } float dyValue = getDy(b, yR, yC, d2); float xValue = getX(b, xR, xC, d1); dotProd += (xValue * dyValue); } } } setOutput(dotProd); } `}},Zme=class{constructor(e){this.variableNames=["dy","W"],this.outputShape=e.inShape;let t=e.filterHeight,n=e.filterWidth,a=e.strideHeight,r=e.strideWidth,s=t-1-e.padInfo.top,i=n-1-e.padInfo.left,o=e.outChannels/e.inChannels;this.userCode=` const ivec2 pads = ivec2(${s}, ${i}); void main() { ivec4 coords = getOutputCoords(); int batch = coords[0]; int d1 = coords[3]; ivec2 dyCorner = coords.yz - pads; int dyRCorner = dyCorner.x; int dyCCorner = dyCorner.y; float dotProd = 0.0; for (int wR = 0; wR < ${t}; wR++) { float dyR = float(dyRCorner + wR) / ${a}.0; if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); int wRPerm = ${t} - 1 - wR; for (int wC = 0; wC < ${n}; wC++) { float dyC = float(dyCCorner + wC) / ${r}.0; if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); int wCPerm = ${n} - 1 - wC; // TO DO: Vec4 over the channelMul for (int dm = 0; dm < ${o}; dm++) { int d2 = d1 * ${o} + dm; float xValue = getDy(batch, idyR, idyC, d2); float wValue = getW(wRPerm, wCPerm, d1, dm); dotProd += xValue * wValue; } } } setOutput(dotProd); } `}};function Yme(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,dy:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,filterShape:d}=a,h=M.computeConv2DInfo(r.shape,d,i,o,l,u,!0),p=new Xme(h);return n.runWebGLProgram(p,[r,s],"float32")}var Jme={kernelName:C1,backendName:"webgl",kernelFunc:Yme};function Qme(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,filter:s}=t,{strides:i,dilations:o,pad:l,dimRoundingMode:u,inputShape:d}=a,h=M.computeConv2DInfo(d,s.shape,i,o,l,u,!0),p=new Zme(h);return n.runWebGLProgram(p,[r,s],"float32")}var ege={kernelName:M1,backendName:"webgl",kernelFunc:Qme},tge=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 nge(e){let{inputs:t,backend:n}=e,{x:a}=t,r=[...a.shape,...a.shape],s=k.sizeFromShape(a.shape),i=be({inputs:{x:a},backend:n,attrs:{shape:[s]}}),o=new tge(s),l=n.runWebGLProgram(o,[i],i.dtype),u=be({inputs:{x:l},backend:n,attrs:{shape:r}});return n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(l),u}var age={kernelName:$1,backendName:"webgl",kernelFunc:nge},rge=class{constructor(e){this.variableNames=["x","W"],this.outputShape=e.outShape;let{inHeight:t,inWidth:n,padInfo:a,strideHeight:r,strideWidth:s,filterHeight:i,filterWidth:o,dilationHeight:l,dilationWidth:u}=e,{top:d,left:h}=a;this.userCode=` const ivec2 strides = ivec2(${r}, ${s}); const ivec2 pads = ivec2(${d}, ${h}); const float neg_infinity = -3.4e38; void main() { ivec4 coords = getOutputCoords(); int batch = coords.x; int d1 = coords.w; ivec2 outTopLeftCorner = coords.yz * strides - pads; int hBeg = outTopLeftCorner.x; int wBeg = outTopLeftCorner.y; float curVal = neg_infinity; for (int h = 0; h < ${i}; h++) { int hIn = hBeg + h * ${l}; if (hIn >= 0 && hIn < ${t}) { for (int w = 0; w < ${o}; w++) { int wIn = wBeg + w * ${u}; if (wIn >= 0 && wIn < ${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 sge(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s}=t,{strides:i,pad:o,dilations:l}=a,u=M.computeDilation2DInfo(r.shape,s.shape,i,o,"NHWC",l),d,h=new rge(u);d=n.runWebGLProgram(h,[r,s],"float32");let p=be({inputs:{x:d},backend:n,attrs:{shape:u.outShape}});return n.disposeIntermediateTensorInfo(d),p}var ige={kernelName:Jc,backendName:"webgl",kernelFunc:sge};function oge(e){let{inputs:t,backend:n,attrs:a}=e,{equation:r}=a,s=t,{allDims:i,summedDims:o,idDims:l}=M.decodeEinsumEquation(r,s.length);M.checkEinsumDimSizes(i.length,l,s);let{path:u,steps:d}=M.getEinsumComputePath(o,l),h=d.length,p=null,c=i.length,m=[];for(let f=0;f=0&&(p=G0({inputs:{x:p},backend:n,attrs:{axis:u[f]-(i.length-c),keepDims:!1}}),m.push(p)),c--)}for(let f of m)f!==p&&n.disposeIntermediateTensorInfo(f);return p}var lge={kernelName:O1,backendName:"webgl",kernelFunc:oge},uge="return (x >= 0.0) ? x : (exp(x) - 1.0);",dge=` 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; `,hge=ot({opSnippet:uge,packedOpSnippet:dge}),pge={kernelName:Fd,backendName:"webgl",kernelFunc:hge},cge="return (b >= 1.0) ? a : a * (b + 1.0);",fge=` vec4 bGTEZero = vec4(greaterThanEqual(b, vec4(0.))); return (bGTEZero * a) + ((vec4(1.0) - bGTEZero) * (a * (b + vec4(1.0)))); `,mge=e=>{let{inputs:t,backend:n}=e,{dy:a,y:r}=t,s=se().getBool("WEBGL_PACK_BINARY_OPERATIONS")?new pp(fge,a.shape,r.shape):new ku(cge,a.shape,r.shape);return n.runWebGLProgram(s,[a,r],a.dtype)},gge={kernelName:D1,backendName:"webgl",kernelFunc:mge},yge=` return vec4(equal(a, b)); `,Age="return float(a == b);",xge=Tn({opSnippet:Age,packedOpSnippet:yge,dtype:"bool",cpuKernelImpl:ice}),bge={kernelName:ol,backendName:"webgl",kernelFunc:xge},vge=` // Error function is calculated approximately with elementary function. // See "Handbook of Mathematical Functions with Formulas, // Graphs, and Mathematical Tables", Abramowitz and Stegun. float p = ${M.ERF_P}; float a1 = ${M.ERF_A1}; float a2 = ${M.ERF_A2}; float a3 = ${M.ERF_A3}; float a4 = ${M.ERF_A4}; float a5 = ${M.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)); `,wge=ot({opSnippet:vge}),kge={kernelName:Od,backendName:"webgl",kernelFunc:wge},ZE="return exp(x);",YE=ot({opSnippet:ZE,packedOpSnippet:ZE,cpuKernelImpl:oce}),Ige={kernelName:Ei,backendName:"webgl",kernelFunc:YE};function pb(e){let{inputs:t,attrs:n,backend:a}=e,{dim:r}=n,{input:s}=t,i=s.shape.length,o=s.shape.slice(),l=r;return r<0&&(k.assert(-(i+1)<=r,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+r+1),o.splice(l,0,1),be({inputs:{x:s},backend:a,attrs:{shape:o}})}var Sge={kernelName:Dd,backendName:"webgl",kernelFunc:pb},JE="return exp(x) - 1.0;",Nge=ot({opSnippet:JE,packedOpSnippet:JE,cpuKernelImpl:lce}),Tge={kernelName:ll,backendName:"webgl",kernelFunc:Nge},QE=class{constructor(e,t,n){this.variableNames=["real","imag"];let a=t[1];this.outputShape=t;let r=n?`2.0 * ${Math.PI}`:`-2.0 * ${Math.PI}`,s=n?`${a}.0`:"1.0",i;if(e==="real")i="return real * expR - imag * expI;";else if(e==="imag")i="return real * expI + imag * expR;";else throw new Error(`FFT component must be either "real" or "imag", got ${e}.`);this.userCode=` const float exponentMultiplier = ${r}; float unaryOpComplex(float real, float expR, float imag, float expI) { ${i} } float mulMatDFT(int batch, int index) { float indexRatio = float(index) / float(${a}); float exponentMultiplierTimesIndexRatio = exponentMultiplier * indexRatio; float result = 0.0; for (int i = 0; i < ${a}; i++) { // x = (-2|2 * PI / N) * index * i; float x = exponentMultiplierTimesIndexRatio * float(i); float expR = cos(x); float expI = sin(x); float real = getReal(batch, i); float imag = getImag(batch, i); result += unaryOpComplex(real, expR, imag, expI) / ${s}; } return result; } void main() { ivec2 coords = getOutputCoords(); setOutput(mulMatDFT(coords[0], coords[1])); } `}};function eC(e,t,n){let a=n.texData.get(e.dataId),r=k.sizeFromShape(e.shape),s=e.shape[e.shape.length-1],i=r/s,o=be({inputs:{x:e},backend:n,attrs:{shape:[i,s]}}),l=o.shape,u=new QE("real",l,t),d=new QE("imag",l,t),h=[{dataId:a.complexTensorInfos.real.dataId,dtype:a.complexTensorInfos.real.dtype,shape:l},{dataId:a.complexTensorInfos.imag.dataId,dtype:a.complexTensorInfos.imag.dtype,shape:l}],p=n.runWebGLProgram(u,h,"float32"),c=n.runWebGLProgram(d,h,"float32"),m=ei({inputs:{real:p,imag:c},backend:n});n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(c);let f=be({inputs:{x:m},backend:n,attrs:{shape:e.shape}});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(m),f}function Ege(e){let{inputs:t,backend:n}=e,{input:a}=t;return eC(a,!1,n)}var Cge={kernelName:_1,backendName:"webgl",kernelFunc:Ege},Mge=class{constructor(e,t){this.outputShape=[],this.variableNames=["x"],this.outputShape=e,this.userCode=` uniform float value; void main() { // Input can be obtained from uniform value. setOutput(value); } `}getCustomSetupFunc(e){return(t,n)=>{this.valueLoc==null&&(this.valueLoc=t.getUniformLocationNoThrow(n,"value")),t.gl.uniform1f(this.valueLoc,e)}}};function cb(e){let{backend:t,attrs:n}=e,{shape:a,value:r}=n,{dtype:s}=n;if(s=s||k.inferDtype(r),s==="string"){let i=k.getArrayFromDType(s,k.sizeFromShape(a));return i.fill(r),t.makeTensorInfo(a,s,i)}else{let i=new Mge(a,r),o=i.getCustomSetupFunc(r);return t.runWebGLProgram(i,[],s,o)}}var $ge={kernelName:Qc,backendName:"webgl",kernelFunc:cb},Rge=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; 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); } `}},Fge={kernelName:_d,backendName:"webgl",kernelFunc:({inputs:e,backend:t})=>{let{image:n}=e,a=t,r=new Rge(n.shape);return a.runWebGLProgram(r,[n],n.dtype)}},tC="return floor(x);",Oge=ot({opSnippet:tC,packedOpSnippet:tC,cpuKernelImpl:uce}),Dge={kernelName:Ci,backendName:"webgl",kernelFunc:Oge},_ge=` 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; } `,zge=` 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); `,Pge=Tn({opSnippet:_ge,packedOpSnippet:zge,dtype:"int32"}),Lge={kernelName:ul,backendName:"webgl",kernelFunc:Pge},Wge=class{constructor(e){this.variableNames=["A"];let t=Wn(),[n,a]=e;this.outputShape=e,this.userCode=` void main() { ivec3 coords = getOutputCoords(); int texR = coords[0]; int texC = coords[1]; int depth = coords[2]; vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${a}.0, ${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)); } `}},Bge=class{constructor(e){this.variableNames=["A"],this.packedInputs=!1,this.packedOutput=!0;let t=Wn(),[n,a]=e;this.outputShape=e,this.userCode=` void main() { ivec3 coords = getOutputCoords(); int texR = coords[0]; int texC = coords[1]; int depth = coords[2]; vec4 result = vec4(0.); for(int row=0; row<=1; row++) { for(int col=0; col<=1; col++) { texC = coords[1] + row; depth = coords[2] + col; vec2 uv = (vec2(texC, texR) + halfCR) / vec2(${a}.0, ${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; } `}},Vge={kernelName:aA,backendName:"webgl",kernelFunc:Uge},Su;function Uge(e){let{inputs:t,backend:n,attrs:a}=e,{pixels:r}=t,{numChannels:s}=a,i=typeof HTMLVideoElement!="undefined"&&r instanceof HTMLVideoElement,o=typeof HTMLImageElement!="undefined"&&r instanceof HTMLImageElement,[l,u]=i?[r.videoWidth,r.videoHeight]:[r.width,r.height],d=[u,l],h=[u,l,s];(o||i)&&(Su==null&&(Su=document.createElement("canvas").getContext("2d")),Su.canvas.width=l,Su.canvas.height=u,Su.drawImage(r,0,0,l,u),r=Su.canvas);let p=n.makeTensorInfo(d,"int32");n.texData.get(p.dataId).usage=_a.PIXELS,n.gpgpu.uploadPixelDataToTexture(n.getTexture(p.dataId),r);let c=se().getBool("WEBGL_PACK")?new Bge(h):new Wge(h),m=n.runWebGLProgram(c,[p],"int32");return n.disposeData(p.dataId),m}function jge(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dataFormat:d,dilations:h,dimRoundingMode:p,activation:c,leakyreluAlpha:m}=a,f=M.convertConv2DDataFormat(d),g=M.computeConv2DInfo(r.shape,s.shape,l,h,u,p,!1,f),y,A=[];if(g.filterHeight===1&&g.filterWidth===1&&g.dilationHeight===1&&g.dilationWidth===1&&g.strideHeight===1&&g.strideWidth===1&&(g.padInfo.type==="SAME"||g.padInfo.type==="VALID"))y=UE({x:r,filter:s,convInfo:g,backend:n,bias:i,activation:c,preluActivationWeights:o,leakyreluAlpha:m});else if(se().getBool("WEBGL_CONV_IM2COL")&&r.shape[0]===1)y=jE({x:r,filter:s,convInfo:g,backend:n,bias:i,activation:c,preluActivationWeights:o,leakyreluAlpha:m});else{let v=i!=null,b=o!=null,w=c==="leakyrelu",I=c?j0(c,!1):null,T=new VE(g,v,I,b,w),C=[r,s];if(i&&C.push(i),o&&C.push(o),w){let z=n.makeTensorInfo([],"float32",k.createScalarValue(m,"float32"));C.push(z),A.push(z)}y=n.runWebGLProgram(T,C,"float32")}let x=be({inputs:{x:y},backend:n,attrs:{shape:g.outShape}});return A.push(y),A.forEach(v=>n.disposeIntermediateTensorInfo(v)),x}var Hge={kernelName:Wl,backendName:"webgl",kernelFunc:jge};function Gge(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:d,dimRoundingMode:h,activation:p,leakyreluAlpha:c}=a,m=[],f=d;f==null&&(f=[1,1]),k.assert(M.eitherStridesOrDilationsAreOne(l,f),()=>`Error in depthwiseConv2d: Either strides or dilations must be 1. Got strides ${l} and dilations '${f}'`);let g=M.computeConv2DInfo(r.shape,s.shape,l,f,u,h,!0),y=se().getBool("WEBGL_PACK_DEPTHWISECONV")&&g.strideWidth<=2&&g.outChannels/g.inChannels==1,A=p?j0(p,y):null,x=[r,s],v=i!=null,b=o!=null,w=p==="leakyrelu";if(v&&x.push(i),b&&x.push(o),w){let C=n.makeTensorInfo([],"float32",k.createScalarValue(c,"float32"));x.push(C),m.push(C)}let I;y?I=new XE(g,v,A,b,w):I=new KE(g,v,A,b,w);let T=n.runWebGLProgram(I,x,"float32");return m.forEach(C=>n.disposeIntermediateTensorInfo(C)),T}var qge={kernelName:Bl,backendName:"webgl",kernelFunc:Gge},Kge=class{constructor(e,t,n){this.sliceDim=e,this.strides=t,this.variableNames=["x","indices"],this.outputShape=n;let a=kt(t.length),r=kt(n.length),s=this.sliceDim>1?"strides[j]":"strides";this.userCode=` ${a} strides = ${a}(${this.strides}); void main() { ${r} coords = getOutputCoords(); int flattenIndex = 0; for (int j = 0; j < ${this.sliceDim}; j++) { int index = round(getIndices(coords[0], j)); flattenIndex += index * ${s}; } setOutput(getX(flattenIndex, coords[1])); } `}};function Xge(e){let{inputs:t,backend:n}=e,{params:a,indices:r}=t,s=r.shape,i=s[s.length-1],o=k.sizeFromShape(a.shape),[l,u,d,h]=M.prepareAndValidate(a,r),p=be({inputs:{x:r},backend:n,attrs:{shape:[u,i]}}),c=be({inputs:{x:a},backend:n,attrs:{shape:[k.sizeFromShape(a.shape)/d,d]}});if(n.shouldExecuteOnCPU([a,r])||a.dtype==="string"){let y=n.readSync(r.dataId),A=n.bufferSync(a),x=dce(y,A,a.dtype,u,i,d,h,a.shape,o);return n.makeTensorInfo(l,a.dtype,x.values)}let m=new Kge(i,h,[u,d]),f=n.runWebGLProgram(m,[c,p],c.dtype),g=be({inputs:{x:f},backend:n,attrs:{shape:l}});return n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(f),g}var Zge={kernelName:Pd,backendName:"webgl",kernelFunc:Xge},Yge=class{constructor(e,t){this.variableNames=["A","indices"],this.outputShape=t,this.rank=t.length;let n=kt(this.rank),a=Jge(e,2);this.userCode=` void main() { ${n} resRC = getOutputCoords(); setOutput(getA(${a})); } `}};function Jge(e,t){let n=["resRC.x","resRC.y","resRC.z","resRC.w"],a=[];for(let r=0;rn.disposeIntermediateTensorInfo(b)),n.makeTensorInfo(u.outputShape,v.dtype,v.values)}let f=new Yge(p.shape,m),g=n.runWebGLProgram(f,[p,c],p.dtype);h.push(g);let y=be({inputs:{x:g},backend:n,attrs:{shape:u.outputShape}});return h.forEach(A=>n.disposeIntermediateTensorInfo(A)),y}var eye={kernelName:zd,backendName:"webgl",kernelFunc:Qge},tye="return float(a > b);",nye=` return vec4(greaterThan(a, b)); `,aye=Tn({opSnippet:tye,packedOpSnippet:nye,cpuKernelImpl:pce,dtype:"bool"}),rye={kernelName:hl,backendName:"webgl",kernelFunc:aye},sye="return float(a >= b);",iye=` return vec4(greaterThanEqual(a, b)); `,oye=Tn({opSnippet:sye,packedOpSnippet:iye,dtype:"bool",cpuKernelImpl:cce}),lye={kernelName:Mi,backendName:"webgl",kernelFunc:oye};function uye(e){let{inputs:t,backend:n}=e,{input:a}=t;return eC(a,!0,n)}var dye={kernelName:z1,backendName:"webgl",kernelFunc:uye},hye="return float(!isnan(x) && !isinf(x));",pye=ot({opSnippet:hye,dtype:"bool"}),cye={kernelName:Ld,backendName:"webgl",kernelFunc:pye},fye="return float(isinf(x));",mye=ot({opSnippet:fye,dtype:"bool"}),gye={kernelName:Wd,backendName:"webgl",kernelFunc:mye},yye="return float(isnan(x));",Aye=ot({opSnippet:yye,dtype:"bool"}),xye={kernelName:Bd,backendName:"webgl",kernelFunc:Aye},bye="return float(a < b);",vye=` return vec4(lessThan(a, b)); `,wye=Tn({opSnippet:bye,packedOpSnippet:vye,cpuKernelImpl:fce,dtype:"bool"}),kye={kernelName:fl,backendName:"webgl",kernelFunc:wye},Iye="return float(a <= b);",Sye=` return vec4(lessThanEqual(a, b)); `,Nye=Tn({opSnippet:Iye,packedOpSnippet:Sye,cpuKernelImpl:mce,dtype:"bool"}),Tye={kernelName:ml,backendName:"webgl",kernelFunc:Nye};function Eye(e){let{backend:t,attrs:n}=e,{start:a,stop:r,num:s}=n,i=gce(a,r,s);return t.makeTensorInfo([i.length],"float32",i)}var Cye={kernelName:L1,backendName:"webgl",kernelFunc:Eye},Mye=`if (x < 0.0) return NAN; return log(x);`,$ye=` vec4 result = log(x); vec4 isNaN = vec4(lessThan(x, vec4(0.0))); result.r = isNaN.r == 1.0 ? NAN : result.r; result.g = isNaN.g == 1.0 ? NAN : result.g; result.b = isNaN.b == 1.0 ? NAN : result.b; result.a = isNaN.a == 1.0 ? NAN : result.a; return result; `,Rye=ot({opSnippet:Mye,packedOpSnippet:$ye,cpuKernelImpl:yce}),Fye={kernelName:$i,backendName:"webgl",kernelFunc:Rye},Oye="return log(1.0 + x);",Dye=ot({opSnippet:Oye}),_ye={kernelName:Vd,backendName:"webgl",kernelFunc:Dye},zye="return float(a >= 1.0 && b >= 1.0);",Pye=` return vec4( vec4(greaterThanEqual(a, vec4(1.0))) * vec4(greaterThanEqual(b, vec4(1.0)))); `,Lye=Tn({opSnippet:zye,packedOpSnippet:Pye,dtype:"bool"}),Wye={kernelName:Ud,backendName:"webgl",kernelFunc:Lye},Bye="return float(!(x >= 1.0));",Vye=ot({opSnippet:Bye}),Uye={kernelName:ef,backendName:"webgl",kernelFunc:Vye},jye="return float(a >= 1.0 || b >= 1.0);",Hye=` return min( vec4(greaterThanEqual(a, vec4(1.0))) + vec4(greaterThanEqual(b, vec4(1.0))), vec4(1.0)); `,Gye=Tn({opSnippet:jye,packedOpSnippet:Hye,dtype:"bool"}),qye={kernelName:tf,backendName:"webgl",kernelFunc:Gye},Kye=class{constructor(e,t,n,a,r){this.variableNames=["x"],this.outputShape=[];let s=t,i=e[3]-1;this.outputShape=e;let o,l=`float(${n}) + float(${a}) * sum`;r===.5?o=`inversesqrt(${l})`:r===1?o=`1.0/(${l})`:o=`exp(log(${l}) * float(-${r}));`,this.userCode=` void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; int r = coords[1]; int c = coords[2]; int d = coords[3]; float x = getX(b, r, c, d); float sum = 0.0; for (int j = -${s}; j <= ${s}; j++) { int idx = d + j; if (idx >= 0 && idx <= ${i}) { float z = getX(b, r, c, idx); sum += z * z; } } float val = x * ${o}; setOutput(val); } `}},Xye=class{constructor(e,t,n,a,r){this.variableNames=["x"],this.outputShape=[],this.packedInputs=!0,this.packedOutput=!0;let s=t,i=e[3]-1;this.outputShape=e;let o,l=`float(${n}) + float(${a}) * sum`;r===.5?o=`inversesqrt(${l})`:r===1?o=`1.0/(${l})`:o=`exp(log(${l}) * float(-${r}));`,this.userCode=` void main() { ivec4 coords = getOutputCoords(); int b = coords.x; int r = coords.y; int c = coords.z; int d = coords.w; bool hasNextCol = d < ${this.outputShape[3]}; bool hasNextRow = c < ${this.outputShape[2]}; vec4 sum = vec4(0.); vec4 xFragAtOutputCoords = getX(b, r, c, d); vec4 xAtOutputCoords = vec4( getChannel(xFragAtOutputCoords, vec2(c, d)), hasNextCol ? getChannel(xFragAtOutputCoords, vec2(c, d + 1)) : 0.0, hasNextRow ? getChannel(xFragAtOutputCoords , vec2(c + 1, d)) : 0.0, (hasNextRow && hasNextCol) ? getChannel(xFragAtOutputCoords, vec2(c + 1, d + 1)) : 0.0 ); int firstChannel = d - ${s}; vec2 cache = vec2(0.); if(firstChannel >= 0){ vec4 firstChannelFrag = getX(b, r, c, firstChannel); cache.x = getChannel(firstChannelFrag, vec2(c, firstChannel)); if(hasNextRow){ cache.y = getChannel(firstChannelFrag, vec2(c + 1, firstChannel)); } } ivec2 depth = ivec2(d, d + 1); for (int j = - ${s}; j <= ${s}; j++) { ivec2 idx = depth + j; bvec2 aboveLowerBound = greaterThanEqual(idx, ivec2(0)); bvec2 belowUpperBound = lessThanEqual(idx, ivec2(${i})); bool depthInRange = aboveLowerBound.x && belowUpperBound.x; bool depthPlusOneInRange = aboveLowerBound.y && belowUpperBound.y; if(depthInRange || depthPlusOneInRange){ vec4 z = vec4(0.); vec4 xFragAtCurrentDepth; z.xz = cache.xy; if(depthPlusOneInRange && hasNextCol){ xFragAtCurrentDepth = idx.y != d ? getX(b, r, c, idx.y) : xFragAtOutputCoords; z.y = getChannel(xFragAtCurrentDepth, vec2(c, idx.y)); if(hasNextRow){ z.w = getChannel(xFragAtCurrentDepth, vec2(c + 1, idx.y)); } } cache.xy = z.yw; sum += z * z; } } vec4 result = xAtOutputCoords * ${o}; setOutput(result); } `}},Zye=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{depthRadius:s,bias:i,alpha:o,beta:l}=a,u=se().getBool("WEBGL_PACK_NORMALIZATION")?new Xye(r.shape,s,i,o,l):new Kye(r.shape,s,i,o,l);return n.runWebGLProgram(u,[r],r.dtype)},Yye={kernelName:nf,backendName:"webgl",kernelFunc:Zye},Jye=class{constructor(e,t,n,a,r){this.variableNames=["inputImage","outputImage","dy"],this.outputShape=[],this.outputShape=e,this.depth=e[3],this.depthRadius=t,this.bias=n,this.alpha=a,this.beta=r,this.userCode=` void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; int r = coords[1]; int c = coords[2]; float result = 0.0; for (int d = 0; d < ${this.depth}; ++d) { int depthBegin = int(max(0.0, float(d - ${t}))); int depthEnd = int(min(float(${this.depth}), float(d + ${t} + 1))); const int MIN_DEPTH_BEGIN = 0; const int MAX_DEPTH_END = ${this.depth}; float norm = 0.0; for (int k = MIN_DEPTH_BEGIN; k < MAX_DEPTH_END; ++k) { if (k < depthBegin){ continue; } else if (k >= depthBegin && k < depthEnd) { norm += getInputImage(b, r, c, k) * getInputImage(b, r, c, k); } else { break; } } norm = float(${a}) * 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(${a}) * float(${r}) * getInputImage(b ,r ,c, k) * getOutputImage(b, r, c, d) / norm; if (k == d) { dyi += pow(norm, -1.0 * ${r}); } if (k == coords[3]) { dyi *= getDy(b, r, c, d); result += dyi; } } else { break; } } } setOutput(result); } `}},Qye=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r,y:s,dy:i}=t,{depthRadius:o,bias:l,alpha:u,beta:d}=a,h=new Jye(r.shape,o,l,u,d);return n.runWebGLProgram(h,[r,s,i],r.dtype)},e1e={kernelName:W1,backendName:"webgl",kernelFunc:Qye};function t1e(e,t,n,a){let r=k.sizeFromShape(t),s=k.sizeFromShape(e.shape)/r,i=be({inputs:{x:e},attrs:{shape:[s,r]},backend:a}),o=bo(i,e.dtype,"max",a),l=be({inputs:{x:o},attrs:{shape:n},backend:a});return a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(o),l}function nC(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{reductionIndices:s,keepDims:i}=a,o=r.shape.length,l=k.parseAxisParam(s,r.shape),u=l,d=M.getAxesPermutation(u,o),h=d!=null,p=n.shouldExecuteOnCPU([r]),c=r;if(h){if(p){let A=n.texData.get(c.dataId).values,x=new Array(o);for(let w=0;w`Error in maxPool: Either strides or dilations must be 1. Got strides ${i} and dilations '${u}'`);let d=M.computePool2DInfo(r.shape,s,i,u,o,l);if(d.filterWidth===1&&d.filterHeight===1&&k.arraysEqual(d.inShape,d.outShape))return fa({inputs:{x:r},backend:n});let h=new cp(d,"max",!1);return n.runWebGLProgram(h,[r],r.dtype)}var l1e={kernelName:yl,backendName:"webgl",kernelFunc:o1e};function u1e(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{filterSize:s,strides:i,pad:o,dataFormat:l,dimRoundingMode:u}=a,d=[1,1,1],h=M.computePool3DInfo(r.shape,s,i,d,o,u,l),p=new ub(h,"max",!1);return n.runWebGLProgram(p,[r],r.dtype)}var d1e={kernelName:af,backendName:"webgl",kernelFunc:u1e},h1e=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideHeight,n=e.strideWidth,a=e.dilationHeight,r=e.effectiveFilterHeight,s=e.effectiveFilterWidth,i=r-1-e.padInfo.top,o=s-1-e.padInfo.left,l=r*s-1;this.userCode=` const ivec2 pads = ivec2(${i}, ${o}); void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; int d = coords[3]; ivec2 dyRCCorner = coords.yz - pads; int dyRCorner = dyRCCorner.x; int dyCCorner = dyRCCorner.y; // Convolve dy(?, ?, d) with pos mask(:, :, d) to get dx(xR, xC, d). // ? = to be determined. : = across all values in that axis. float dotProd = 0.0; for (int wR = 0; wR < ${r}; wR += ${a}) { float dyR = float(dyRCorner + wR) / ${t}.0; if (dyR < 0.0 || dyR >= ${e.outHeight}.0 || fract(dyR) > 0.0) { continue; } int idyR = int(dyR); for (int wC = 0; wC < ${s}; wC++) { float dyC = float(dyCCorner + wC) / ${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 * ${s} + wC; float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0); dotProd += dyValue * mask; } } setOutput(dotProd); } `}},p1e=class{constructor(e){this.variableNames=["dy","maxPos"],this.outputShape=e.inShape;let t=e.strideDepth,n=e.strideHeight,a=e.strideWidth,r=e.dilationDepth,s=e.dilationHeight,i=e.dilationWidth,o=e.effectiveFilterDepth,l=e.effectiveFilterHeight,u=e.effectiveFilterWidth,d=o-1-e.padInfo.front,h=l-1-e.padInfo.top,p=u-1-e.padInfo.left,c=o*l*u-1;this.userCode=` const ivec3 pads = ivec3(${d}, ${h}, ${p}); void main() { ivec5 coords = getOutputCoords(); int batch = coords.x; int ch = coords.u; ivec3 dyCorner = ivec3(coords.y, coords.z, coords.w) - pads; int dyDCorner = dyCorner.x; int dyRCorner = dyCorner.y; int dyCCorner = dyCorner.z; // Convolve dy(?, ?, ?, ch) with pos mask(:, :, :, d) to get // dx(xD, xR, xC, ch). // ? = to be determined. : = across all values in that axis. float dotProd = 0.0; for (int wD = 0; wD < ${o}; wD += ${r}) { float dyD = float(dyDCorner + wD) / ${t}.0; if (dyD < 0.0 || dyD >= ${e.outDepth}.0 || fract(dyD) > 0.0) { continue; } int idyD = int(dyD); for (int wR = 0; wR < ${l}; wR += ${s}) { float dyR = float(dyRCorner + wR) / ${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 += ${i}) { float dyC = float(dyCCorner + wC) / ${a}.0; if (dyC < 0.0 || dyC >= ${e.outWidth}.0 || fract(dyC) > 0.0) { continue; } int idyC = int(dyC); float dyValue = getDy(batch, idyD, idyR, idyC, ch); int maxPosValue = ${c} - int(getMaxPos(batch, idyD, idyR, idyC, ch)); // Get the current value, check it against the value from the // position matrix. int curPosValue = wD * ${l} * ${u} + wR * ${u} + wC; float mask = float(maxPosValue == curPosValue ? 1.0 : 0.0); dotProd += dyValue * mask; } } } setOutput(dotProd); } `}};function c1e(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s}=t,i=s,{filterSize:o,strides:l,pad:u,dimRoundingMode:d}=a,h=[1,1,1],p=M.computePool3DInfo(i.shape,o,l,h,u,d),c=new ub(p,"max",!0),m=n.runWebGLProgram(c,[i],i.dtype),f=new p1e(p),g=n.runWebGLProgram(f,[r,m],i.dtype);return n.disposeIntermediateTensorInfo(m),g}var f1e={kernelName:V1,backendName:"webgl",kernelFunc:c1e};function m1e(e){let{inputs:t,backend:n,attrs:a}=e,{dy:r,input:s,output:i}=t,o=s;mu([s,i],"maxPoolGrad");let{filterSize:l,strides:u,pad:d,dimRoundingMode:h}=a,p=M.computePool2DInfo(o.shape,l,u,1,d,h),c=!0,m=new cp(p,"max",c),f=n.runWebGLProgram(m,[o],o.dtype),g=new h1e(p),y=n.runWebGLProgram(g,[r,f],o.dtype);return n.disposeIntermediateTensorInfo(f),y}var g1e={kernelName:B1,backendName:"webgl",kernelFunc:m1e};function y1e(e,t,n,a){let r=new cp(n,"max",!1),s=a.runWebGLProgram(r,[e],"float32");r=new cp(n,"max",!0,!0,t);let i=a.runWebGLProgram(r,[e],"float32");return[s,i]}var A1e={kernelName:U1,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:a}=e,{filterSize:r,strides:s,pad:i,includeBatchInIndex:o}=t,l=n;k.assert(a.shape.length===4,()=>`Error in maxPool: input must be rank 4 but got rank ${a.shape.length}.`);let u=[1,1];k.assert(M.eitherStridesOrDilationsAreOne(s,u),()=>`Error in maxPool: Either strides or dilations must be 1. Got strides ${s} and dilations '${u}'`);let d=M.computePool2DInfo(a.shape,r,s,u,i),[h,p]=y1e(a,o,d,l);return[h,p]}};function x1e(e,t,n,a){let r=k.sizeFromShape(t),s=k.sizeFromShape(e.shape)/r,i=be({inputs:{x:e},attrs:{shape:[s,r]},backend:a}),o=bo(i,"float32","mean",a),l=be({inputs:{x:o},attrs:{shape:n},backend:a});return a.disposeIntermediateTensorInfo(i),a.disposeIntermediateTensorInfo(o),l}var b1e={kernelName:Al,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{x:a}=e,{keepDims:r,axis:s}=t,i=n,o=a.shape.length,l=k.parseAxisParam(s,a.shape),u=l,d=M.getAxesPermutation(u,o),h=d!=null,p=i.shouldExecuteOnCPU([a]),c=[],m=a;if(h){if(p){let x=i.texData.get(m.dataId).values,v=new Array(o);for(let I=0;Iu[0]+e[d]+u[1]);let a=e.length,r=kt(a),s=t.map(u=>u[0]).join(","),i=t.map((u,d)=>u[0]+e[d]).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,a),l=n==="reflect"?0:1;if(a===1){this.userCode=` int start = ${s}; int end = ${i}; void main() { int outC = getOutputCoords(); if (outC < start) { outC = start * 2 - outC - ${l}; } else if(outC >= end) { outC = (end - 1) * 2 - outC + ${l}; } setOutput(getX(outC - start)); } `;return}this.userCode=` ${r} start = ${r}(${s}); ${r} end = ${r}(${i}); void main() { ${r} outC = getOutputCoords(); for (int i = 0; i < ${a}; i++) { if (outC[i] < start[i]) { outC[i] = start[i] * 2 - outC[i] - ${l}; } else if(outC[i] >= end[i]) { outC[i] = (end[i] - 1) * 2 - outC[i] + ${l}; } } ${r} coords = outC - start; setOutput(getX(${o})); } `}},E1e=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((c,m)=>c[0]+e[m]+c[1]);let a=e.length,r=kt(a),s=t.map(c=>c[0]).join(","),i=t.map((c,m)=>c[0]+e[m]).join(","),o=Bn("rc",a),l=Bn("source",a),u=`${o[a-1]} < ${this.outputShape[a-1]}`,d=a===1?"source":`vec2(${l.slice(-2).join()})`,h=n==="reflect"?0:1,p="";if(a===1){let c=` ${r} source = rc; if (source < start) { source = start * 2 - source - ${h}; } else if (source >= end) { source = (end - 1) * 2 - source + ${h}; } source -= start; `;p=` ${r} rc = outputLoc; ${c} result[0] = getChannel(getX(${l.join()}), ${d}); ${o[a-1]} += 1; if(${u}) { ${c} result[1] = getChannel(getX(${l.join()}), ${d}); } `}else{let c=` ${r} source = rc; ${r} lt = ${r}(lessThan(source, start)); ${r} gte = ${r}(greaterThanEqual(source, end)); ${r} orig = 1 - (lt + gte); source = orig * source + lt * (start * 2 - source - ${h}) + gte * ((end - 1) * 2 - source + ${h}); source -= start; `;p=` ${r} rc = outputLoc; ${c} result[0] = getChannel(getX(${l.join()}), ${d}); ${o[a-1]} += 1; if(${u}) { ${c} result[1] = getChannel(getX(${l.join()}), ${d}); } rc = outputLoc; ${o[a-2]} += 1; if(${o[a-2]} < ${this.outputShape[a-2]}) { ${c} result[2] = getChannel(getX(${l.join()}), ${d}); ${o[a-1]} += 1; if(${u}) { ${c} result[3] = getChannel(getX(${l.join()}), ${d}); } } `}this.userCode=` const ${r} start = ${r}(${s}); const ${r} end = ${r}(${i}); void main() { ${r} outputLoc = getOutputCoords(); vec4 result = vec4(0.); ${p} setOutput(result); } `}},C1e=({inputs:e,backend:t,attrs:n})=>{let{x:a}=e,{paddings:r,mode:s}=n,i=se().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new E1e(a.shape,r,s):new T1e(a.shape,r,s);return t.runWebGLProgram(i,[a],a.dtype)},M1e={kernelName:bl,backendName:"webgl",kernelFunc:C1e},$1e=`if (b == 0.0) return NAN; return mod(a, b);`,R1e=` vec4 result = mod(a, b); vec4 isNaN = vec4(equal(b, vec4(0.0))); `+U0+` return result; `,F1e=Tn({opSnippet:$1e,packedOpSnippet:R1e}),O1e={kernelName:jd,backendName:"webgl",kernelFunc:F1e},D1e=class{constructor(e,t,n){this.variableNames=["probs"],this.outputShape=[e,n],this.userCode=` uniform float seed; 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})); } `}getCustomSetupFunc(e){return(t,n)=>{this.seedLoc==null&&(this.seedLoc=t.getUniformLocation(n,"seed")),t.gl.uniform1f(this.seedLoc,e)}}},_1e=` if (a == b) { return 1.0; }; return a / b;`,z1e=` // 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; `,aC=Tn({opSnippet:_1e,packedOpSnippet:z1e,checkOutOfBounds:!0}),P1e={kernelName:il,backendName:"webgl",kernelFunc:aC},rC="return a - b;",sC=Tn({opSnippet:rC,packedOpSnippet:rC,supportsComplex:!0,cpuKernelImpl:Oce}),L1e={kernelName:zi,backendName:"webgl",kernelFunc:sC};function iC(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{dim:s}=a,i=k.parseAxisParam([s],r.shape),o=nC({inputs:{x:r},backend:n,attrs:{reductionIndices:i,keepDims:!1}}),l=M.expandShapeToKeepDim(o.shape,i),u=be({inputs:{x:o},backend:n,attrs:{shape:l}}),d=sC({inputs:{a:r,b:u},backend:n}),h=YE({inputs:{x:d},backend:n}),p=G0({inputs:{x:h},backend:n,attrs:{axis:i,keepDims:!1}}),c=be({inputs:{x:p},backend:n,attrs:{shape:l}}),m=aC({inputs:{a:h,b:c},backend:n});return n.disposeIntermediateTensorInfo(o),n.disposeIntermediateTensorInfo(u),n.disposeIntermediateTensorInfo(d),n.disposeIntermediateTensorInfo(h),n.disposeIntermediateTensorInfo(p),n.disposeIntermediateTensorInfo(c),m}var W1e={kernelName:Dl,backendName:"webgl",kernelFunc:iC};function B1e(e){let{inputs:t,backend:n,attrs:a}=e,{logits:r}=t,{numSamples:s,seed:i,normalized:o}=a,l=o?r:iC({inputs:{logits:r},backend:n,attrs:{dim:r.shape.length-1}}),u=l.shape[0],d=l.shape[1],h=new D1e(u,d,s),p=h.getCustomSetupFunc(i),c=n.runWebGLProgram(h,[l],"int32",p);return o||n.disposeIntermediateTensorInfo(l),c}var V1e={kernelName:j1,backendName:"webgl",kernelFunc:B1e},oC="return -x;";function U1e(e){let{inputs:t,backend:n}=e,{x:a}=t;if(n.shouldExecuteOnCPU([a])){let s=n.texData.get(a.dataId),[i,o]=wce(s.values,a.shape,a.dtype);return n.makeTensorInfo(o,a.dtype,i)}let r;return se().getBool("WEBGL_PACK_UNARY_OPERATIONS")?r=new wu(a.shape,oC):r=new Qs(a.shape,oC),n.runWebGLProgram(r,[a],a.dtype)}var j1e={kernelName:Hd,backendName:"webgl",kernelFunc:U1e},H1e=us.nonMaxSuppressionV3Impl;function G1e(e){M.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l}=a,u=n.readSync(r.dataId),d=n.readSync(s.dataId),{selectedIndices:h}=H1e(u,d,i,o,l);return n.makeTensorInfo([h.length],"int32",new Int32Array(h))}var q1e={kernelName:Gd,backendName:"webgl",kernelFunc:G1e},K1e=us.nonMaxSuppressionV4Impl;function X1e(e){M.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,padToMaxOutputSize:u}=a,d=n.readSync(r.dataId),h=n.readSync(s.dataId),{selectedIndices:p,validOutputs:c}=K1e(d,h,i,o,l,u);return[n.makeTensorInfo([p.length],"int32",new Int32Array(p)),n.makeTensorInfo([],"int32",new Int32Array([c]))]}var Z1e={kernelName:qd,backendName:"webgl",kernelFunc:X1e},Y1e=us.nonMaxSuppressionV5Impl;function J1e(e){M.warn("tf.nonMaxSuppression() in webgl locks the UI thread. Call tf.nonMaxSuppressionAsync() instead");let{inputs:t,backend:n,attrs:a}=e,{boxes:r,scores:s}=t,{maxOutputSize:i,iouThreshold:o,scoreThreshold:l,softNmsSigma:u}=a,d=n.readSync(r.dataId),h=n.readSync(s.dataId),p=i,c=o,m=l,f=u,{selectedIndices:g,selectedScores:y}=Y1e(d,h,p,c,m,f);return[n.makeTensorInfo([g.length],"int32",new Int32Array(g)),n.makeTensorInfo([y.length],"float32",new Float32Array(y))]}var Q1e={kernelName:Kd,backendName:"webgl",kernelFunc:J1e},eAe=class{constructor(e,t,n,a){this.variableNames=["indices"],this.outputShape=[e,t],this.userCode=` void main() { ivec2 coords = getOutputCoords(); int index = round(getIndices(coords.x)); setOutput(mix(float(${a}), float(${n}), float(index == coords.y))); } `}},tAe=e=>{let{inputs:t,backend:n,attrs:a}=e,{indices:r}=t,{depth:s,onValue:i,offValue:o}=a,l=k.sizeFromShape(r.shape),u=new eAe(l,s,i,o),d=be({inputs:{x:r},backend:n,attrs:{shape:[l]}}),h=n.runWebGLProgram(u,[d],r.dtype);n.disposeIntermediateTensorInfo(d);let p=[...r.shape,s],c=be({inputs:{x:h},backend:n,attrs:{shape:p}});return n.disposeIntermediateTensorInfo(h),c},nAe={kernelName:wl,backendName:"webgl",kernelFunc:tAe};function Y0(e){let{inputs:t,backend:n}=e,{x:a}=t;if(a.dtype==="complex64"){let r=mp({inputs:{input:a},backend:n}),s=Y0({inputs:{x:r},backend:n}),i=Z0({inputs:{input:a},backend:n}),o=Y0({inputs:{x:i},backend:n}),l=ei({inputs:{real:s,imag:o},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}else return cb({attrs:{shape:a.shape,dtype:a.dtype,value:a.dtype==="string"?"":0},backend:n})}var aAe={kernelName:ph,backendName:"webgl",kernelFunc:Y0};function lC(e){let{inputs:t,backend:n}=e,{x:a}=t;if(a.dtype==="string")throw new Error("onesLike is not supported under string dtype");if(a.dtype==="complex64"){let r=mp({inputs:{input:a},backend:n}),s=lC({inputs:{x:r},backend:n}),i=Z0({inputs:{input:a},backend:n}),o=Y0({inputs:{x:i},backend:n}),l=ei({inputs:{real:s,imag:o},backend:n});return n.disposeIntermediateTensorInfo(r),n.disposeIntermediateTensorInfo(s),n.disposeIntermediateTensorInfo(i),n.disposeIntermediateTensorInfo(o),l}else return cb({attrs:{shape:a.shape,dtype:a.dtype,value:1},backend:n})}var rAe={kernelName:Xd,backendName:"webgl",kernelFunc:lC};function sAe(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a;if(t.length===1)return pb({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let s=t[0].shape,i=t[0].dtype;t.forEach(d=>{k.assertShapesMatch(s,d.shape,"All tensors passed to stack must have matching shapes"),k.assert(i===d.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(d=>{let h=pb({inputs:{input:d},backend:n,attrs:{dim:r}});return o.push(h),h}),u=BE({inputs:l,backend:n,attrs:{axis:r}});return o.forEach(d=>n.disposeIntermediateTensorInfo(d)),u}var iAe={kernelName:Zd,backendName:"webgl",kernelFunc:sAe},oAe=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=t.map((l,u)=>l[0]+e[u]+l[1]);let a=e.length,r=kt(a),s=t.map(l=>l[0]).join(","),i=t.map((l,u)=>l[0]+e[u]).join(","),o=["coords[0]","coords[1]","coords[2]","coords[3]"].slice(0,a);if(a===1){this.userCode=` int start = ${s}; int end = ${i}; uniform float value; void main() { int outC = getOutputCoords(); if (outC < start || outC >= end) { setOutput(value); } else { setOutput(getX(outC - start)); } } `;return}this.userCode=` ${r} start = ${r}(${s}); ${r} end = ${r}(${i}); uniform float value; void main() { ${r} outC = getOutputCoords(); if (any(lessThan(outC, start)) || any(greaterThanEqual(outC, end))) { setOutput(value); } else { ${r} coords = outC - start; setOutput(getX(${o})); } } `}getCustomSetupFunc(e){return(t,n)=>{this.valueLoc==null&&(this.valueLoc=t.getUniformLocationNoThrow(n,"value")),t.gl.uniform1f(this.valueLoc,e)}}},lAe=class{constructor(e,t,n){this.variableNames=["x"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=t.map((m,f)=>m[0]+e[f]+m[1]);let a=e.length,r=kt(a),s=t.map(m=>m[0]).join(","),i=t.map((m,f)=>m[0]+e[f]).join(","),o=Bn("rc",a),l=Bn("source",a),u=`${o[a-1]} < ${this.outputShape[a-1]}`,d=a===1?"source":`vec2(${l.slice(-2).join()})`,h=[`${r} rc = outputLoc;`,`${o[a-1]} += 1; if(${u}) { `,a===1?"":`} rc = outputLoc; ${o[a-2]} += 1; if(${o[a-2]} < ${this.outputShape[a-2]}) {`,a===1?"":` ${o[a-1]} += 1; if(${u}) {`],p=a===1?"rc < start || rc >= end":"any(lessThan(rc, start)) || any(greaterThanEqual(rc, end))",c="";for(let m=0,f=a===1?2:4;m{this.valueLoc==null&&(this.valueLoc=t.getUniformLocationNoThrow(n,"value")),t.gl.uniform1f(this.valueLoc,e)}}},uC=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{paddings:s,constantValue:i}=a,o=se().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new lAe(r.shape,s,i):new oAe(r.shape,s,i),l=o.getCustomSetupFunc(i);return n.runWebGLProgram(o,[r],r.dtype,l)},uAe={kernelName:kl,backendName:"webgl",kernelFunc:uC},dAe=` 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); `,hAe=` // 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)); `+U0+` return result; `,pAe=Tn({opSnippet:dAe,packedOpSnippet:hAe}),cAe={kernelName:Il,backendName:"webgl",kernelFunc:pAe};function fAe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{axis:s,keepDims:i}=a,o=r.shape.length,l=[],u=k.parseAxisParam(s,r.shape),d=u,h=M.getAxesPermutation(d,o),p=r;h!=null&&(p=Vn({inputs:{x:r},backend:n,attrs:{perm:h}}),d=M.getInnerMostAxes(d.length,o),l.push(p)),M.assertAxesAreInnerMostDims("prod",d,o);let c;if(n.shouldExecuteOnCPU([p])){let m=n.texData.get(p.dataId).values,{outVals:f,outShape:g,outDtype:y}=Ice(p.shape,p.dtype,m,d);c=n.makeTensorInfo(g,y,f)}else{let[m,f]=M.computeOutAndReduceShapes(p.shape,d),g=k.sizeFromShape(f),y=be({inputs:{x:p},backend:n,attrs:{shape:[-1,g]}}),A=cA(r.dtype),x=bo(y,A,"prod",n);c=be({inputs:{x},backend:n,attrs:{shape:m}}),l.push(y),l.push(x)}if(i){l.push(c);let m=M.expandShapeToKeepDim(c.shape,u);c=be({inputs:{x:c},backend:n,attrs:{shape:m}})}return l.forEach(m=>n.disposeIntermediateTensorInfo(m)),c}var mAe={kernelName:Yd,backendName:"webgl",kernelFunc:fAe},dC=e=>{let{backend:t,attrs:n}=e,{start:a,stop:r,step:s,dtype:i}=n,o=Sce(a,r,s,i);return t.makeTensorInfo([o.length],i,o)},gAe={kernelName:rf,backendName:"webgl",kernelFunc:dC},yAe="return 1.0 / x;",AAe=ot({opSnippet:yAe}),xAe={kernelName:Jd,backendName:"webgl",kernelFunc:AAe},bAe=gr+` return (x < 0.0) ? 0.0 : x; `,vAe=` 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; `,wAe=ot({opSnippet:bAe,packedOpSnippet:vAe}),kAe={kernelName:Nl,backendName:"webgl",kernelFunc:wAe},IAe=gr+` return (x < 0.0) ? 0.0 : min(6.0, x); `,SAe=` 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; `,NAe=ot({opSnippet:IAe,packedOpSnippet:SAe}),TAe={kernelName:El,backendName:"webgl",kernelFunc:NAe},EAe=class{constructor(e,t,n,a,r){this.variableNames=["A"],this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,n,l];let u=[a&&t>1?i-1:i,a&&n>1?o-1:o],d=[a&&t>1?t-1:t,a&&n>1?n-1:n],h;r?h="(vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC - vec2(0.5)":h="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` const vec2 effectiveInputOverOutputRatioRC = vec2( ${u[0]/d[0]}, ${u[1]/d[1]}); const vec2 inputShapeRC = vec2(${i}.0, ${o}.0); void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; int d = coords[3]; ivec2 yRC = coords.yz; // Fractional source index. vec2 sourceFracIndexRC = ${h}; // Compute the four integer indices. ivec2 sourceFloorRC = ivec2(max(sourceFracIndexRC, vec2(0.0))); ivec2 sourceCeilRC = ivec2( min(inputShapeRC - 1.0, ceil(sourceFracIndexRC))); float topLeft = getA(b, sourceFloorRC.x, sourceFloorRC.y, d); float bottomLeft = getA(b, sourceCeilRC.x, sourceFloorRC.y, d); float topRight = getA(b, sourceFloorRC.x, sourceCeilRC.y, d); float bottomRight = getA(b, sourceCeilRC.x, sourceCeilRC.y, d); vec2 fracRC = sourceFracIndexRC - vec2(sourceFloorRC); float top = topLeft + (topRight - topLeft) * fracRC.y; float bottom = bottomLeft + (bottomRight - bottomLeft) * fracRC.y; float newValue = top + (bottom - top) * fracRC.x; setOutput(newValue); } `}},CAe=class{constructor(e,t,n,a,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,n,l];let u=[a&&t>1?i-1:i,a&&n>1?o-1:o],d=[a&&t>1?t-1:t,a&&n>1?n-1:n],h;r?h="(vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC - vec3(0.5)":h="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` const vec3 effectiveInputOverOutputRatioRC = vec3( ${u[0]/d[0]}, ${u[1]/d[1]}, ${u[1]/d[1]}); const vec3 inputShapeRC = vec3(${i}.0, ${o}.0, ${o}.0); float getAValue(int b, int r, int c, int d) { return getChannel(getA(b, r, c, d), vec2(c, d)); } void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; int d = coords[3]; // Calculate values for next column in yRC.z. ivec3 yRC = coords.yzz + ivec3(0, 0, 1); // Fractional source index. vec3 sourceFracIndexRC = ${h}; // Compute the four integer indices. ivec3 sourceFloorRC = ivec3(max(sourceFracIndexRC, vec3(0.0))); ivec3 sourceCeilRC = ivec3( min(inputShapeRC - 1.0, ceil(sourceFracIndexRC))); // Should we calculate next column and row elements in 2x2 packed cell. bool hasNextCol = d < ${l-1}; bool hasNextRow = coords.z < ${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 MAe(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a,[l,u]=o,d=se().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new CAe(r.shape,l,u,s,i):new EAe(r.shape,l,u,s,i);return n.runWebGLProgram(d,[r],"float32")}var $Ae={kernelName:Tl,backendName:"webgl",kernelFunc:MAe},RAe=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,a,r]=t,[,s,i]=e,o=[n&&s>1?a-1:a,n&&i>1?r-1:r],l=[n&&s>1?s-1:s,n&&i>1?i-1:i],u=o[0]/l[0],d=o[1]/l[1],h=1/u,p=1/d,c=Math.ceil(h)*2+2,m=Math.ceil(p)*2+2;this.userCode=` void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; int d = coords[3]; int r = coords[1]; int c = coords[2]; float accumulator = 0.0; const float heightScale = float(${u}); const float widthScale = float(${d}); const float invHeightScale = float(${h}); const float invWidthScale = float(${p}); const int winHeight = int(${c}); const int winWidth = int(${m}); // Compute bounds for where in dy we will look float startRLerp = floor(float(r) * invHeightScale); int startDyR = int(startRLerp - float(winHeight / 2)); float startCLerp = floor(float(c) * invWidthScale); int startDyC = int(startCLerp - float(winWidth / 2)); // Loop over dy for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) { int dyR = dyROffset + startDyR; // Guard against the window exceeding the bounds of dy if (dyR < 0 || dyR >= ${s}) { continue; } for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) { int dyC = dyCOffset + startDyC; // Guard against the window exceeding the bounds of dy if (dyC < 0 || dyC >= ${i}) { continue; } float dxR = float(dyR) * heightScale; int topDxRIndex = int(floor(dxR)); int bottomDxRIndex = int(min(ceil(dxR), ${a-1}.0)); float dxRLerp = dxR - float(topDxRIndex); float inverseDxRLerp = 1.0 - dxRLerp; float dxC = float(dyC) * widthScale; int leftDxCIndex = int(floor(dxC)); int rightDxCIndex = int(min(ceil(dxC), ${r-1}.0)); float dxCLerp = dxC - float(leftDxCIndex); float inverseDxCLerp = 1.0 - dxCLerp; if (r == topDxRIndex && c == leftDxCIndex) { // topLeft accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * inverseDxCLerp; } if (r == topDxRIndex && c == rightDxCIndex) { // topRight accumulator += getDy(b, dyR, dyC, d) * inverseDxRLerp * dxCLerp; } if (r == bottomDxRIndex && c == leftDxCIndex) { // bottomLeft accumulator += getDy(b, dyR, dyC, d) * dxRLerp * inverseDxCLerp; } if (r == bottomDxRIndex && c == rightDxCIndex) { // bottomRight accumulator += getDy(b, dyR, dyC, d) * dxRLerp * dxCLerp; } } } // End loop over dy setOutput(accumulator); } `}};function FAe(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a,o=new RAe(s.shape,r.shape,i);return n.runWebGLProgram(o,[s],s.dtype)}var OAe={kernelName:q1,backendName:"webgl",kernelFunc:FAe},DAe=class{constructor(e,t,n,a,r){this.variableNames=["A"],this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,n,l];let u=[a&&t>1?i-1:i,a&&n>1?o-1:o],d=[a&&t>1?t-1:t,a&&n>1?n-1:n],h=a?"0.5":"0.0",p;r?p="max((vec2(yRC) + vec2(0.5)) * effectiveInputOverOutputRatioRC, vec2(0.0))":p="vec2(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` const vec2 effectiveInputOverOutputRatioRC = vec2( ${u[0]/d[0]}, ${u[1]/d[1]}); const vec2 inputShapeRC = vec2(${i}.0, ${o}.0); void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; int d = coords[3]; ivec2 yRC = coords.yz; // Fractional source index. vec2 sourceFracIndexRC = ${p}; // Compute the coordinators of nearest neighbor point. ivec2 sourceNearestRC = ivec2( min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${h}))); float newValue = getA(b, sourceNearestRC.x, sourceNearestRC.y, d); setOutput(newValue); } `}},_Ae=class{constructor(e,t,n,a,r){this.variableNames=["A"],this.packedInputs=!0,this.packedOutput=!0,this.outputShape=[];let[s,i,o,l]=e;this.outputShape=[s,t,n,l];let u=[a&&t>1?i-1:i,a&&n>1?o-1:o],d=[a&&t>1?t-1:t,a&&n>1?n-1:n],h=a?"0.5":"0.0",p;r?p="max((vec3(yRC) + vec3(0.5)) * effectiveInputOverOutputRatioRC, vec3(0.0))":p="vec3(yRC) * effectiveInputOverOutputRatioRC",this.userCode=` const vec3 effectiveInputOverOutputRatioRC = vec3( ${u[0]/d[0]}, ${u[1]/d[1]}, ${u[1]/d[1]}); const vec3 inputShapeRC = vec3(${i}.0, ${o}.0, ${o}.0); float getAValue(int b, int r, int c, int d) { return getChannel(getA(b, r, c, d), vec2(c, d)); } void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; int d = coords[3]; // Calculate values for next column in yRC.z. ivec3 yRC = coords.yzz + ivec3(0, 0, 1); // Fractional source index. vec3 sourceFracIndexRC = ${p}; // Compute the coordinators of nearest neighbor point. ivec3 sourceNearestRC = ivec3( min(inputShapeRC - 1.0, floor(sourceFracIndexRC + ${h}))); // 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 zAe(e){let{inputs:t,backend:n,attrs:a}=e,{images:r}=t,{alignCorners:s,halfPixelCenters:i,size:o}=a,[l,u]=o,d=se().getBool("WEBGL_PACK_IMAGE_OPERATIONS")?new _Ae(r.shape,l,u,s,i):new DAe(r.shape,l,u,s,i);return n.runWebGLProgram(d,[r],r.dtype)}var PAe={kernelName:sf,backendName:"webgl",kernelFunc:zAe},LAe=class{constructor(e,t,n){this.variableNames=["dy"],this.outputShape=[],this.outputShape=t;let[,a,r]=t,[,s,i]=e,o=[n&&s>1?a-1:a,n&&i>1?r-1:r],l=[n&&s>1?s-1:s,n&&i>1?i-1:i],u=o[0]/l[0],d=o[1]/l[1],h=1/u,p=1/d,c=Math.ceil(h)*2+2,m=Math.ceil(p)*2+2;this.userCode=` void main() { ivec4 coords = getOutputCoords(); int b = coords[0]; int d = coords[3]; int r = coords[1]; int c = coords[2]; float accumulator = 0.0; const float heightScale = float(${u}); const float widthScale = float(${d}); const float invHeightScale = float(${h}); const float invWidthScale = float(${p}); const int winHeight = int(${c}); const int winWidth = int(${m}); // Compute bounds for where in dy we will look float startRLerp = floor(float(r) * invHeightScale); int startDyR = int(floor(startRLerp - float(winHeight / 2))); float startCLerp = floor(float(c) * invWidthScale); int startDyC = int(floor(startCLerp - float(winWidth / 2))); // Loop over dy for (int dyROffset = 0; dyROffset < winHeight; dyROffset++) { int dyR = dyROffset + startDyR; // Guard against the window exceeding the bounds of dy if (dyR < 0 || dyR >= ${s}) { continue; } for (int dyCOffset = 0; dyCOffset < winWidth; dyCOffset++) { int dyC = dyCOffset + startDyC; // Guard against the window exceeding the bounds of dy if (dyC < 0 || dyC >= ${i}) { continue; } float sourceFracRow = float(${o[0]}) * (float(dyR) / float(${l[0]})); float sourceFracCol = float(${o[1]}) * (float(dyC) / float(${l[1]})); int sourceNearestRow = int(min( float(int(${a}) - 1), ${n} ? float(round(sourceFracRow)) : float(floor(sourceFracRow)))); int sourceNearestCol = int(min( float(int(${r}) - 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 WAe(e){let{inputs:t,backend:n,attrs:a}=e,{images:r,dy:s}=t,{alignCorners:i}=a,o=new LAe(s.shape,r.shape,i);return n.runWebGLProgram(o,[s],s.dtype)}var BAe={kernelName:G1,backendName:"webgl",kernelFunc:WAe},VAe=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 a=i=>t.indexOf(i)!==-1&&e[i]!==1?`${e[i]} - coords[${i}] - 1`:`coords[${i}]`,r=e.map((i,o)=>a(o)).join(","),s=kt(n);this.userCode=` void main() { ${s} coords = getOutputCoords(); setOutput(getX(${r})); } `}},UAe=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 a=Bn("rc",n),r=`${a[n-1]} + 1 < ${this.outputShape[n-1]}`,s=`${a[n-2]} + 1 < ${this.outputShape[n-2]}`,i=kt(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(${r}){ result.g = getChannel(getX(${e[0]} - (rc + 1) - 1), ${e[0]} - (rc + 1) - 1); } setOutput(result); } `:this.userCode=` void main() { ${i} rc = getOutputCoords(); vec4 result = vec4(0.); result.r = ${o(a.slice())}; if(${r}){ result.g = ${l(a.slice())}; } if(${s}) { result.b = ${u(a.slice())}; if(${r}) { result.a = ${d(a.slice())}; } } setOutput(result); } `;function o(c){return h(c)}function l(c){return c[n-1]="("+c[n-1]+" + 1)",h(c)}function u(c){return c[n-2]="("+c[n-2]+" + 1)",h(c)}function d(c){return c[n-1]="("+c[n-1]+" + 1)",c[n-2]="("+c[n-2]+" + 1)",h(c)}function h(c){let m=e.map((y,A)=>p(A,c)),f=m.join(","),g=m.slice(-2).join(",");return`getChannel(getX(${f}), vec2(${g}))`}function p(c,m){return t.indexOf(c)!==-1&&e[c]!==1?`${e[c]} - ${m[c]} - 1`:`${m[c]}`}}};function jAe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dims:s}=a,i=r.shape.length,o=k.parseAxisParam(s,r.shape);if(i===0)return fa({inputs:{x:r},backend:n});let l=se().getBool("WEBGL_PACK_ARRAY_OPERATIONS")?new UAe(r.shape,o):new VAe(r.shape,o);return n.runWebGLProgram(l,[r],r.dtype)}var HAe={kernelName:Cl,backendName:"webgl",kernelFunc:jAe},GAe=class{constructor(e,t){this.variableNames=["Image"],this.outputShape=[];let n=e[1],a=e[2];this.outputShape=e;let r="";typeof t=="number"?r=`float outputValue = ${t.toFixed(2)};`:r=` vec3 fill = vec3(${t.join(",")}); float outputValue = fill[coords[3]];`,this.userCode=` uniform vec4 params; void main() { ivec4 coords = getOutputCoords(); int x = coords[2]; int y = coords[1]; float coordXFloat = (float(x) - params[0]) * params[3] - (float(y) - params[1]) * params[2]; float coordYFloat = (float(x) - params[0]) * params[2] + (float(y) - params[1]) * params[3]; int coordX = int(round(coordXFloat + params[0])); int coordY = int(round(coordYFloat + params[1])); ${r} if(coordX >= 0 && coordX < ${a} && coordY >= 0 && coordY < ${n}) { outputValue = getImage(coords[0], coordY, coordX, coords[3]); } setOutput(outputValue); } `}getCustomSetupFunc(e,t,n,a){return(r,s)=>{this.paramsLoc==null&&(this.paramsLoc=r.getUniformLocationNoThrow(s,"params")),r.gl.uniform4f(this.paramsLoc,e,t,n,a)}}},qAe={kernelName:ch,backendName:"webgl",kernelFunc:({inputs:e,attrs:t,backend:n})=>{let{image:a}=e,{radians:r,fillValue:s,center:i}=t,o=n,l=new GAe(a.shape,s),[u,d]=M.getImageCenter(i,a.shape[1],a.shape[2]),h=l.getCustomSetupFunc(u,d,Math.sin(r),Math.cos(r));return o.runWebGLProgram(l,[a],a.dtype,h)}},KAe=` // 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; } } `,XAe=ot({opSnippet:KAe}),ZAe={kernelName:Ml,backendName:"webgl",kernelFunc:XAe},YAe="return inversesqrt(x);",JAe=ot({opSnippet:YAe,cpuKernelImpl:Nce}),QAe={kernelName:Di,backendName:"webgl",kernelFunc:JAe},hC=class{constructor(e,t,n,a,r,s,i=!0){this.variableNames=["updates","indices","defaultValue"],this.outputShape=s;let o=kt(r.length),l=kt(s.length),u="";n===1?u="i":n===2&&(u="i, j");let d=`getIndices(${u})`,h="";a===1?h="i":a===2&&(h="i, coords[1]");let p=`getUpdates(${h})`,c=t>1?"strides[j]":"strides";this.userCode=` ${o} strides = ${o}(${r}); void main() { ${l} coords = getOutputCoords(); float sum = 0.0; bool found = false; for (int i = 0; i < ${e}; i++) { int flattenedIndex = 0; for (int j = 0; j < ${t}; j++) { int index = round(${d}); flattenedIndex += index * ${c}; } if (flattenedIndex == coords[0]) { sum += ${p}; found = true; } } setOutput(mix(getDefaultValue(), sum, float(found))); } `}};function e2e(e){let{inputs:t,backend:n,attrs:a}=e,{indices:r,updates:s}=t,{shape:i}=a,{sliceRank:o,numUpdates:l,sliceSize:u,strides:d,outputSize:h}=M.calculateShapes(s,r,i),p=[h/u,u];if(h===0)return n.makeTensorInfo(i,r.dtype);let c=be({inputs:{x:r},backend:n,attrs:{shape:[l,o]}}),m=be({inputs:{x:s},backend:n,attrs:{shape:[l,u]}}),f=n.makeTensorInfo([],"float32",new Float32Array([0])),g=new hC(l,o,c.shape.length,m.shape.length,d,p),y=n.runWebGLProgram(g,[m,c,f],m.dtype),A=be({inputs:{x:y},backend:n,attrs:{shape:i}});return n.disposeIntermediateTensorInfo(c),n.disposeIntermediateTensorInfo(m),n.disposeIntermediateTensorInfo(y),n.disposeIntermediateTensorInfo(f),A}var t2e={kernelName:eh,backendName:"webgl",kernelFunc:e2e},n2e=class{constructor(e,t,n){this.variableNames=["c","a","b"],this.outputShape=t;let a,r;if(n>4)throw Error(`Where for rank ${n} is not yet supported`);if(n===1)r="resRC",a="resRC";else{let i=["resRC.x","resRC.y","resRC.z","resRC.w"],o=[],l=[];for(let u=0;u= 1.0) { setOutput(getA(${r})); } else { setOutput(getB(${r})); } } `}};function a2e(e){let{inputs:t,backend:n}=e,{condition:a,t:r,e:s}=t,i=new n2e(a.shape.length,r.shape,r.shape.length);return n.runWebGLProgram(i,[a,r,s],Ga(r.dtype,s.dtype))}var r2e={kernelName:th,backendName:"webgl",kernelFunc:a2e},s2e=` // Stable and Attracting Fixed Point (0, 1) for Normalized Weights. // see: https://arxiv.org/abs/1706.02515 float scaleAlpha = ${M.SELU_SCALEALPHA}; float scale = ${M.SELU_SCALE}; return (x >= 0.0) ? scale * x : scaleAlpha * (exp(x) - 1.0); `,i2e=ot({opSnippet:s2e}),o2e={kernelName:nh,backendName:"webgl",kernelFunc:i2e},l2e="return 1.0 / (1.0 + exp(-1.0 * x));",u2e=ot({opSnippet:l2e}),d2e={kernelName:Rl,backendName:"webgl",kernelFunc:u2e},h2e=` if (isnan(x)) { return 0.0; } return sign(x); `,p2e=ot({opSnippet:h2e}),c2e={kernelName:sh,backendName:"webgl",kernelFunc:p2e},f2e=NE+` return sin(x); `,m2e=ot({opSnippet:f2e}),g2e={kernelName:$l,backendName:"webgl",kernelFunc:m2e},y2e=` float e2x = exp(x); return (e2x - 1.0 / e2x) / 2.0; `,A2e=ot({opSnippet:y2e}),x2e={kernelName:rh,backendName:"webgl",kernelFunc:A2e},b2e=` 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; `,v2e=ot({opSnippet:b2e}),w2e={kernelName:ih,backendName:"webgl",kernelFunc:v2e},k2e=e=>{let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{blockShape:s,paddings:i}=a;k.assert(r.shape.length<=4,()=>"spaceToBatchND for rank > 4 with a WebGL backend not implemented yet");let o=s.reduce((y,A)=>y*A),l=[[0,0]];l.push(...i);for(let y=1+s.length;yn.disposeIntermediateTensorInfo(y)),g},I2e={kernelName:of,backendName:"webgl",kernelFunc:k2e};function S2e(e){let{inputs:t,backend:n}=e,{indices:a,values:r,denseShape:s,defaultValue:i}=t;if(s.shape.length!==1)throw new Error(`Dense shape must be a vector, saw: ${s.shape}`);if(a.shape.length!==2)throw new Error(`Indices must be a matrix, saw: ${a.shape}`);if(r.shape.length!==1)throw new Error(`Values must be a vector, saw: ${r.shape}`);if(i.shape.length!==0)throw new Error(`Default value must be a scalar, saw: ${i.shape}`);let o=n.readSync(a.dataId),l=n.readSync(r.dataId),u=n.readSync(s.dataId),d=n.readSync(i.dataId)[0],[h,p,c,m,f]=Ece(o,a.shape,a.dtype,l,r.dtype,u,d);return[n.makeTensorInfo(p,a.dtype,h),n.makeTensorInfo([p[0]],r.dtype,c),n.makeTensorInfo([m.length],"bool",new Uint8Array(m.map(g=>Number(g)))),n.makeTensorInfo([f.length],a.dtype,new Int32Array(f))]}var N2e={kernelName:K1,backendName:"webgl",kernelFunc:S2e};function T2e(e){let{inputs:t,backend:n}=e,{inputIndices:a,inputShape:r,newShape:s}=t;if(a.shape.length!==2)throw new Error(`Input indices should be a matrix but received shape ${a.shape}`);if(r.shape.length!==1)throw new Error(`Input shape should be a vector but received shape ${r.shape}`);if(s.shape.length!==1)throw new Error(`Target shape should be a vector but received shape ${s.shape}`);let i=Array.from(n.readSync(r.dataId)),o=n.readSync(a.dataId),l=Array.from(n.readSync(s.dataId)),[u,d,h]=Cce(o,a.shape,a.dtype,i,l);return[n.makeTensorInfo(d,a.dtype,u),n.makeTensorInfo([h.length],s.dtype,new Int32Array(h))]}var E2e={kernelName:X1,backendName:"webgl",kernelFunc:T2e};function C2e(e){let{inputs:t,backend:n}=e,{data:a,indices:r,segmentIds:s}=t;if(a.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape ${r.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape ${s.shape}`);let i=n.readSync(a.dataId),o=n.readSync(r.dataId),l=n.readSync(s.dataId),[u,d]=pE(i,a.shape,a.dtype,o,l,!0);return n.makeTensorInfo(d,a.dtype,u)}var M2e={kernelName:Z1,backendName:"webgl",kernelFunc:C2e};function $2e(e){let{inputs:t,backend:n}=e,{data:a,indices:r,segmentIds:s}=t;if(a.shape.length<1)throw new Error("Data should be at least 1 dimensional but received scalar");if(r.shape.length!==1)throw new Error(`Indices should be a vector but received shape ${r.shape}`);if(s.shape.length!==1)throw new Error(`Segment ids should be a vector but received shape ${s.shape}`);let i=n.readSync(a.dataId),o=n.readSync(r.dataId),l=n.readSync(s.dataId),[u,d]=pE(i,a.shape,a.dtype,o,l);return n.makeTensorInfo(d,a.dtype,u)}var R2e={kernelName:Y1,backendName:"webgl",kernelFunc:$2e};function F2e(e){let{inputs:t,backend:n,attrs:a}=e,{sparseIndices:r,sparseValues:s,defaultValue:i}=t,{outputShape:o}=a,{sliceRank:l,numUpdates:u,strides:d,outputSize:h}=M.calculateShapes(s,r,o),p=!1,c=new hC(u,l,r.shape.length,s.shape.length,d,[h,1],p),m=n.runWebGLProgram(c,[s,r,i],s.dtype),f=be({inputs:{x:m},backend:n,attrs:{shape:o}});return n.disposeIntermediateTensorInfo(m),f}var O2e={kernelName:J1,backendName:"webgl",kernelFunc:F2e};function D2e(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{numOrSizeSplits:s,axis:i}=a,o=k.parseAxisParam(i,r.shape)[0],l=M.prepareSplitSize(r,s,o),u=r.shape.length,d=new Array(u).fill(0),h=r.shape.slice();return l.map(p=>{let c=[...h];c[o]=p;let m=fp({inputs:{x:r},backend:n,attrs:{begin:d,size:c}});return d[o]+=p,m})}var _2e={kernelName:oh,backendName:"webgl",kernelFunc:D2e},z2e="return sqrt(x);",P2e=ot({opSnippet:z2e}),L2e={kernelName:Fl,backendName:"webgl",kernelFunc:P2e},W2e="return x * x;",B2e=ot({opSnippet:W2e}),V2e={kernelName:lf,backendName:"webgl",kernelFunc:B2e},pC="return (a - b) * (a - b);",U2e=Tn({opSnippet:pC,packedOpSnippet:pC}),j2e={kernelName:_i,backendName:"webgl",kernelFunc:U2e};function H2e({inputs:e,attrs:t,backend:n}){let{x:a}=e,r=gr+` return x > 0.0 ? 1.0 : float(${t.alpha}); `,s=new Qs(a.shape,r);return n.runWebGLProgram(s,[a],a.dtype)}var G2e={kernelName:Li,backendName:"webgl",kernelFunc:H2e},q2e=class{constructor(e,t,n){this.variableNames=["x"],this.outputShape=n;let a=n.length,r=kt(n.length),s=kt(n.length),i="";if(a===1)i="coords * strides + begin";else{let o=0;i=n.map((l,u)=>(o++,n.length===1?`coords * strides[${u}] + begin[${u}]`:`coords[${o-1}] * strides[${u}] + begin[${u}]`)).join(",")}this.userCode=` ${r} begin = ${r}(${e}); ${r} strides = ${r}(${t}); void main() { ${s} coords = getOutputCoords(); setOutput(getX(${i})); } `}};function K2e(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{begin:s,end:i,strides:o,beginMask:l,endMask:u,ellipsisMask:d,newAxisMask:h,shrinkAxisMask:p}=a,{nonStrided:c,$begin:m,$strides:f,size:g,newShape:y,outShape:A}=Cn.sliceInfo(r.shape,s,i,o,l,u,d,h,p),x=be({inputs:{x:r},backend:n,attrs:{shape:y}}),v;if(c){let w=fp({inputs:{x},backend:n,attrs:{begin:m,size:g}});v=be({inputs:{x:w},backend:n,attrs:{shape:A}}),n.disposeIntermediateTensorInfo(w)}else if(A.some(w=>w===0))v=n.makeTensorInfo(A,r.dtype,[]);else if(n.shouldExecuteOnCPU([x])){let w=n.texData.get(x.dataId).values,I=Pe(x.shape,x.dtype,w),T=Mce(A,I,f,m);v=n.makeTensorInfo(A,x.dtype,T.values)}else{let w=new q2e(m,f,A);v=n.runWebGLProgram(w,[x],x.dtype)}let b=be({inputs:{x:v},backend:n,attrs:{shape:A}});return n.disposeIntermediateTensorInfo(x),n.disposeIntermediateTensorInfo(v),b}var X2e={kernelName:lh,backendName:"webgl",kernelFunc:K2e};function Z2e(e){let{inputs:t,backend:n,attrs:a}=e,{separator:r,nGramWidths:s,leftPad:i,rightPad:o,padWidth:l,preserveShortSequences:u}=a,{data:d,dataSplits:h}=t,p=n.readSync(d.dataId),c=n.readSync(h.dataId),[m,f]=$ce(p,c,r,s,i,o,l,u);return[n.makeTensorInfo([m.length],"string",m),n.makeTensorInfo(h.shape,"int32",f)]}var Y2e={kernelName:Q1,backendName:"webgl",kernelFunc:Z2e};function J2e(e){let{inputs:t,backend:n,attrs:a}=e,{skipEmpty:r}=a,{input:s,delimiter:i}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(s.shape.length!==1)throw new Error(`Input must be a vector, got shape: ${s.shape}`);if(i.shape.length!==0)throw new Error(`Delimiter must be a scalar, got shape: ${i.shape}`);let o=n.readSync(s.dataId),l=n.readSync(i.dataId)[0],[u,d,h]=Rce(o,l,r),p=d.length;return[n.makeTensorInfo([p,2],"int32",u),n.makeTensorInfo([p],"string",d),n.makeTensorInfo([2],"int32",new Int32Array(h))]}var Q2e={kernelName:eA,backendName:"webgl",kernelFunc:J2e};function exe(e){let{inputs:t,backend:n,attrs:a}=e,{numBuckets:r}=a,{input:s}=t;if(s.dtype!=="string")throw new Error("Input must be of datatype string");if(r<=0)throw new Error("Number of buckets must be at least 1");let i=n.readSync(s.dataId),o=Fce(i,r);return n.makeTensorInfo(s.shape,"int32",o)}var txe={kernelName:tA,backendName:"webgl",kernelFunc:exe},nxe="return tan(x);",axe=ot({opSnippet:nxe}),rxe={kernelName:_l,backendName:"webgl",kernelFunc:axe},sxe=` float e2x = exp(-2.0 * abs(x)); return sign(x) * (1.0 - e2x) / (1.0 + e2x); `,ixe=ot({opSnippet:sxe}),oxe={kernelName:zl,backendName:"webgl",kernelFunc:ixe},lxe=class{constructor(e,t){this.variableNames=["A"];let n=new Array(e.length);for(let s=0;s5)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"],a=[];for(let r=0;r5){let o=n.readSync(r.dataId),l=r.dtype==="string"?o.map(h=>k.decodeString(h)):o,u=Pe(r.shape,r.dtype,l),d=Dce(u,s);return n.makeTensorInfo(d.shape,d.dtype,d.values)}let i=new lxe(r.shape,s);return n.runWebGLProgram(i,[r],r.dtype)}var dxe={kernelName:Pi,backendName:"webgl",kernelFunc:cC};function hxe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{k:s,sorted:i}=a,o=n.readSync(r.dataId),[l,u]=_ce(o,r.shape,r.dtype,s,i);return[n.makeTensorInfo(l.shape,l.dtype,l.values),n.makeTensorInfo(u.shape,u.dtype,u.values)]}var pxe={kernelName:uh,backendName:"webgl",kernelFunc:hxe},cxe=class{constructor(e,t,n,a,r,s){this.variableNames=["Image","Transforms"],this.outputShape=s;let i=n==="nearest"?1:2,o;switch(a){case"constant":o=1;break;case"reflect":o=2;break;case"wrap":o=3;break;case"nearest":o=4;break;default:o=1;break}this.userCode=` float mapCoord(float outCoord, float len) { float inCoord = outCoord; if(${o} == 2) { if (inCoord < 0.0) { if (len <= 1.0) { inCoord = 0.0; } else { float sz2 = 2.0 * len; if (inCoord < sz2) { inCoord = sz2 * float(int(float(-inCoord / sz2))) + inCoord; } inCoord = inCoord < -len ? inCoord + sz2 : -inCoord - 1.0; } } else if (inCoord > len - 1.0) { if (len <= 1.0) { inCoord = 0.0; } else { float sz2 = 2.0 * len; inCoord -= sz2 * float(int(float(inCoord / sz2))); if (inCoord >= len) { inCoord = sz2 - inCoord - 1.0; } } } return clamp(inCoord, 0.0, len - 1.0); } else if (${o} == 3) { if (inCoord < 0.0) { if (len <= 1.0) { inCoord = 0.0; } else { float sz = len - 1.0; inCoord += len * (float(int(float(-inCoord / sz))) + 1.0); } } else if (inCoord > len - 1.0) { if (len <= 1.0) { inCoord = 0.0; } else { float sz = len - 1.0; inCoord -= len * float(int(float(inCoord / sz))); } } return clamp(inCoord, 0.0, len - 1.0); } else if (${o} == 4) { return clamp(outCoord, 0.0, len - 1.0); } else { return outCoord; } } float readWithFillValue(int batch, int coordY, int coordX, int channel) { float outputValue; if (0 <= coordY && coordY < ${e} && 0 <= coordX && coordX < ${t}) { outputValue = getImage(batch, coordY, coordX, channel); } else { outputValue = float(${r}); } return outputValue; } void main() { ivec4 coords = getOutputCoords(); float outputValue; int batch = coords[0]; int x = coords[2]; int y = coords[1]; int channel = coords[3]; float xf = float(x); float yf = float(y); float a1 = getTransforms(batch, 0); float a2 = getTransforms(batch, 1); float a3 = getTransforms(batch, 2); float b1 = getTransforms(batch, 3); float b2 = getTransforms(batch, 4); float b3 = getTransforms(batch, 5); float c1 = getTransforms(batch, 6); float c2 = getTransforms(batch, 7); float projection = c1 * xf + c2 * yf + 1.0; if (projection == 0.0) { outputValue = float(${r}); } else { float inX = (a1 * xf + a2 * yf + a3) / projection; float inY = (b1 * xf + b2 * yf + b3) / projection; float mapX = mapCoord(inX, float(${t})); float mapY = mapCoord(inY, float(${e})); if (${i} == 1) { int coordY = int(round(mapY)); int coordX = int(round(mapX)); outputValue = readWithFillValue(batch, coordY, coordX, channel); } else { float yFloor = floor(mapY); float xFloor = floor(mapX); float yCeil = yFloor + 1.0; float xCeil = xFloor + 1.0; float valueYFloor = (xCeil - mapX) * readWithFillValue(batch, int(yFloor), int(xFloor), channel) + (mapX - xFloor) * readWithFillValue(batch, int(yFloor), int(xCeil), channel); float valueYCeil = (xCeil - mapX) * readWithFillValue(batch, int(yCeil), int(xFloor), channel) + (mapX - xFloor) * readWithFillValue(batch, int(yCeil), int(xCeil), channel); outputValue = (yCeil - mapY) * valueYFloor + (mapY - yFloor) * valueYCeil; } } setOutput(outputValue); } `}};function fxe(e){let{inputs:t,backend:n,attrs:a}=e,{image:r,transforms:s}=t,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=a,[d,h,p,c]=r.shape,[m,f]=u!=null?u:[h,p],g=[d,m,f,c],y=new cxe(h,p,i,o,l,g);return n.runWebGLProgram(y,[r,s],"float32")}var mxe={kernelName:dh,backendName:"webgl",kernelFunc:fxe};function gxe(e){let{inputs:t,attrs:n,backend:a}=e,{axis:r}=n,{x:s}=t;mu(s,"unique"),console.warn("WARNING: ","UI might be locked temporarily as data is being downloaded");let i=a.readSync(s.dataId),{outputValues:o,outputShape:l,indices:u}=zce(i,r,s.shape,s.dtype);return[a.makeTensorInfo(l,s.dtype,o),a.makeTensorInfo([u.length],"int32",u)]}var yxe={kernelName:nA,backendName:"webgl",kernelFunc:gxe};function Axe(e){let{inputs:t,backend:n,attrs:a}=e,{value:r}=t,{axis:s}=a;s<0&&(s+=r.shape.length);let i=r,o=i.shape.length,l=r.shape[s],u=new Array(o-1),d=0;for(let f=0;fn.disposeIntermediateTensorInfo(f)),m}var xxe={kernelName:hh,backendName:"webgl",kernelFunc:Axe},bxe=class{constructor(e,t){this.variableNames=["x","segmentIds"];let n=e.windowSize,a=e.batchSize,r=e.inSize,s=e.numSegments,i=s*Math.ceil(r/n);this.outputShape=[a,i];let o="0.0",l="sumValue",u=Math.floor(n/4)*4,d=n%4,h=` sumValue += dot(values, segFilter); `,p="";r%n>0&&(p=` if (inIdx < 0 || inIdx >= ${r}) { return initializationValue; } `);let c="";r%n>0&&(c=` if (inIdx < 0 || inIdx >= ${r}) { return -1.0; } `),this.userCode=` const float initializationValue = ${o}; float getValue(int batch, int inIdx) { ${p} return getX(batch, inIdx); } float getSegmentIdAtIndex(int inIdx) { ${c} return getSegmentIds(inIdx); } void main() { ivec2 coords = getOutputCoords(); int batch = coords[0]; int outIdx = coords[1]; int inOffset = int(floor(float(outIdx) / float( ${s})) * float(${n})); int currentSeg = int(mod(float(outIdx), float(${s}))); float sumValue = 0.0; for (int i = 0; i < ${u}; i += 4) { int inIdx = inOffset + i; vec4 values = vec4( getValue(batch, inIdx), getValue(batch, inIdx + 1), getValue(batch, inIdx + 2), getValue(batch, inIdx + 3) ); vec4 segFilter = vec4( int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0, int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0, int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0, int(getSegmentIdAtIndex(inIdx + 3)) == currentSeg ? 1 : 0 ); ${h} } int inIdx = inOffset + ${u}; if (${d===1}) { vec4 values = vec4( getValue(batch, inIdx), initializationValue, initializationValue, initializationValue ); int inIdxSeg = int(getSegmentIdAtIndex(inIdx)); vec4 segFilter = vec4( int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0, 0, 0, 0 ); ${h} } else if (${d===2}) { vec4 values = vec4( getValue(batch, inIdx), getValue(batch, inIdx + 1), initializationValue, initializationValue ); vec4 segFilter = vec4( int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0, int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0, 0, 0 ); ${h} } else if (${d===3}) { vec4 values = vec4( getValue(batch, inIdx), getValue(batch, inIdx + 1), getValue(batch, inIdx + 2), initializationValue ); vec4 segFilter = vec4( int(getSegmentIdAtIndex(inIdx)) == currentSeg ? 1 : 0, int(getSegmentIdAtIndex(inIdx + 1)) == currentSeg ? 1 : 0, int(getSegmentIdAtIndex(inIdx + 2)) == currentSeg ? 1 : 0, 0 ); ${h} } setOutput(${l}); } `}};function vxe(e){let{inputs:t,backend:n,attrs:a}=e,{x:r,segmentIds:s}=t,{numSegments:i}=a,o=r.shape.length,l=[],u=0,d=M.getAxesPermutation([u],o),h=r;d!=null&&(h=Vn({inputs:{x:r},backend:n,attrs:{perm:d}}),l.push(h),u=M.getInnerMostAxes(1,o)[0]);let p=M.segment_util.computeOutShape(h.shape,u,i),c=k.sizeFromShape([h.shape[u]]),m=be({inputs:{x:h},backend:n,attrs:{shape:[-1,c]}});l.push(m);let f=cA(r.dtype),g=(v,b,w,I,T)=>{let C=v.shape[0],z=v.shape[1],$=M.segment_util.segOpComputeOptimalWindowSize(z,T),S={windowSize:$,inSize:z,batchSize:C,numSegments:T},D=new bxe(S,b),_=n.compileAndRun(D,[v,w],I);if(l.push(_),_.shape[1]===T)return _;let W=dC({backend:n,attrs:{start:0,stop:T,step:1,dtype:"float32"}}),X=cC({inputs:{x:W},backend:n,attrs:{reps:[z/$]}});return l.push(W),l.push(X),g(_,b,X,I,T)},y=g(m,"unsortedSegmentSum",s,f,i),A=be({inputs:{x:y},backend:n,attrs:{shape:p}}),x=A;if(d!=null){l.push(A);let v=M.getUndoAxesPermutation(d);x=Vn({inputs:{x},backend:n,attrs:{perm:v}})}return l.forEach(v=>n.disposeIntermediateTensorInfo(v)),x}var wxe={kernelName:uf,backendName:"webgl",kernelFunc:vxe},kxe=[Yye,e1e,_fe,Pfe,Bfe,jfe,Gfe,Xfe,Yfe,Qfe,a0e,s0e,l0e,h0e,A0e,f0e,v0e,S0e,k0e,C0e,$0e,F0e,z0e,j0e,G0e,J0e,eme,rme,ome,yfe,pme,wme,Ime,gme,Eme,Mme,Nme,Fme,_me,Lme,Bme,Ume,Gme,Jme,ege,Kme,age,ige,lge,pge,gge,bge,kge,Ige,Sge,Tge,Cge,$ge,Fge,Dge,Lge,Vge,Hge,qge,Zge,eye,rye,lye,gfe,dye,dme,cye,gye,xye,xfe,kye,Tye,Cye,_ye,Fye,Wye,Uye,qye,n1e,d1e,l1e,f1e,g1e,A1e,i1e,b1e,w1e,N1e,M1e,O1e,V1e,Ife,j1e,q1e,Z1e,Q1e,K0e,nAe,rAe,iAe,uAe,cAe,vfe,mAe,gAe,X0e,P1e,xAe,TAe,kAe,Nfe,$Ae,OAe,PAe,BAe,HAe,qAe,ZAe,QAe,t2e,r2e,o2e,d2e,c2e,g2e,x2e,V0e,W1e,w2e,I2e,N2e,E2e,M2e,R2e,O2e,_2e,L2e,V2e,j2e,G2e,X2e,Y2e,Q2e,txe,L1e,Ffe,rxe,oxe,dxe,pxe,mxe,Ofe,yxe,xxe,wxe,aAe];for(let e of kxe)iA(e);var na;(function(e){e[e.float32=0]="float32",e[e.int32=1]="int32",e[e.bool=2]="bool",e[e.string=3]="string",e[e.complex64=4]="complex64"})(na||(na={}));var gp;(function(e){e[e.linear=0]="linear",e[e.relu=1]="relu",e[e.relu6=2]="relu6",e[e.prelu=3]="prelu",e[e.leakyrelu=4]="leakyrelu",e[e.sigmoid=5]="sigmoid"})(gp||(gp={}));var fC;function Ixe(e){fC=e.wasm.cwrap(Ll,null,["number","array","number","number","array","number","number","number","number","number","number","number","number"])}function Sxe(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s,bias:i,preluActivationWeights:o}=t;if(r.dtype!=="float32"||s.dtype!=="float32")throw new Error("_FusedMatMul for non non-float32 tensors not yet supported.");let{transposeA:l,transposeB:u,activation:d,leakyreluAlpha:h}=a,p=n.dataIdMap.get(r.dataId).id,c=n.dataIdMap.get(s.dataId).id,m=0;if(i!=null){let T=n.dataIdMap.get(i.dataId);if(T.shape.length!==1)throw new Error(`_FusedMatMul only supports rank-1 bias but got rank ${T.shape.length}.`);m=T.id}let f=o==null?0:n.dataIdMap.get(o.dataId).id,g=gp[d];if(g==null)throw new Error(`${d} activation not yet supported for FusedConv2D in the wasm backend.`);let y=l?r.shape[2]:r.shape[1],A=u?s.shape[1]:s.shape[2],x=r.shape[0],v=n.makeOutput([x,y,A],r.dtype),b=n.dataIdMap.get(v.dataId).id,w=new Uint8Array(new Int32Array(r.shape).buffer),I=new Uint8Array(new Int32Array(s.shape).buffer);return fC(p,w,r.shape.length,c,I,s.shape.length,l,u,g,m,f,h||0,b),v}var Nxe={kernelName:Ll,backendName:"wasm",setupFunc:Ixe,kernelFunc:Sxe};function Un(e){let t;function n(r){t=r.wasm.cwrap(e,null,["number","number"])}function a(r){let{backend:s,inputs:{x:i}}=r,o=s.dataIdMap.get(i.dataId).id,l=s.makeOutput(i.shape,i.dtype),u=s.dataIdMap.get(l.dataId).id;return k.sizeFromShape(l.shape)===0||t(o,u),l}return{kernelName:e,backendName:"wasm",setupFunc:n,kernelFunc:a}}var Txe=Un(xd);function jn(e,t,n){let a;function r(i){a=i.wasm.cwrap(e,null,["number","array","number","number","array","number","number","number"])}function s(i){let{backend:o,inputs:l}=i,{a:u,b:d}=l,h=o.dataIdMap.get(u.dataId).id,p=o.dataIdMap.get(d.dataId).id,c=n!=null?n:u.dtype,m=M.assertAndGetBroadcastShape(u.shape,d.shape),f=o.makeOutput(m,c);if(k.sizeFromShape(m)===0)return f;let g=new Uint8Array(new Int32Array(u.shape).buffer),y=new Uint8Array(new Int32Array(d.shape).buffer),A=o.dataIdMap.get(f.dataId).id,x=()=>a(h,g,u.shape.length,p,y,d.shape.length,na[u.dtype],A);if(t&&u.dtype==="float32")return x(),f;let v=M.getBroadcastDims(u.shape,m),b=M.getBroadcastDims(d.shape,m),w=v.every((T,C)=>T===C),I=b.every((T,C)=>T===C);if(w&&I)return x(),f;throw new Error(`Broadcasting along outer dims is not yet supported for ${u.dtype} ${e}.`)}return{kernelName:e,backendName:"wasm",setupFunc:r,kernelFunc:s}}var Exe=!0,Cxe=jn(Os,Exe),mC;function Mxe(e){mC=e.wasm.cwrap(Zo,null,["array","number","number","number"])}function $xe(e){let{inputs:t,backend:n}=e,a=n.makeOutput(t[0].shape,t[0].dtype);if(k.sizeFromShape(a.shape)===0)return a;let r=t.map(o=>n.dataIdMap.get(o.dataId).id),s=new Uint8Array(new Int32Array(r).buffer),i=n.dataIdMap.get(a.dataId).id;return mC(s,r.length,na[a.dtype],i),a}var Rxe={kernelName:Zo,backendName:"wasm",setupFunc:Mxe,kernelFunc:$xe};function J0(e){let{inputs:{x:t},backend:n}=e,a=n.makeOutput(t.shape,t.dtype),r=n.typedArrayFromHeap(t);return n.typedArrayFromHeap(a).set(r),a}var Fxe={kernelName:pl,backendName:"wasm",kernelFunc:J0},gC;function Oxe(e){gC=e.wasm.cwrap(Pl,null,["number","array","number","number","number","array","number"])}function Q0(e){let{inputs:t,backend:n,attrs:a}=e,[r,s]=_xe(t.x.shape,a.perm),i=!0;for(let m=0;m=r&&(s===-1||a[s]>a[i])&&(s=i);a[s]=r}return[n,a]}var zxe={kernelName:Pl,backendName:"wasm",kernelFunc:Q0,setupFunc:Oxe};function ti(e,t,n){let a=e.shape,r=e.shape.length,s=k.parseAxisParam(t,a),i=s,o=M.getAxesPermutation(i,r),l=null,u=!1;if(o!=null){let d=new Array(r);for(let p=0;p`new shape: ${i}, old shape: ${a.shape}. New shape and old shape must have the same number of elements.`),e.backend.incRef(a.dataId),{dataId:a.dataId,shape:i,dtype:a.dtype}}var Zxe={kernelName:Qd,backendName:"wasm",kernelFunc:yr},vC;function Yxe(e){vC=e.wasm.cwrap(Qo,null,["number","array","number","number","array","number","number","number","number"])}function Jxe(e){let{inputs:t,backend:n,attrs:a}=e,{a:r,b:s}=t,{transposeA:i,transposeB:o}=a;if(r.dtype!=="float32"||s.dtype!=="float32")throw new Error("BatchMatMul for non non-float32 tensors not yet supported.");let l=r.shape.length,u=s.shape.length,d=i?r.shape[l-2]:r.shape[l-1],h=o?s.shape[u-1]:s.shape[u-2],p=i?r.shape[l-1]:r.shape[l-2],c=o?s.shape[u-2]:s.shape[u-1],m=r.shape.slice(0,-2),f=s.shape.slice(0,-2),g=k.sizeFromShape(m),y=k.sizeFromShape(f),A=g===y||g===1||y===1;k.assert(l>=2&&u>=2&&A,()=>`Error in matMul: the input batch dimensions must either be the same or at least one input batch dimension must be 1. Got input batch dimensions of (${m}) and (${f}).`);let x=(g>y?r.shape.slice(0,-2):s.shape.slice(0,-2)).concat([p,c]);k.assert(d===h,()=>`Error in matMul: inner shapes (${d}) and (${h}) of Tensors with shapes ${r.shape} and ${s.shape} and transposeA=${i} and transposeB=${o} must match.`);let v=i?[g,d,p]:[g,p,d],b=o?[y,c,h]:[y,h,c],w=yr({inputs:{x:r},backend:n,attrs:{shape:v}}),I=yr({inputs:{x:s},backend:n,attrs:{shape:b}}),T=n.dataIdMap.get(w.dataId).id,C=n.dataIdMap.get(I.dataId).id,z=i?w.shape[2]:w.shape[1],$=o?I.shape[1]:I.shape[2],S=Math.max(g,y),D=n.makeOutput([S,z,$],w.dtype),_=n.dataIdMap.get(D.dataId).id,W=new Uint8Array(new Int32Array(w.shape).buffer),X=new Uint8Array(new Int32Array(I.shape).buffer);return vC(T,W,w.shape.length,C,X,I.shape.length,i,o,_),n.disposeData(w.dataId),n.disposeData(I.dataId),D.shape=x,D}var Qxe={kernelName:Qo,backendName:"wasm",setupFunc:Yxe,kernelFunc:Jxe};function em(e){let{inputs:{x:t},attrs:{dtype:n},backend:a}=e,r=a.makeOutput(t.shape,n),s=a.typedArrayFromHeap(t);return a.typedArrayFromHeap(r).set(s),r}var e5e={kernelName:el,backendName:"wasm",kernelFunc:em},t5e=Un(Ni),wC;function n5e(e){wC=e.wasm.cwrap(Ti,null,["number","number","number","number"])}function a5e(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{clipValueMin:s,clipValueMax:i}=a,o=n.dataIdMap.get(r.dataId).id,l=n.makeOutput(r.shape,r.dtype),u=n.dataIdMap.get(l.dataId).id;return wC(o,s,i,u),l}var r5e={kernelName:Ti,backendName:"wasm",setupFunc:n5e,kernelFunc:a5e};function kC(e){let{inputs:t,backend:n}=e,a=k.parseAxisParam(e.attrs.axis,t[0].shape)[0],r=M.computeOutShape(t.map(c=>c.shape),a),s=t.filter(c=>k.sizeFromShape(c.shape)>0);if(s.length===1)return J0({inputs:{x:s[0]},backend:n});let i=n.makeOutput(r,t[0].dtype);if(k.sizeFromShape(r)===0)return i;let o=s.map(c=>c.shape);if(M.assertParamsConsistent(o,a),s[0].dtype==="string"){let c=s.map(x=>{let v=k.sizeFromShape(x.shape.slice(a));return yr({inputs:{x},backend:n,attrs:{shape:[-1,v]}})}),m=c.map(x=>({vals:n.readSync(x.dataId),shape:x.shape}));r=M.computeOutShape(c.map(x=>x.shape),1);let f=c[0].shape[0]===1,g=qT(m,r,t[0].dtype,f),y=M.computeOutShape(s.map(x=>x.shape),a);i.shape=y;let A=n.dataIdMap.get(i.dataId);return A.stringBytes=M.fromStringArrayToUint8(g),c.forEach(x=>n.disposeData(x.dataId)),i}let l=k.sizeFromShape(s[0].shape.slice(0,a)),u=0,d=s.map(c=>{let m=k.sizeFromShape(c.shape.slice(a));return u+=m,m}),h=s.map(c=>n.typedArrayFromHeap(c)),p=n.typedArrayFromHeap(i);for(let c=0;c`cumsum does not support ${r.dtype} tensors in the WASM backend`);let u=M.getAxesPermutation([s],l),d=r;u!==null&&(d=Q0({inputs:{x:r},attrs:{perm:u},backend:n}));let h=M.getInnerMostAxes(1,l)[0];M.assertAxesAreInnerMostDims("cumsum",[h],l);let p=n.makeOutput(d.shape,d.dtype),c=d.shape[h],m=n.dataIdMap.get(d.dataId).id,f=n.dataIdMap.get(p.dataId).id;TC(m,i?1:0,o?1:0,c,f,na[r.dtype]);let g=p;if(u!==null){let y=M.getUndoAxesPermutation(u);g=Q0({inputs:{x:p},attrs:{perm:y},backend:n}),n.disposeData(d.dataId),n.disposeData(p.dataId)}return g}var A5e={kernelName:rl,backendName:"wasm",setupFunc:g5e,kernelFunc:y5e},EC;function x5e(e){EC=e.wasm.cwrap(Rd,null,["number","number","number","array","number","array","array","number","number"])}function b5e(e){let{backend:t,inputs:n,attrs:a}=e,{x:r}=n,{blockSize:s,dataFormat:i}=a;k.assert(s>1,()=>`blockSize should be > 1 for depthToSpace, but was: ${s}`);let o=r.shape[0],l=i==="NHWC"?r.shape[1]:r.shape[2],u=i==="NHWC"?r.shape[2]:r.shape[3],d=i==="NHWC"?r.shape[3]:r.shape[1],h=l*s,p=u*s,c=d/(s*s),m=i==="NHWC"?[o,h,p,c]:[o,c,h,p],f=t.makeOutput(m,"float32"),g=t.dataIdMap.get(r.dataId).id,y=new Uint8Array(new Int32Array(k.computeStrides(r.shape)).buffer),A=new Uint8Array(new Int32Array(m).buffer),x=new Uint8Array(new Int32Array(k.computeStrides(m)).buffer),v=t.dataIdMap.get(f.dataId).id;return EC(g,s,i==="NHWC"?1:0,y,r.shape.length-1,A,x,m.length,v),f}var v5e={kernelName:Rd,backendName:"wasm",setupFunc:x5e,kernelFunc:b5e},CC;function w5e(e){CC=e.wasm.cwrap(sl,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function k5e(e){let{inputs:t,attrs:n,backend:a}=e,{x:r,filter:s}=t,i=a.dataIdMap.get(r.dataId).id,o=a.dataIdMap.get(s.dataId).id,{strides:l,dilations:u,pad:d,dimRoundingMode:h}=n,p=u==null?[1,1]:u,c=M.computeConv2DInfo(r.shape,s.shape,l,p,d,h,!0),m=c.filterHeight,f=c.filterWidth,g=c.padInfo.top,y=c.padInfo.right,A=c.padInfo.bottom,x=c.padInfo.left,v=c.dilationHeight,b=c.dilationWidth,w=c.strideHeight,I=c.strideWidth,T=c.inChannels,C=c.outChannels,z=c.padInfo.type==="SAME"?1:0;if(c.dataFormat!=="channelsLast")throw new Error(`wasm backend DepthwiseConv2dNative does not support dataFormat:'${c.dataFormat}'. Please use 'channelsLast'.`);let $=a.makeOutput(c.outShape,"float32"),S=a.dataIdMap.get($.dataId).id;return CC(i,r.shape[0],r.shape[1],r.shape[2],o,m,f,g,y,A,x,z,v,b,w,I,T,C,S),$}var I5e={kernelName:sl,backendName:"wasm",setupFunc:w5e,kernelFunc:k5e},S5e=!1,N5e=jn(ol,S5e,"bool"),T5e=Un(Ei);function mb(e){let{inputs:t,attrs:n,backend:a}=e,{input:r}=t,{dim:s}=n,i=r.shape.length,o=r.shape.slice(),l=s;return s<0&&(k.assert(-(i+1)<=s,()=>`Axis must be in the interval [${-(i+1)}, ${i}]`),l=i+s+1),o.splice(l,0,1),yr({inputs:{x:r},backend:a,attrs:{shape:o}})}var E5e={kernelName:Dd,backendName:"wasm",kernelFunc:mb};function C5e(e){let{attrs:{shape:t,value:n,dtype:a},backend:r}=e,s=r.makeOutput(t,a);return r.typedArrayFromHeap(s).fill(n),s}var M5e={kernelName:Qc,backendName:"wasm",kernelFunc:C5e},MC;function $5e(e){MC=e.wasm.cwrap(_d,null,["number","number","number","number","number","number"])}function R5e(e){let{inputs:t,backend:n}=e,{image:a}=t,r=n.makeOutput(a.shape,a.dtype),s=n.dataIdMap.get(a.dataId).id,i=n.dataIdMap.get(r.dataId).id,[o,l,u,d]=a.shape;return MC(s,o,l,u,d,i),r}var F5e={kernelName:_d,backendName:"wasm",kernelFunc:R5e,setupFunc:$5e},O5e=Un(Ci),D5e=!1,_5e=jn(ul,D5e),$C;function z5e(e){$C=e.wasm.cwrap(dl,null,["number","number","number","number","number","number","number"])}function P5e(e){let{backend:t,inputs:n,attrs:a}=e,{varianceEpsilon:r}=a,{x:s,mean:i,variance:o,offset:l,scale:u}=n,d=t.dataIdMap.get(s.dataId).id,h=t.dataIdMap.get(i.dataId).id,p=t.dataIdMap.get(o.dataId).id,c=l!=null?t.dataIdMap.get(l.dataId).id:0,m=u!=null?t.dataIdMap.get(u.dataId).id:0,f=t.makeOutput(s.shape,s.dtype);if(k.sizeFromShape(s.shape)===0)return f;let g=t.dataIdMap.get(f.dataId).id;return $C(d,h,p,c,m,r,g),f}var L5e={kernelName:dl,backendName:"wasm",setupFunc:z5e,kernelFunc:P5e},RC;function W5e(e){RC=e.wasm.cwrap(Wl,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 B5e(e){let{inputs:t,attrs:n,backend:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:d,dataFormat:h,dimRoundingMode:p,activation:c,leakyreluAlpha:m}=n,f=M.computeConv2DInfo(r.shape,s.shape,l,d,u,p),g=gp[c];if(g==null)throw new Error(`${c} activation not yet supported for FusedConv2D in the wasm backend.`);let y=a.dataIdMap.get(r.dataId).id,A=a.dataIdMap.get(s.dataId).id,x=f.outChannels,v=0;if(i!=null){let te=a.dataIdMap.get(i.dataId);if(te.shape.length!==1)throw new Error(`FusedConv2D only supports rank-1 bias but got rank ${te.shape.length}.`);if(te.shape[0]!==x)throw new Error(`FusedConv2D bias shape (${te.shape}) does not match the number of output channels (${x})`);v=te.id}let b=f.filterHeight,w=f.filterWidth,I=f.padInfo.top,T=f.padInfo.right,C=f.padInfo.bottom,z=f.padInfo.left,$=f.dilationHeight,S=f.dilationWidth,D=f.strideHeight,_=f.strideWidth,W=f.inChannels,X=f.padInfo.type==="SAME"?1:0,q=f.batchSize,Q=f.inHeight,ee=f.inWidth;if(h!=="NHWC")throw new Error(`wasm backend FusedConv2D does not support dataFormat:'${h}'. Please use 'NHWC'.`);let ie=a.makeOutput(f.outShape,"float32"),ae=a.dataIdMap.get(ie.dataId).id,de=o==null?0:a.dataIdMap.get(o.dataId).id;return RC(y,q,Q,ee,A,b,w,v,I,T,C,z,X,$,S,D,_,W,x,g,de,m||0,ae),ie}var V5e={kernelName:Wl,backendName:"wasm",setupFunc:W5e,kernelFunc:B5e},FC;function U5e(e){FC=e.wasm.cwrap(Bl,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 j5e(e){let{inputs:t,attrs:n,backend:a}=e,{x:r,filter:s,bias:i,preluActivationWeights:o}=t,{strides:l,pad:u,dilations:d,dataFormat:h,dimRoundingMode:p,activation:c,leakyreluAlpha:m}=n,f=M.computeConv2DInfo(r.shape,s.shape,l,d,u,p,!0),g=gp[c];if(g==null)throw new Error(`${c} activation not yet supported for FusedDepthwiseConv2D in the wasm backend.`);let y=a.dataIdMap.get(r.dataId).id,A=a.dataIdMap.get(s.dataId).id,x=f.outChannels,v=0;if(i!=null){let te=a.dataIdMap.get(i.dataId);if(te.shape.length!==1)throw new Error(`FusedDepthwiseConv2D only supports rank-1 bias but got rank ${te.shape.length}.`);if(te.shape[0]!==x)throw new Error(`FusedDepthwiseConv2D bias shape (${te.shape}) does not match the number of output channels (${x})`);v=te.id}let b=f.filterHeight,w=f.filterWidth,I=f.padInfo.top,T=f.padInfo.right,C=f.padInfo.bottom,z=f.padInfo.left,$=f.dilationHeight,S=f.dilationWidth,D=f.strideHeight,_=f.strideWidth,W=f.inChannels,X=f.padInfo.type==="SAME"?1:0,q=f.batchSize,Q=f.inHeight,ee=f.inWidth;if(h!=="NHWC")throw new Error(`wasm backend FusedDepthwiseConv2D does not support dataFormat:'${h}'. Please use 'NHWC'.`);let ie=a.makeOutput(f.outShape,"float32"),ae=a.dataIdMap.get(ie.dataId).id,de=o==null?0:a.dataIdMap.get(o.dataId).id;return FC(y,q,Q,ee,A,b,w,v,I,T,C,z,X,$,S,D,_,W,x,g,de,m||0,ae),ie}var H5e={kernelName:Bl,backendName:"wasm",setupFunc:U5e,kernelFunc:j5e},OC;function G5e(e){OC=e.wasm.cwrap(Pd,null,["number","number","number","number","number","number","array","number"])}function q5e(e){let{backend:t,inputs:n}=e,{params:a,indices:r}=n,[s,i,o,l]=S4.prepareAndValidate(a,r),u=t.makeOutput(s,a.dtype);if(i===0)return u;let d=r.shape,h=d[d.length-1],p=t.dataIdMap.get(a.dataId).id,c=t.dataIdMap.get(r.dataId).id,m=new Uint8Array(new Int32Array(l).buffer),f=t.dataIdMap.get(u.dataId).id;return OC(p,na[a.dtype],c,i,h,o,m,f),u}var K5e={kernelName:Pd,backendName:"wasm",setupFunc:G5e,kernelFunc:q5e},DC;function X5e(e){DC=e.wasm.cwrap("Gather",null,["number","number","array","number","number","number","array","number"])}function Z5e(e){let{backend:t,inputs:n,attrs:a}=e,{x:r,indices:s}=n,{axis:i,batchDims:o}=a,l=k.parseAxisParam(i,r.shape)[0],u=M.segment_util.collectGatherOpShapeInfo(r,s,l,o),d=yr({inputs:{x:r},attrs:{shape:[u.batchSize,u.outerSize,u.dimSize,u.sliceSize]},backend:t}),h=k.sizeFromShape(s.shape),p=yr({inputs:{x:s},attrs:{shape:[u.batchSize,h/u.batchSize]},backend:t}),c=[u.batchSize,u.outerSize,h/u.batchSize,u.sliceSize],m=t.makeOutput(c,r.dtype);if(k.sizeFromShape(r.shape)===0)return m;let f=d.shape.length-1,g=t.dataIdMap.get(d.dataId).id,y=t.dataIdMap.get(p.dataId).id,A=t.dataIdMap.get(m.dataId).id,x=new Uint8Array(new Int32Array(k.computeStrides(d.shape)).buffer),v=new Uint8Array(new Int32Array(k.computeStrides(c)).buffer);return DC(g,na[r.dtype],x,f,y,u.batchSize,v,A),t.disposeData(d.dataId),t.disposeData(p.dataId),m.shape=u.outputShape,m}var Y5e={kernelName:zd,backendName:"wasm",setupFunc:X5e,kernelFunc:Z5e},J5e=!1,Q5e=jn(hl,J5e,"bool"),ebe=!1,tbe=jn(Mi,ebe,"bool"),_C;function nbe(e){_C=e.wasm.cwrap(cl,null,["number","number","number"])}function abe(e){let{inputs:{x:t},attrs:{alpha:n},backend:a}=e,r=a.dataIdMap.get(t.dataId).id,s=a.makeOutput(t.shape,t.dtype);if(k.sizeFromShape(t.shape)!==0){let i=a.dataIdMap.get(s.dataId).id;_C(r,n,i)}return s}var rbe={kernelName:cl,backendName:"wasm",setupFunc:nbe,kernelFunc:abe},sbe=!1,ibe=jn(fl,sbe,"bool"),obe=!1,lbe=jn(ml,obe,"bool"),ube=Un($i),dbe=!1,hbe=jn(Ud,dbe,"bool"),zC;function pbe(e){zC=e.wasm.cwrap(gl,null,["number, number, number"])}function cbe(e){let{backend:t,inputs:n,attrs:a}=e,{reductionIndices:r,keepDims:s}=a,{x:i}=n,o=t.dataIdMap.get(i.dataId).id,l=i,{transposed:u,axes:d,originalAxes:h,inputWasTransposed:p}=ti(i,r,t);if(p){let A=t.dataIdMap.get(u.dataId).id;l=u,o=A}let c=l.shape.length;M.assertAxesAreInnerMostDims("max",d,c);let[m,f]=M.computeOutAndReduceShapes(l.shape,d),g=k.sizeFromShape(f),y=t.makeOutput(m,i.dtype);if(k.sizeFromShape(l.shape)!==0){let A=t.dataIdMap.get(y.dataId).id;zC(o,g,A)}if(p&&t.disposeData(u.dataId),s){let A=M.expandShapeToKeepDim(y.shape,h);y.shape=A}return y}var fbe={kernelName:gl,backendName:"wasm",setupFunc:pbe,kernelFunc:cbe},mbe=!1,gbe=jn(Ri,mbe),PC;function ybe(e){PC=e.wasm.cwrap(yl,null,["number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number","number"])}function Abe(e){let{inputs:t,attrs:n,backend:a}=e,r=t.x,s=a.dataIdMap.get(r.dataId).id,{filterSize:i,strides:o,pad:l,dimRoundingMode:u}=n,d=M.computePool2DInfo(r.shape,i,o,1,l,u),h=d.filterHeight,p=d.filterWidth,c=d.padInfo.top,m=d.padInfo.right,f=d.padInfo.bottom,g=d.padInfo.left,y=d.dilationHeight,A=d.dilationWidth,x=d.strideHeight,v=d.strideWidth,b=d.inChannels,w=d.outChannels;if(d.dataFormat!=="channelsLast")throw new Error(`wasm backend does not support dataFormat:'${d.dataFormat}'. Please use 'channelsLast'.`);let I=a.makeOutput(d.outShape,"float32"),T=a.dataIdMap.get(I.dataId).id;return PC(s,r.shape[0],r.shape[1],r.shape[2],h,p,c,m,f,g,y,A,x,v,b,w,T),I}var xbe={kernelName:yl,backendName:"wasm",setupFunc:ybe,kernelFunc:Abe},LC;function bbe(e){LC=e.wasm.cwrap(Al,null,["number, number, number"])}function vbe(e){let{backend:t,inputs:n,attrs:a}=e,{axis:r,keepDims:s}=a,{x:i}=n,o=t.dataIdMap.get(i.dataId).id,l=o,u=i,{transposed:d,axes:h,originalAxes:p,inputWasTransposed:c}=ti(i,r,t),m=h;if(c){let v=t.dataIdMap.get(d.dataId).id;v!==o&&(u=d,l=v,m=M.getInnerMostAxes(m.length,u.shape.length))}M.assertAxesAreInnerMostDims("mean",m,u.shape.length);let[f,g]=M.computeOutAndReduceShapes(u.shape,m),y=k.sizeFromShape(g),A=u;u.dtype!=="float32"&&(A=em({backend:t,inputs:{x:u},attrs:{dtype:"float32"}}),l=t.dataIdMap.get(A.dataId).id);let x=t.makeOutput(f,"float32");if(k.sizeFromShape(u.shape)!==0){let v=t.dataIdMap.get(x.dataId).id;LC(l,y,v)}if(c&&t.disposeData(d.dataId),s){let v=M.expandShapeToKeepDim(x.shape,p);x.shape=v}return u.dtype!=="float32"&&t.disposeData(A.dataId),x}var wbe={kernelName:Al,backendName:"wasm",setupFunc:bbe,kernelFunc:vbe},WC;function kbe(e){WC=e.wasm.cwrap(xl,null,["number, number, number"])}function Ibe(e){let{backend:t,inputs:n,attrs:a}=e,{axis:r,keepDims:s}=a,{x:i}=n,o=t.dataIdMap.get(i.dataId).id,l=o,u=i,{transposed:d,axes:h,originalAxes:p,inputWasTransposed:c}=ti(i,r,t);if(c){let x=t.dataIdMap.get(d.dataId).id;x!==o&&(u=d,l=x)}let m=u.shape.length;M.assertAxesAreInnerMostDims("min",h,m);let[f,g]=M.computeOutAndReduceShapes(u.shape,h),y=k.sizeFromShape(g),A=t.makeOutput(f,u.dtype);if(k.sizeFromShape(u.shape)!==0){let x=t.dataIdMap.get(A.dataId).id;WC(l,y,x)}if(c&&t.disposeData(d.dataId),s){let x=M.expandShapeToKeepDim(A.shape,p);A.shape=x}return A}var Sbe={kernelName:xl,backendName:"wasm",setupFunc:kbe,kernelFunc:Ibe},Nbe=!1,Tbe=jn(Fi,Nbe),gb;(function(e){e[e.reflect=0]="reflect",e[e.symmetric=1]="symmetric"})(gb||(gb={}));var BC;function Ebe(e){BC=e.wasm.cwrap(bl,null,["number","array","number","number","array","array","number","number"])}function Cbe(e){let{inputs:{x:t},backend:n,attrs:{paddings:a,mode:r}}=e,s=a.map((m,f)=>m[0]+t.shape[f]+m[1]),i=n.dataIdMap.get(t.dataId).id,o=n.makeOutput(s,t.dtype),l=n.dataIdMap.get(o.dataId).id,u=new Uint8Array(new Int32Array(t.shape).buffer),d=a.map(m=>m[0]),h=a.map(m=>m[1]),p=new Uint8Array(new Int32Array(d).buffer),c=new Uint8Array(new Int32Array(h).buffer);return BC(i,u,t.shape.length,na[t.dtype],p,c,gb[r],l),o}var Mbe={kernelName:bl,backendName:"wasm",kernelFunc:Cbe,setupFunc:Ebe},$be=!0,Rbe=jn(Oi,$be),Fbe=Un(Hd);function yb(e,t){let n=new Int32Array(e.wasm.HEAPU8.buffer,t,4),a=n[0],r=n[1],s=n[2],i=n[3];return e.wasm._free(t),{pSelectedIndices:a,selectedSize:r,pSelectedScores:s,pValidOutputs:i}}var VC;function Obe(e){VC=e.wasm.cwrap(Gd,"number",["number","number","number","number","number"])}function Dbe(e){let{backend:t,inputs:n,attrs:a}=e,{iouThreshold:r,maxOutputSize:s,scoreThreshold:i}=a,{boxes:o,scores:l}=n,u=t.dataIdMap.get(o.dataId).id,d=t.dataIdMap.get(l.dataId).id,h=VC(u,d,s,r,i),{pSelectedIndices:p,selectedSize:c,pSelectedScores:m,pValidOutputs:f}=yb(t,h);return t.wasm._free(m),t.wasm._free(f),t.makeOutput([c],"int32",p)}var _be={kernelName:Gd,backendName:"wasm",setupFunc:Obe,kernelFunc:Dbe},UC;function zbe(e){UC=e.wasm.cwrap(qd,"number",["number","number","number","number","number","bool"])}function Pbe(e){let{backend:t,inputs:n,attrs:a}=e,{iouThreshold:r,maxOutputSize:s,scoreThreshold:i,padToMaxOutputSize:o}=a,{boxes:l,scores:u}=n,d=t.dataIdMap.get(l.dataId).id,h=t.dataIdMap.get(u.dataId).id,p=UC(d,h,s,r,i,o),{pSelectedIndices:c,selectedSize:m,pSelectedScores:f,pValidOutputs:g}=yb(t,p);t.wasm._free(f);let y=t.makeOutput([m],"int32",c),A=t.makeOutput([],"int32",g);return[y,A]}var Lbe={kernelName:qd,backendName:"wasm",setupFunc:zbe,kernelFunc:Pbe},jC;function Wbe(e){jC=e.wasm.cwrap(Kd,"number",["number","number","number","number","number","number"])}function Bbe(e){let{backend:t,inputs:n,attrs:a}=e,{iouThreshold:r,maxOutputSize:s,scoreThreshold:i,softNmsSigma:o}=a,{boxes:l,scores:u}=n,d=t.dataIdMap.get(l.dataId).id,h=t.dataIdMap.get(u.dataId).id,p=jC(d,h,s,r,i,o),{pSelectedIndices:c,selectedSize:m,pSelectedScores:f,pValidOutputs:g}=yb(t,p);t.wasm._free(g);let y=t.makeOutput([m],"int32",c),A=t.makeOutput([m],"float32",f);return[y,A]}var Vbe={kernelName:Kd,backendName:"wasm",setupFunc:Wbe,kernelFunc:Bbe},Ube=!1,jbe=jn(vl,Ube,"bool"),HC;function Hbe(e){HC=e.wasm.cwrap(wl,null,["number","number","number","number","number"])}function Gbe(e){let{inputs:t,backend:n,attrs:a}=e,{indices:r}=t,{depth:s,onValue:i,offValue:o}=a,l=n.makeOutput([...r.shape,s],"int32"),u=n.dataIdMap.get(l.dataId).id,d=n.dataIdMap.get(r.dataId).id;return HC(d,s,i,o,u),l}var qbe={kernelName:wl,backendName:"wasm",setupFunc:Hbe,kernelFunc:Gbe};function Kbe(e){let{inputs:{x:t},backend:n}=e,a=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(a).fill(1),a}var Xbe={kernelName:Xd,backendName:"wasm",kernelFunc:Kbe};function Zbe(e){let{inputs:t,backend:n,attrs:a}=e,{axis:r}=a;if(t.length===1)return mb({inputs:{input:t[0]},backend:n,attrs:{dim:r}});let s=t[0].shape,i=t[0].dtype;t.forEach(d=>{k.assertShapesMatch(s,d.shape,"All tensors passed to stack must have matching shapes"),k.assert(i===d.dtype,()=>"All tensors passed to stack must have matching dtypes")});let o=[],l=t.map(d=>{let h=mb({inputs:{input:d},backend:n,attrs:{dim:r}});return o.push(h),h}),u=kC({inputs:l,backend:n,attrs:{axis:r}});return o.forEach(d=>n.disposeData(d.dataId)),u}var Ybe={kernelName:Zd,backendName:"wasm",kernelFunc:Zbe},GC;function Jbe(e){GC=e.wasm.cwrap(kl,null,["number","array","number","number","array","array","number","number"])}function Qbe(e){let{inputs:{x:t},backend:n,attrs:{paddings:a,constantValue:r}}=e,s=a.map((m,f)=>m[0]+t.shape[f]+m[1]),i=n.dataIdMap.get(t.dataId).id,o=n.makeOutput(s,t.dtype),l=n.dataIdMap.get(o.dataId).id,u=new Uint8Array(new Int32Array(t.shape).buffer),d=a.map(m=>m[0]),h=a.map(m=>m[1]),p=new Uint8Array(new Int32Array(d).buffer),c=new Uint8Array(new Int32Array(h).buffer);return GC(i,u,t.shape.length,na[t.dtype],p,c,r,l),o}var e3e={kernelName:kl,backendName:"wasm",kernelFunc:Qbe,setupFunc:Jbe},t3e=!1,n3e=jn(Il,t3e),qC;function a3e(e){qC=e.wasm.cwrap(Sl,null,["number","number","number"])}function r3e(e){let{inputs:t,backend:n}=e,{x:a,alpha:r}=t,s=n.dataIdMap.get(a.dataId).id,i=n.dataIdMap.get(r.dataId).id,o=n.makeOutput(a.shape,"float32"),l=n.dataIdMap.get(o.dataId).id;return qC(s,i,l),o}var s3e={kernelName:Sl,backendName:"wasm",setupFunc:a3e,kernelFunc:r3e},KC;function i3e(e){KC=e.wasm.cwrap(Yd,null,["number","number","number","number"])}function o3e(e){let{backend:t,inputs:n,attrs:a}=e,{axis:r,keepDims:s}=a,{x:i}=n,o=t.dataIdMap.get(i.dataId).id,l=o,u=i,{transposed:d,axes:h,originalAxes:p,inputWasTransposed:c}=ti(i,r,t),m=h;if(c){let x=t.dataIdMap.get(d.dataId).id;x!==o&&(u=d,l=x,m=M.getInnerMostAxes(m.length,u.shape.length))}M.assertAxesAreInnerMostDims("prod",m,u.shape.length);let[f,g]=M.computeOutAndReduceShapes(u.shape,m),y=k.sizeFromShape(g),A=t.makeOutput(f,u.dtype);if(k.sizeFromShape(u.shape)!==0){let x=t.dataIdMap.get(A.dataId).id;KC(l,y,na[A.dtype],x)}if(c&&t.disposeData(d.dataId),s){let x=M.expandShapeToKeepDim(A.shape,p);A.shape=x}return A}var l3e={kernelName:Yd,backendName:"wasm",setupFunc:i3e,kernelFunc:o3e},u3e=e=>{let{backend:t,attrs:n}=e,{start:a,stop:r,step:s,dtype:i}=n,o=iE(a,r,s,i),l=t.makeOutput([o.length],i);return t.typedArrayFromHeap(l).set(o),l},d3e={kernelName:rf,backendName:"wasm",kernelFunc:u3e},h3e=!0,p3e=jn(il,h3e),c3e=Un(Nl),f3e=Un(El),XC;function m3e(e){XC=e.wasm.cwrap(Tl,null,["number","number","number","number","number","number","number","number","number","number"])}function g3e(e){let{backend:t,inputs:n,attrs:a}=e,{images:r}=n,{alignCorners:s,halfPixelCenters:i,size:o}=a,[l,u]=o,[d,h,p,c]=r.shape,m=[d,l,u,c],f=t.dataIdMap.get(r.dataId),g;f.dtype!=="float32"&&(g=em({backend:t,inputs:{x:r},attrs:{dtype:"float32"}}),f=t.dataIdMap.get(g.dataId));let y=f.id,A=t.makeOutput(m,"float32");if(k.sizeFromShape(r.shape)===0)return A;let x=t.dataIdMap.get(A.dataId).id;return XC(y,d,h,p,c,l,u,s?1:0,i?1:0,x),g!=null&&t.disposeData(g.dataId),A}var y3e={kernelName:Tl,backendName:"wasm",setupFunc:m3e,kernelFunc:g3e},ZC;function A3e(e){ZC=e.wasm.cwrap(Cl,null,["number","array","number","array","number","number"])}function x3e(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,{dims:s}=a,i=k.parseAxisParam(s,r.shape);if(r.shape.length===0)return J0({inputs:{x:r},backend:n});let o=n.makeOutput(r.shape,r.dtype),l=n.dataIdMap.get(r.dataId).id,u=n.dataIdMap.get(o.dataId).id,d=new Uint8Array(new Int32Array(i).buffer),h=new Uint8Array(new Int32Array(r.shape).buffer);ZC(l,d,i.length,h,r.shape.length,u);let p=yr({inputs:{x:o},attrs:{shape:r.shape},backend:n});return n.disposeData(o.dataId),p}var b3e={kernelName:Cl,backendName:"wasm",kernelFunc:x3e,setupFunc:A3e},YC;function v3e(e){YC=e.wasm.cwrap(ch,null,["number","number","number","number","number","number","number","number","array","number","number"])}function w3e(e){let{inputs:t,backend:n,attrs:a}=e,{image:r}=t,{radians:s,fillValue:i,center:o}=a,l=n.makeOutput(r.shape,r.dtype),u=n.dataIdMap.get(r.dataId).id,d=n.dataIdMap.get(l.dataId).id,[h,p,c,m]=r.shape,[f,g]=M.getImageCenter(o,p,c),y=i===0,A=255,x=typeof i=="number"?[i,i,i,y?0:A]:[...i,A],v=new Uint8Array(new Int32Array(x).buffer);return YC(u,h,p,c,m,s,f,g,v,x.length,d),l}var k3e={kernelName:ch,backendName:"wasm",kernelFunc:w3e,setupFunc:v3e},I3e=Un(Ml),S3e=Un(Di),JC;function N3e(e){JC=e.wasm.cwrap(eh,null,["number","number","number","number","number","number","array","number","number"])}function T3e(e){let{backend:t,inputs:n,attrs:a}=e,{indices:r,updates:s}=n,{shape:i}=a,o=t.makeOutput(i,s.dtype);if(k.sizeFromShape(i)===0)return o;let{sliceRank:l,numUpdates:u,sliceSize:d,strides:h,outputSize:p}=T4.calculateShapes(s,r,i),c=t.dataIdMap.get(r.dataId).id,m=t.dataIdMap.get(s.dataId).id,f=new Uint8Array(new Int32Array(h).buffer),g=t.dataIdMap.get(o.dataId).id;return JC(c,m,na[s.dtype],l,u,d,f,p,g),o}var E3e={kernelName:eh,backendName:"wasm",setupFunc:N3e,kernelFunc:T3e},QC;function C3e(e){QC=e.wasm.cwrap("SelectV2",null,["number","number","number","number","number"])}function M3e(e){let{inputs:t,backend:n}=e,{condition:a,t:r,e:s}=t,i=n.dataIdMap.get(a.dataId).id,o=n.dataIdMap.get(r.dataId).id,l=n.dataIdMap.get(s.dataId).id,u=n.makeOutput(r.shape,r.dtype),d=n.dataIdMap.get(u.dataId).id,h=a.shape.length,p=r.shape.length,c=h===0||h>1||p===1?1:k.sizeFromShape(r.shape.slice(1));return QC(i,o,l,c,d),u}var $3e={kernelName:th,backendName:"wasm",kernelFunc:M3e,setupFunc:C3e},eM;function R3e(e){eM=e.wasm.cwrap(Rl,null,["number","number"])}function F3e(e){let{backend:t,inputs:{x:n}}=e,a=t.dataIdMap.get(n.dataId).id,r=t.makeOutput(n.shape,n.dtype),s=t.dataIdMap.get(r.dataId).id;return k.sizeFromShape(r.shape)===0||eM(a,s),r}var O3e={kernelName:"Sigmoid",backendName:"wasm",setupFunc:R3e,kernelFunc:F3e},D3e=Un($l);function tm(e){let{inputs:{x:t},attrs:{begin:n,size:a},backend:r}=e,[s,i]=Cn.parseSliceParams(t,n,a),o=Cn.isSliceContinous(t.shape,s,i),l=r.readSync(t.dataId),u=r.makeOutput(i,t.dtype),d=k.computeStrides(t.shape),h=r.dataIdMap.get(u.dataId);if(o){let m=Cn.computeFlatOffset(s,d);return t.dtype==="string"?h.stringBytes=l.slice(m,m+k.sizeFromShape(i)):r.typedArrayFromHeap(u).set(l.subarray(m,m+k.sizeFromShape(i))),u}if(t.dtype==="string"){let m=sb(l,s,i,t.shape,t.dtype);return h.stringBytes=m,u}let p=r.typedArrayFromHeap(u),c=t.shape.length;if(c===2)_3e(l,d[0],p,s,i);else if(c===3)z3e(l,d[0],d[1],p,s,i);else if(c===4)P3e(l,d[0],d[1],d[2],p,s,i);else{let m=sb(l,s,i,t.shape,t.dtype);p.set(m)}return u}function _3e(e,t,n,a,r){let s=0,i=a[0],o=a[1],l=i+r[0];for(let u=i;u{let p=[...d];p[o]=h;let c=tm({inputs:{x:r},attrs:{begin:u,size:p},backend:a});return u[o]+=h,c})}var j3e={kernelName:oh,backendName:"wasm",kernelFunc:U3e},H3e=Un(Fl),G3e=Un(lf),q3e=!0,K3e=jn(_i,q3e),nM;function X3e(e){nM=e.wasm.cwrap(Li,null,["number","number","number"])}function Z3e(e){let{backend:t,inputs:n,attrs:a}=e,{alpha:r}=a,{x:s}=n,i=t.dataIdMap.get(s.dataId).id,o=t.makeOutput(s.shape,s.dtype),l=t.dataIdMap.get(o.dataId).id;return nM(i,r,l),o}var Y3e={kernelName:Li,backendName:"wasm",setupFunc:X3e,kernelFunc:Z3e},aM;function J3e(e){aM=e.wasm.cwrap(lh,null,["number","array","number","array","array","array","array","array","number","number"])}function Q3e(e){let{backend:t,inputs:n,attrs:a}=e,{x:r}=n,{begin:s,end:i,strides:o}=a;o==null&&(o=new Array(s.length));let{beginMask:l,endMask:u,ellipsisMask:d,newAxisMask:h,shrinkAxisMask:p}=a,c=M.slice_util.maskToAxes(d);if(c.length>1)throw new Error("Multiple ellipses in slice is not allowed.");if(d!==0&&h!==0)throw new Error("Using both ellipsisMask and newAxisMask is not yet supported.");if(d!==0&&p!==0)throw new Error("Using both ellipsisMask and shrinkAxisMask is not yet supported.");let m=r.shape.length-s.length,f=M.slice_util.maskToAxes(h),g=r.shape.slice();f.forEach(z=>{s[z]=0,i[z]=1,g.splice(z,0,1)});let y=yr({inputs:{x:r},attrs:{shape:g},backend:t}),{begin:A,end:x,strides:v}=M.slice_util.getNormalizedAxes(y.shape,c,m,s,i,o,l,u,d);s=A,i=x,o=v;let b=M.slice_util.maskToAxes(p);b.forEach(z=>{i[z]=s[z]+1,o[z]=1});let w=M.slice_util.computeOutShape(s,i,o),I=w.filter((z,$)=>b.indexOf($)===-1);if(o.every(z=>z===1)){let z=tm({inputs:{x:y},attrs:{begin:s,size:w},backend:t});t.disposeData(y.dataId);let $=yr({inputs:{x:z},attrs:{shape:I},backend:t});return t.disposeData(z.dataId),$}let T=t.makeOutput(I,"float32");if(!I.some(z=>z===0)){let z=t.dataIdMap.get(y.dataId).id,$=new Uint8Array(new Int32Array(k.computeStrides(y.shape)).buffer),S=new Uint8Array(new Int32Array(s).buffer),D=new Uint8Array(new Int32Array(i).buffer),_=new Uint8Array(new Int32Array(o).buffer),W=new Uint8Array(new Int32Array(I).buffer),X=new Uint8Array(new Int32Array(k.computeStrides(I)).buffer),q=t.dataIdMap.get(T.dataId).id;aM(z,$,y.shape.length,S,D,_,W,X,I.length,q)}t.disposeData(y.dataId);let C=yr({inputs:{x:T},attrs:{shape:I},backend:t});return t.disposeData(T.dataId),C}var eve={kernelName:lh,backendName:"wasm",setupFunc:J3e,kernelFunc:Q3e},tve=!0,nve=jn(zi,tve),rM;function ave(e){rM=e.wasm.cwrap(Ol,null,["number, number, number"])}function rve(e){let{backend:t,inputs:n,attrs:a}=e,{axis:r,keepDims:s}=a,{x:i}=n,o=t.dataIdMap.get(i.dataId).id,l=o,u=i,{transposed:d,axes:h,originalAxes:p,inputWasTransposed:c}=ti(i,r,t),m=h;if(c){let x=t.dataIdMap.get(d.dataId).id;x!==o&&(u=d,l=x,m=M.getInnerMostAxes(m.length,u.shape.length))}M.assertAxesAreInnerMostDims("sum",m,u.shape.length);let[f,g]=M.computeOutAndReduceShapes(u.shape,m),y=k.sizeFromShape(g),A=t.makeOutput(f,u.dtype);if(k.sizeFromShape(u.shape)!==0){let x=t.dataIdMap.get(A.dataId).id;rM(l,y,x)}if(c&&t.disposeData(d.dataId),s){let x=M.expandShapeToKeepDim(A.shape,p);A.shape=x}return A}var sve={kernelName:Ol,backendName:"wasm",setupFunc:ave,kernelFunc:rve},ive=Un(_l),ove=Un(zl),sM;function lve(e){sM=e.wasm.cwrap(Pi,null,["number","array","number","array","number","number"])}function uve(e){let{inputs:t,backend:n,attrs:a}=e,{x:r}=t,s=n.dataIdMap.get(r.dataId).id,{reps:i}=a,o=new Array(r.shape.length);for(let p=0;p{let{x:a}=e,{k:r,sorted:s}=n,i=t.dataIdMap.get(a.dataId).id,o=new Uint8Array(new Int32Array(a.shape).buffer),l=a.shape.slice();l[l.length-1]=r;let u=t.makeOutput(l,a.dtype),d=t.dataIdMap.get(u.dataId).id,h=t.makeOutput(l,"int32"),p=t.dataIdMap.get(h.dataId).id;return iM(i,o,a.shape.length,na[a.dtype],r,s,d,p),[u,h]},cve={kernelName:uh,backendName:"wasm",setupFunc:hve,kernelFunc:pve},oM;function fve(e){oM=e.wasm.cwrap(dh,null,["number","number","bool","number","number","number","number","number","number","array","number","number","number","number","number"])}function mve(e){let{backend:t,inputs:n,attrs:a}=e,{image:r,transforms:s}=n,{interpolation:i,fillMode:o,fillValue:l,outputShape:u}=a,[d,h,p,c]=r.shape,[m,f]=u!=null?u:[h,p],g=[d,m,f,c],y=new Uint8Array(new Int32Array(k.computeStrides(r.shape)).buffer),A=t.makeOutput(g,r.dtype),x=t.dataIdMap.get(A.dataId).id,v=t.dataIdMap.get(r.dataId).id,b=t.dataIdMap.get(s.dataId).id,w=i==="nearest"?1:2,I;switch(o){case"constant":I=1;break;case"reflect":I=2;break;case"wrap":I=3;break;case"nearest":I=4;break;default:I=1;break}return oM(v,b,s.shape[0]>1,d,m,f,c,p,h,y,r.shape.length-1,w,I,l,x),A}var gve={kernelName:dh,backendName:"wasm",setupFunc:fve,kernelFunc:mve};function yve(e){let{inputs:t,backend:n,attrs:a}=e,{value:r}=t,{axis:s}=a;s<0&&(s+=r.shape.length);let i=r.shape[s],o=r.shape.length,l=new Array(o-1),u=0;for(let c=0;c({dataId:c,dtype:m,shape:l}))}var Ave={kernelName:hh,backendName:"wasm",kernelFunc:yve};function xve(e){let{inputs:{x:t},backend:n}=e,a=n.makeOutput(t.shape,t.dtype);return n.typedArrayFromHeap(a).fill(0),a}var bve={kernelName:ph,backendName:"wasm",kernelFunc:xve},vve=[Txe,Cxe,Rxe,Wxe,Uxe,Gxe,Xxe,Qxe,e5e,t5e,r5e,s5e,l5e,h5e,p5e,m5e,A5e,v5e,I5e,N5e,T5e,E5e,M5e,F5e,O5e,_5e,Nxe,L5e,V5e,H5e,K5e,Y5e,Q5e,tbe,Fxe,rbe,ibe,lbe,ube,hbe,fbe,gbe,xbe,wbe,Sbe,Tbe,Mbe,Rbe,Fbe,_be,Lbe,Vbe,jbe,qbe,Xbe,Ybe,e3e,n3e,s3e,l3e,d3e,p3e,c3e,f3e,Zxe,y3e,b3e,k3e,S3e,I3e,E3e,$3e,O3e,D3e,L3e,V3e,j3e,H3e,G3e,K3e,Y3e,eve,nve,sve,ive,ove,dve,cve,gve,zxe,Ave,bve];for(let e of vve)iA(e);var Ab=se();Ab.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])));Ab.registerFlag("WASM_HAS_MULTITHREAD_SUPPORT",async()=>{if(Ab.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 lM=qr(SR()),wve='var Module={};function threadPrintErr(){var text=Array.prototype.slice.call(arguments).join(" ");console.error(text)}function threadAlert(){var text=Array.prototype.slice.call(arguments).join(" ");postMessage({cmd:"alert",text:text,threadId:Module["_pthread_self"]()})}var err=threadPrintErr;this.alert=threadAlert;Module["instantiateWasm"]=function(info,receiveInstance){var instance=new WebAssembly.Instance(Module["wasmModule"],info);Module["wasmModule"]=null;receiveInstance(instance);return instance.exports};function moduleLoaded(){}this.onmessage=function(e){try{if(e.data.cmd==="load"){Module["wasmModule"]=e.data.wasmModule;Module["wasmMemory"]=e.data.wasmMemory;Module["buffer"]=Module["wasmMemory"].buffer;Module["ENVIRONMENT_IS_PTHREAD"]=true;if(typeof e.data.urlOrBlob==="string"){importScripts(e.data.urlOrBlob)}else{var objectUrl=URL.createObjectURL(e.data.urlOrBlob);importScripts(objectUrl);URL.revokeObjectURL(objectUrl)}WasmBackendModuleThreadedSimd(Module).then(function(instance){Module=instance;moduleLoaded()})}else if(e.data.cmd==="objectTransfer"){Module["PThread"].receiveObjectTransfer(e.data)}else if(e.data.cmd==="run"){Module["__performance_now_clock_drift"]=performance.now()-e.data.time;Module["__emscripten_thread_init"](e.data.threadInfoStruct,0,0);var max=e.data.stackBase;var top=e.data.stackBase+e.data.stackSize;Module["establishStackSpace"](top,max);Module["_emscripten_tls_init"]();Module["PThread"].receiveObjectTransfer(e.data);Module["PThread"].setThreadStatus(Module["_pthread_self"](),1);try{var result=Module["invokeEntryPoint"](e.data.start_routine,e.data.arg);if(!Module["getNoExitRuntime"]())Module["PThread"].threadExit(result)}catch(ex){if(ex==="Canceled!"){Module["PThread"].threadCancel()}else if(ex!="unwind"){if(ex instanceof Module["ExitStatus"]){if(Module["getNoExitRuntime"]()){}else{Module["PThread"].threadExit(ex.status)}}else{Module["PThread"].threadExit(-2);throw ex}}}}else if(e.data.cmd==="cancel"){if(Module["_pthread_self"]()){Module["PThread"].threadCancel()}}else if(e.data.target==="setimmediate"){}else if(e.data.cmd==="processThreadQueue"){if(Module["_pthread_self"]()){Module["_emscripten_current_thread_process_queued_calls"]()}}else{err("worker.js received unknown command "+e.data.cmd);err(e.data)}}catch(ex){err("worker.js onmessage() captured an uncaught exception: "+ex);if(ex&&ex.stack)err(ex.stack);throw ex}};if(typeof process==="object"&&typeof process.versions==="object"&&typeof process.versions.node==="string"){self={location:{href:__filename}};var onmessage=this.onmessage;var nodeWorkerThreads=require("worker_threads");global.Worker=nodeWorkerThreads.Worker;var parentPort=nodeWorkerThreads.parentPort;parentPort.on("message",function(data){onmessage({data:data})});var nodeFS=require("fs");var nodeRead=function(filename){return nodeFS.readFileSync(filename,"utf8")};function globalEval(x){global.require=require;global.Module=Module;eval.call(null,x)}importScripts=function(f){globalEval(nodeRead(f))};postMessage=function(msg){parentPort.postMessage(msg)};if(typeof performance==="undefined"){performance={now:function(){return Date.now()}}}}',kve=qr(NR()),uM=class extends Wc{constructor(e){super();this.wasm=e,this.dataIdNextNumber=1,this.wasm.tfjs.init(),this.dataIdMap=new f1(this,Ps())}write(e,t,n){let a={id:this.dataIdNextNumber++};return this.move(a,e,t,n,1),a}numDataIds(){return this.dataIdMap.numDataIds()}async time(e){let t=k.now();return e(),{kernelMs:k.now()-t}}move(e,t,n,a,r){let s=this.dataIdNextNumber++;if(a==="string"){let u=t;this.dataIdMap.set(e,{id:s,stringBytes:u,shape:n,dtype:a,memoryOffset:null,refCount:r});return}let i=k.sizeFromShape(n),o=i*k.bytesPerElement(a),l=this.wasm._malloc(o);this.dataIdMap.set(e,{id:s,memoryOffset:l,shape:n,dtype:a,refCount:r}),this.wasm.tfjs.registerTensor(s,i,l),t!=null&&this.wasm.HEAPU8.set(new Uint8Array(t.buffer,t.byteOffset,o),l)}async read(e){return this.readSync(e)}readSync(e){let{memoryOffset:t,dtype:n,shape:a,stringBytes:r}=this.dataIdMap.get(e);if(n==="string")return r;let s=this.wasm.HEAPU8.slice(t,t+k.sizeFromShape(a)*k.bytesPerElement(n));return Nve(s.buffer,n)}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 a;if(n==null)a=this.write(null,e,t);else{let r=this.dataIdNextNumber++;a={id:r},this.dataIdMap.set(a,{id:r,memoryOffset:n,shape:e,dtype:t,refCount:1});let s=k.sizeFromShape(e);this.wasm.tfjs.registerTensor(r,s,n)}return{dataId:a,shape:e,dtype:t}}typedArrayFromHeap({shape:e,dtype:t,dataId:n}){let a=this.wasm.HEAPU8.buffer,{memoryOffset:r}=this.dataIdMap.get(n),s=k.sizeFromShape(e);switch(t){case"float32":return new Float32Array(a,r,s);case"int32":return new Int32Array(a,r,s);case"bool":return new Uint8Array(a,r,s);default:throw new Error(`Unknown dtype ${t}`)}}};function Ive(e){return(t,n)=>(k.fetch(e,{credentials:"same-origin"}).then(a=>{a.ok||t.env.a(`failed to load wasm binary file at '${e}'`),a.arrayBuffer().then(r=>{WebAssembly.instantiate(r,t).then(s=>{n(s.instance,s.module)})})}),{})}function dM(e,t,n){if(nm!=null)return nm;let a="tfjs-backend-wasm.wasm";return e&&t?a="tfjs-backend-wasm-threaded-simd.wasm":e&&(a="tfjs-backend-wasm-simd.wasm"),Ap!=null&&Ap[a]!=null?Ap[a]:n+a}async function Sve(){let[e,t]=await Promise.all([se().getAsync("WASM_HAS_SIMD_SUPPORT"),se().getAsync("WASM_HAS_MULTITHREAD_SUPPORT")]);return new Promise((n,a)=>{let r={};r.locateFile=(o,l)=>{if(o.endsWith(".worker.js")){let u=wve,d=new Blob([u],{type:"application/javascript"});return URL.createObjectURL(d)}return o.endsWith(".wasm")?dM(e,t,yp!=null?yp:l):l+o},xb&&(r.instantiateWasm=Ive(dM(e,t,yp!=null?yp:"")));let s=!1;r.onAbort=()=>{s||xp||(xp=!0,a({message:"Make sure the server can serve the `.wasm` file relative to the bundled js file. For more details see https://github.com/tensorflow/tfjs/blob/master/tfjs-backend-wasm/README.md#using-bundlers"}))};let i;t&&e&&nm==null?(r.mainScriptUrlOrBlob=new Blob(["var WasmBackendModuleThreadedSimd = "+lM.default.toString()],{type:"text/javascript"}),i=(0,lM.default)(r)):i=(0,kve.default)(r),i.then(o=>{s=!0,xp=!1;let l=null;o.tfjs={init:o.cwrap("init",null,[]),registerTensor:o.cwrap("register_tensor",null,["number","number","number"]),disposeData:o.cwrap("dispose_data",l,["number"]),dispose:o.cwrap("dispose",l,[])},n({wasm:o})})})}function Nve(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 Tve=["tfjs-backend-wasm.wasm","tfjs-backend-wasm-simd.wasm","tfjs-backend-wasm-threaded-simd.wasm"],nm=null,yp=null,Ap={},xp=!1,xb=!1;function Eve(e,t=!1){if(B4("setWasmPath has been deprecated in favor of setWasmPaths and will be removed in a future release."),xp)throw new Error("The WASM backend was already initialized. Make sure you call `setWasmPath()` before you call `tf.setBackend()` or `tf.ready()`");nm=e,xb=t}function Cve(e,t=!1){if(xp)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")yp=e;else{Ap=e;let n=Tve.filter(a=>Ap[a]==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.`)}xb=t}var Mve="3.7.0",$ve=2;MA("wasm",async()=>{let{wasm:e}=await Sve();return new uM(e)},$ve);var Rve={tfjs:TR,"tfjs-core":ER,"tfjs-data":CR,"tfjs-layers":MR,"tfjs-converter":$R,"tfjs-backend-cpu":RR,"tfjs-backend-webgl":FR,"tfjs-backend-wasm":OR};var ma={name:"humangl",priority:99,canvas:null,gl:null,width:1024,height:1024,webGLattr:{alpha:!1,antialias:!1,premultipliedAlpha:!1,preserveDrawingBuffer:!1,depth:!1,stencil:!1,failIfMajorPerformanceCaveat:!1,desynchronized:!0}};function hM(){if(!qy(ma.name)){ge("backend registration:",ma.name);try{ma.canvas=typeof OffscreenCanvas!="undefined"?new OffscreenCanvas(ma.width,ma.height):document.createElement("canvas")}catch(e){ge("error: cannot create canvas:",e);return}try{ma.gl=ma.canvas.getContext("webgl2",ma.webGLattr)}catch(e){ge("error: cannot get WebGL2 context:",e);return}try{F0(2,ma.gl)}catch(e){ge("error: cannot set WebGL2 context:",e);return}try{let e=new W0(ma.gl);Ky(ma.name,()=>new hp(e),ma.priority)}catch(e){ge("error: cannot register WebGL backend:",e);return}try{Lo("webgl").forEach(t=>{let n={...t,backendName:ma.name};rc(n)})}catch(e){ge("error: cannot update WebGL backend registration:",e);return}try{ka.set("WEBGL_VERSION",2)}catch(e){ge("error: cannot set WebGL backend flags:",e);return}ge("backend registered:",ma.name)}}function pM(e,t){let n=[e.startPoint[0]*t[0],e.startPoint[1]*t[1]],a=[e.endPoint[0]*t[0],e.endPoint[1]*t[1]];return{startPoint:n,endPoint:a}}function vp(e){return[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])]}function Nu(e){return[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2]}function Tu(e,t,n){let a=t.shape[1],r=t.shape[2],s=[[e.startPoint[1]/a,e.startPoint[0]/r,e.endPoint[1]/a,e.endPoint[0]/r]];return Ye.cropAndResize(t,s,[0],n)}function am(e,t=1.5){let n=Nu(e),a=vp(e),r=[t*a[0]/2,t*a[1]/2],s=[n[0]-r[0],n[1]-r[1]],i=[n[0]+r[0],n[1]+r[1]];return{startPoint:s,endPoint:i,landmarks:e.landmarks}}function rm(e){let t=Nu(e),n=vp(e),r=Math.max(...n)/2,s=[Math.round(t[0]-r),Math.round(t[1]-r)],i=[Math.round(t[0]+r),Math.round(t[1]+r)];return{startPoint:s,endPoint:i,landmarks:e.landmarks}}function bb(e){let t=e.map(s=>s[0]),n=e.map(s=>s[1]),a=[Math.min(...t),Math.min(...n)],r=[Math.max(...t),Math.max(...n)];return{startPoint:a,endPoint:r,landmarks:e}}var cM=e=>({startPoint:Ze(e,[0,0],[-1,2]),endPoint:Ze(e,[0,2],[-1,2])});var sm=[[1,0,0],[0,1,0],[0,0,1]];function Fve(e){return e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI))}function vb(e,t){let n=Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]);return Fve(n)}function fM(e,t){return[[1,0,e],[0,1,t],[0,0,1]]}function ni(e,t){let n=0;for(let a=0;a{let u=Ye.resizeBilinear(t,[this.inputSize,this.inputSize]).div(127.5).sub(.5),d=this.model.execute(u),h;if(Array.isArray(d)){let f=d.sort((x,v)=>x.size-v.size),g=sn([f[0],f[2]],2),y=sn([f[1],f[3]],2);h=sn([y,g],1).squeeze(0)}else h=Yn(d);let p=Dve(h,this.anchors,[this.inputSize,this.inputSize]),c=Ze(h,[0,0],[-1,1]),m=Sr(c).squeeze().dataSync();return[h,p,m]}),s=await Ye.nonMaxSuppressionAsync(a,r,this.config.face.detector.maxDetected,this.config.face.detector.iouThreshold,this.config.face.detector.minConfidence),i=s.arraySync();s.dispose();let o=[];for(let l=0;lthis.config.face.detector.minConfidence){let d=Ze(a,[i[l],0],[1,-1]),h=cM(d);d.dispose();let p=this.anchorsData[i[l]],c=Ue(()=>Ze(n,[i[l],xM-1],[1,-1]).squeeze().reshape([xM,-1]));o.push({box:h,landmarks:c,anchor:p,confidence:u})}}return n.dispose(),a.dispose(),{boxes:o,scaleFactor:[t.shape[2]/this.inputSize,t.shape[1]/this.inputSize]}}};async function vM(e){let t=await Et(Mt(e.modelBasePath,e.face.detector.modelPath),{fromTFHub:e.face.detector.modelPath.includes("tfhub.dev")}),n=new bM(t,e);return!t||!t.modelUrl?ge("load model failed:",e.face.detector.modelPath):e.debug&&ge("load model:",t.modelUrl),n}var Lr={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]},wb=[{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]}],wp=[[.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]],vo=[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 _ve=[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],zve=[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],Pve=[33,133,362,263,1,78,308],y7e=_ve.map(e=>wp[e]),A7e=zve.map(e=>wp[e]),x7e=Pve.map(e=>wp[e]);var kb=Lr.leftEyeLower0,Ib=Lr.rightEyeLower0,Eu={leftBounds:[kb[0],kb[kb.length-1]],rightBounds:[Ib[0],Ib[Ib.length-1]]},om={count:468,mouth:13,symmetryLine:[13,Lr.midwayBetweenEyes[0]]},wM={leftEye:0,rightEye:1,nose:2,mouth:3,leftEar:4,rightEar:5,symmetryLine:[3,2]},Cu={upperCenter:3,lowerCenter:4,index:71,numCoordinates:76};function lm(e,t,n,a){for(let r=0;r[s[0]/this.meshSize*(h[0]-this.meshSize/2),s[1]/this.meshSize*(h[1]-this.meshSize/2),h[2]]),o=a!==0?im(a,[0,0]):sm,l=a!==0?i.map(h=>[...yM(h,o),h[2]]):i,u=a!==0?gM(r):sm,d=[...Nu({startPoint:n.startPoint,endPoint:n.endPoint}),1];return l.map(h=>[Math.round(h[0]+ni(d,u[0])),Math.round(h[1]+ni(d,u[1])),Math.round(h[2])])}getLeftToRightEyeDepthDifference(t){let n=t[Eu.leftBounds[0]][2],a=t[Eu.rightBounds[0]][2];return n-a}getEyeBox(t,n,a,r,s=!1){let i=rm(am(bb([t[a],t[r]]),this.irisEnlarge)),o=vp(i),l=Ye.cropAndResize(n,[[i.startPoint[1]/this.meshSize,i.startPoint[0]/this.meshSize,i.endPoint[1]/this.meshSize,i.endPoint[0]/this.meshSize]],[0],[this.irisSize,this.irisSize]);return s&&ka.flags.IS_BROWSER&&(l=Ye.flipLeftRight(l)),{box:i,boxSize:o,crop:l}}getEyeCoords(t,n,a,r=!1){let s=[];for(let i=0;i{let u=i;return l===2?u=r:l===4&&(u=s),[o[0],o[1],u]})}async predict(t,n){let a=!1,r;if((this.skipped===0||this.skipped>n.face.detector.skipFrames||!n.face.mesh.enabled||!n.skipFrame)&&(r=await this.boundingBoxDetector.getBoundingBoxes(t),this.skipped=0),n.skipFrame&&this.skipped++,!n.skipFrame||r&&r.boxes&&(!n.face.mesh.enabled||r.boxes.length!==this.detectedFaces&&this.detectedFaces!==n.face.detector.maxDetected)){this.storedBoxes=[],this.detectedFaces=0;for(let i of r.boxes)this.storedBoxes.push({startPoint:i.box.startPoint.dataSync(),endPoint:i.box.endPoint.dataSync(),landmarks:i.landmarks.arraySync(),confidence:i.confidence});this.storedBoxes.length>0&&(a=!0)}if(a){if(!r||!r.boxes||r.boxes.length===0)return this.storedBoxes=[],this.detectedFaces=0,null;for(let i=0;i{i.box.startPoint.dispose(),i.box.endPoint.dispose(),i.landmarks.dispose()});let s=Ue(()=>this.storedBoxes.map((i,o)=>{let l,u=0,d;if(n.face.detector.rotation&&n.face.mesh.enabled&&ka.flags.IS_BROWSER){let[x,v]=i.landmarks.length>=om.count?om.symmetryLine:wM.symmetryLine;u=vb(i.landmarks[x],i.landmarks[v]);let b=Nu({startPoint:i.startPoint,endPoint:i.endPoint}),w=[b[0]/t.shape[2],b[1]/t.shape[1]],I=Ye.rotateWithOffset(t,u,0,w);d=im(-u,b),n.face.mesh.enabled?l=Tu({startPoint:i.startPoint,endPoint:i.endPoint},I,[this.meshSize,this.meshSize]).div(255):l=Tu({startPoint:i.startPoint,endPoint:i.endPoint},I,[this.boxSize,this.boxSize]).div(255)}else{d=sm;let x=t.clone();n.face.mesh.enabled?l=Tu({startPoint:i.startPoint,endPoint:i.endPoint},x,[this.meshSize,this.meshSize]).div(255):l=Tu({startPoint:i.startPoint,endPoint:i.endPoint},x,[this.boxSize,this.boxSize]).div(255)}if(!n.face.mesh.enabled)return{mesh:[],box:i,faceConfidence:null,boxConfidence:i.confidence,confidence:i.confidence,image:l};let[,h,p]=this.meshDetector.execute(l),c=h.dataSync()[0];if(c=om.count?om.symmetryLine:wM.symmetryLine;u=vb(i.landmarks[x],i.landmarks[v]);let b=Nu({startPoint:i.startPoint,endPoint:i.endPoint}),w=[b[0]/t.shape[2],b[1]/t.shape[1]],I=Ye.rotateWithOffset(t.toFloat(),u,0,w);d=im(-u,b),l=Tu({startPoint:i.startPoint,endPoint:i.endPoint},I,[this.meshSize,this.meshSize]).div(255)}let A={mesh:g,box:i,faceConfidence:c,boxConfidence:i.confidence,image:l};return this.storedBoxes[o]={...rm(i),confidence:i.confidence,faceConfidence:c},A}));return n.face.mesh.enabled&&(this.storedBoxes=this.storedBoxes.filter(i=>i.confidence>n.face.detector.minConfidence)),this.detectedFaces=s.length,s}};var Zt=[null,null,null],Nb;async function kM(e,t){let n=await Nb.predict(e,t),a=[],r=0;for(let s of n||[]){if(!s||s.isDisposedInternal)continue;let i=s.mesh.map(d=>[d[0]/(e.shape[2]||0),d[1]/(e.shape[1]||0),d[2]/Nb.meshSize]),o={};if(s.mesh&&s.mesh.length>0)for(let d of Object.keys(Lr))o[d]=Lr[d].map(h=>s.mesh[h]);let l=s.box?[Math.trunc(Math.max(0,s.box.startPoint[0])),Math.trunc(Math.max(0,s.box.startPoint[1])),Math.trunc(Math.min(e.shape[2]||0,s.box.endPoint[0])-Math.max(0,s.box.startPoint[0])),Math.trunc(Math.min(e.shape[1]||0,s.box.endPoint[1])-Math.max(0,s.box.startPoint[1]))]:[0,0,0,0],u=s.box?[s.box.startPoint[0]/(e.shape[2]||0),s.box.startPoint[1]/(e.shape[1]||0),(s.box.endPoint[0]-s.box.startPoint[0])/(e.shape[2]||0),(s.box.endPoint[1]-s.box.startPoint[1])/(e.shape[1]||0)]:[0,0,0,0];a.push({id:r++,score:Math.round(100*s.faceConfidence||100*s.boxConfidence||0)/100,boxScore:Math.round(100*s.boxConfidence)/100,faceScore:Math.round(100*s.faceConfidence)/100,box:l,boxRaw:u,mesh:s.mesh,meshRaw:i,annotations:o,image:s.image,tensor:s.image}),s.coords&&s.coords.dispose()}return a}async function Tb(e){return!Zt[0]&&e.face.enabled||!Zt[1]&&e.face.mesh.enabled||!Zt[2]&&e.face.iris.enabled?(Zt=await Promise.all([!Zt[0]&&e.face.enabled?vM(e):null,!Zt[1]&&e.face.mesh.enabled?Et(Mt(e.modelBasePath,e.face.mesh.modelPath),{fromTFHub:e.face.mesh.modelPath.includes("tfhub.dev")}):null,!Zt[2]&&e.face.iris.enabled?Et(Mt(e.modelBasePath,e.face.iris.modelPath),{fromTFHub:e.face.iris.modelPath.includes("tfhub.dev")}):null]),e.face.mesh.enabled&&(!Zt[1]||!Zt[1].modelUrl?ge("load model failed:",e.face.mesh.modelPath):e.debug&&ge("load model:",Zt[1].modelUrl)),e.face.iris.enabled&&(!Zt[2]||!Zt[2].modelUrl?ge("load model failed:",e.face.iris.modelPath):e.debug&&ge("load model:",Zt[2].modelUrl))):e.debug&&(Zt[0]&&ge("cached model:",Zt[0].model.modelUrl),Zt[1]&&ge("cached model:",Zt[1].modelUrl),Zt[2]&&ge("cached model:",Zt[2].modelUrl)),Nb=new Sb(Zt[0],Zt[1],Zt[2]),Zt}var IM=vo,SM=wp;var Lve=["angry","disgust","fear","happy","sad","surprise","neutral"],Ar,um=[],NM=0,Eb=Number.MAX_SAFE_INTEGER,Cb=[.2989,.587,.114];async function Mb(e){return Ar?e.debug&&ge("cached model:",Ar.modelUrl):(Ar=await Et(Mt(e.modelBasePath,e.face.emotion.modelPath)),!Ar||!Ar.modelUrl?ge("load model failed:",e.face.emotion.modelPath):e.debug&&ge("load model:",Ar.modelUrl)),Ar}async function $b(e,t,n,a){return Ar?Eb0?(Eb++,um[n]):(Eb=0,new Promise(async r=>{let s=Ye.resizeBilinear(e,[Ar.inputs[0].shape[2],Ar.inputs[0].shape[1]],!1),[i,o,l]=es(s,3,3);s.dispose();let u=fe(i,Cb[0]),d=fe(o,Cb[1]),h=fe(l,Cb[2]);i.dispose(),o.dispose(),l.dispose();let p=Xy([u,d,h]);u.dispose(),d.dispose(),h.dispose();let c=Ue(()=>p.sub(.5).mul(2));p.dispose();let m=[];if(t.face.emotion.enabled){let f=await Ar.predict(c),g=f.dataSync();Ve(f);for(let y=0;yt.face.emotion.minConfidence&&m.push({score:Math.min(.99,Math.trunc(100*g[y])/100),emotion:Lve[y]});m.sort((y,A)=>A.score-y.score)}c.dispose(),um[n]=m,NM=a,r(m)})):null}var xr,dm=[],TM=0,Rb=Number.MAX_SAFE_INTEGER;async function Fb(e){let t=Mt(e.modelBasePath,e.face.description.modelPath);return xr?e.debug&&ge("cached model:",t):(xr=await Et(t),xr?e.debug&&ge("load model:",t):ge("load model failed:",e.face.description.modelPath)),xr}function Ob(e,t,n=2){if(!e||!t||(e==null?void 0:e.length)===0||(t==null?void 0:t.length)===0||(e==null?void 0:e.length)!==(t==null?void 0:t.length))return 0;let a=5*e.map((s,i)=>Math.abs(e[i]-t[i])**n).reduce((s,i)=>s+i,0)**(1/n);return Math.max(0,100-a)/100}function EM(e,t,n=0){let a={similarity:0,name:"",source:"",embedding:[]};if(!e||!t||!Array.isArray(e)||!Array.isArray(t))return a;for(let r of t)if(r.embedding&&r.name){let s=Ob(e,r.embedding);s>n&&s>a.similarity&&(a={...r,similarity:s})}return a}function Db(e){return Ue(()=>{let n=e.image||e.tensor||e;if(!(n instanceof St))return null;let a=[[.05,.15,.85,.85]];return xr.inputs[0].shape?(n.shape.length===3?Ye.cropAndResize(Qr(n,0),a,[0],[xr.inputs[0].shape[2],xr.inputs[0].shape[1]]):Ye.cropAndResize(n,a,[0],[xr.inputs[0].shape[2],xr.inputs[0].shape[1]])).mul(255):null})}async function _b(e,t,n,a){var r,s;return xr?Rb0?(Rb++,dm[n]):(Rb=0,new Promise(async i=>{let o=Db(e),l,u={age:0,gender:"unknown",genderScore:0,descriptor:[]};t.face.description.enabled&&(l=await xr.predict(o)),Ve(o),l&&(Ue(()=>{let d=l.find(f=>f.shape[1]===1).dataSync(),h=Math.trunc(200*Math.abs(d[0]-.5))/100;h>t.face.description.minConfidence&&(u.gender=d[0]<=.5?"female":"male",u.genderScore=Math.min(.99,h));let p=l.find(f=>f.shape[1]===100).argMax(1).dataSync()[0],c=l.find(f=>f.shape[1]===100).dataSync();u.age=Math.round(c[p-1]>c[p+1]?10*p-100*c[p-1]:10*p+100*c[p+1])/10;let m=l.find(f=>f.shape[1]===1024);u.descriptor=[...m.dataSync()]}),l.forEach(d=>Ve(d))),dm[n]=u,TM=a,i(u)})):null}var Wve=e=>{let t=(h,p)=>Math.atan2(h[1]-p[1],h[0]-p[0]);if(!e.annotations.rightEyeIris||!e.annotations.leftEyeIris)return{bearing:0,strength:0};let n=[0,-.1],a=1,r=e.mesh[33][2]>e.mesh[263][2],s=r?e.mesh[473]:e.mesh[468],i=r?[(e.mesh[133][0]+e.mesh[33][0])/2,(e.mesh[133][1]+e.mesh[33][1])/2]:[(e.mesh[263][0]+e.mesh[362][0])/2,(e.mesh[263][1]+e.mesh[362][1])/2],o=r?[e.mesh[133][0]-e.mesh[33][0],e.mesh[23][1]-e.mesh[27][1]]:[e.mesh[263][0]-e.mesh[362][0],e.mesh[253][1]-e.mesh[257][1]],l=[(i[0]-s[0])/o[0]-n[0],a*(s[1]-i[1])/o[1]-n[1]],u=Math.sqrt(l[0]**2+l[1]**2);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}},Bve=(e,t)=>{let n=g=>{let y=Math.sqrt(g[0]*g[0]+g[1]*g[1]+g[2]*g[2]);return g[0]/=y,g[1]/=y,g[2]/=y,g},a=(g,y)=>{let A=g[0]-y[0],x=g[1]-y[1],v=g[2]-y[2];return[A,x,v]},r=(g,y)=>{let A=g[1]*y[2]-g[2]*y[1],x=g[2]*y[0]-g[0]*y[2],v=g[0]*y[1]-g[1]*y[0];return[A,x,v]},s=g=>{let[y,A,x,v,b,w,I,T,C]=g,z,$,S;return v<1?v>-1?(S=Math.asin(v),$=Math.atan2(-I,y),z=Math.atan2(-w,b)):(S=-Math.PI/2,$=-Math.atan2(T,C),z=0):(S=Math.PI/2,$=Math.atan2(T,C),z=0),{pitch:2*-z,yaw:2*-$,roll:2*-S}},i=g=>{let y=(x,v,b,w)=>Math.atan2(w-v,b-x);return{pitch:y(g[10][1],g[10][2],g[152][1],g[152][2]),yaw:y(g[33][0],g[33][2],g[263][0],g[263][2]),roll:y(g[33][0],g[33][1],g[263][0],g[263][1])}},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 l=Math.max(e.boxRaw[2]*t[0],e.boxRaw[3]*t[1])/1.5,u=[o[10],o[152],o[234],o[454]].map(g=>[g[0]*t[0]/l,g[1]*t[1]/l,g[2]]),d=n(a(u[1],u[0])),h=n(a(u[3],u[2])),p=n(r(h,d));h=r(d,p);let c=[h[0],h[1],h[2],d[0],d[1],d[2],p[0],p[1],p[2]],m=s(c),f=o.length===478?Wve(e):{bearing:0,strength:0};return{angle:m,matrix:c,gaze:f}},zb=async(e,t)=>{var d,h,p,c,m,f;let n,a,r,s,i,o,l=[];e.state="run:face",n=st();let u=await kM(t,e.config);if(e.performance.face=Math.trunc(st()-n),!t.shape||t.shape.length!==4)return[];if(!u)return[];for(let g=0;g(e[t]=n,e),{}),Vve=[["leftHip","leftShoulder"],["leftElbow","leftShoulder"],["leftElbow","leftWrist"],["leftHip","leftKnee"],["leftKnee","leftAnkle"],["rightHip","rightShoulder"],["rightElbow","rightShoulder"],["rightElbow","rightWrist"],["rightHip","rightKnee"],["rightKnee","rightAnkle"],["leftShoulder","rightShoulder"],["leftHip","rightHip"]],Uve=Vve.map(([e,t])=>[Ip[e],Ip[t]]),MM=[["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 $M(e){let t=e.reduce(({maxX:n,maxY:a,minX:r,minY:s},{position:{x:i,y:o}})=>({maxX:Math.max(n,i),maxY:Math.max(a,o),minX:Math.min(r,i),minY:Math.min(s,o)}),{maxX:Number.NEGATIVE_INFINITY,maxY:Number.NEGATIVE_INFINITY,minX:Number.POSITIVE_INFINITY,minY:Number.POSITIVE_INFINITY});return[t.minX,t.minY,t.maxX-t.minX,t.maxY-t.minY]}function RM(e,[t,n],[a,r]){let s=t/a,i=n/r,o=(u,d)=>({id:d,score:u.score,boxRaw:[u.box[0]/r,u.box[1]/a,u.box[2]/r,u.box[3]/a],box:[Math.trunc(u.box[0]*i),Math.trunc(u.box[1]*s),Math.trunc(u.box[2]*i),Math.trunc(u.box[3]*s)],keypoints:u.keypoints.map(({score:h,part:p,position:c})=>({score:h,part:p,position:[Math.trunc(c.x*i),Math.trunc(c.y*s)],positionRaw:[c.x/a,c.y/a]}))});return e.map((u,d)=>o(u,d))}var Pb=class{constructor(t,n){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(nn?n:e}function FM(e,t,n,a){let r=n-e,s=a-t;return r*r+s*s}function Vb(e,t){return{x:e.x+t.x,y:e.y+t.y}}var hm=1,Mu=16,jve=50**2;function OM(e,t,n,a,r,s,i=2){let o=y=>({y:s.get(y.y,y.x,e),x:s.get(y.y,y.x,s.shape[2]/2+e)}),l=(y,A,x)=>({y:Bb(Math.round(y.y/Mu),0,A-1),x:Bb(Math.round(y.x/Mu),0,x-1)}),[u,d]=a.shape,h=l(t.position,u,d),p=o(h),m=Vb(t.position,p);for(let y=0;y[Ip[p],Ip[c]]),i=s.map(([,p])=>p),o=s.map(([p])=>p),l=t.shape[2],u=i.length,d=new Array(l),h=Wb(e.part,Mu,n);d[e.part.id]={score:e.score,part:kp[e.part.id],position:h};for(let p=u-1;p>=0;--p){let c=i[p],m=o[p];d[c]&&!d[m]&&(d[m]=OM(p,d[c],m,t,n,r))}for(let p=0;pt){o=!1;break}if(!o)break}return o}function qve(e,t){let[n,a,r]=t.shape,s=new Pb(n*a*r,({score:i})=>i);for(let i=0;i{var i;let s=(i=r[a])==null?void 0:i.position;return s?FM(n,t,s.y,s.x)<=jve:!1})}function Kve(e,t){return t.reduce((a,{position:r,score:s},i)=>(DM(e,r,i)||(a+=s),a),0)/t.length}function _M(e,t,n,a,r,s){let i=[],o=qve(s,t);for(;i.lengthc.score>s);let h=Kve(i,d),p=$M(d);h>s&&i.push({keypoints:d,box:p,score:Math.round(100*h)/100})}return i}var ga,Xve=["MobilenetV1/offset_2/BiasAdd","MobilenetV1/heatmap_2/BiasAdd","MobilenetV1/displacement_fwd_2/BiasAdd","MobilenetV1/displacement_bwd_2/BiasAdd"];async function Ub(e,t){let n=Ue(()=>{if(!ga.inputs[0].shape)return[];let o=Ye.resizeBilinear(e,[ga.inputs[0].shape[2],ga.inputs[0].shape[1]]).toFloat().div(127.5).sub(1),u=ga.execute(o,Xve).map(d=>Yn(d,[0]));return u[1]=u[1].sigmoid(),u}),a=await Promise.all(n.map(i=>i.buffer()));for(let i of n)i.dispose();let r=await _M(a[0],a[1],a[2],a[3],t.body.maxDetected,t.body.minConfidence);return ga.inputs[0].shape?RM(r,[e.shape[1],e.shape[2]],[ga.inputs[0].shape[2],ga.inputs[0].shape[1]]):[]}async function jb(e){return ga?e.debug&&ge("cached model:",ga.modelUrl):(ga=await Et(Mt(e.modelBasePath,e.body.modelPath)),!ga||!ga.modelUrl?ge("load model failed:",e.body.modelPath):e.debug&&ge("load model:",ga.modelUrl)),ga}function pm(e){return[Math.abs(e.endPoint[0]-e.startPoint[0]),Math.abs(e.endPoint[1]-e.startPoint[1])]}function Sp(e){return[e.startPoint[0]+(e.endPoint[0]-e.startPoint[0])/2,e.startPoint[1]+(e.endPoint[1]-e.startPoint[1])/2]}function zM(e,t,n){let a=t.shape[1],r=t.shape[2],s=[[e.startPoint[1]/a,e.startPoint[0]/r,e.endPoint[1]/a,e.endPoint[0]/r]];return Ye.cropAndResize(t,s,[0],n)}function PM(e,t){let n=[e.startPoint[0]*t[0],e.startPoint[1]*t[1]],a=[e.endPoint[0]*t[0],e.endPoint[1]*t[1]],r=e.palmLandmarks.map(s=>[s[0]*t[0],s[1]*t[1]]);return{startPoint:n,endPoint:a,palmLandmarks:r,confidence:e.confidence}}function cm(e,t=1.5){let n=Sp(e),a=pm(e),r=[t*a[0]/2,t*a[1]/2],s=[n[0]-r[0],n[1]-r[1]],i=[n[0]+r[0],n[1]+r[1]];return{startPoint:s,endPoint:i,palmLandmarks:e.palmLandmarks}}function fm(e){let t=Sp(e),n=pm(e),r=Math.max(...n)/2,s=[t[0]-r,t[1]-r],i=[t[0]+r,t[1]+r];return{startPoint:s,endPoint:i,palmLandmarks:e.palmLandmarks}}var LM=[{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 Hb=class{constructor(t){var n;this.model=t,this.anchors=LM.map(a=>[a.x,a.y]),this.anchorsTensor=ns(this.anchors),this.inputSize=(n=this.model)==null?void 0:n.inputs[0].shape[2],this.inputSizeTensor=oa([this.inputSize,this.inputSize]),this.doubleInputSizeTensor=oa([this.inputSize*2,this.inputSize*2])}normalizeBoxes(t){return Ue(()=>{let n=Ze(t,[0,0],[-1,2]),a=Ze(t,[0,2],[-1,2]),r=De(Qe(n,this.inputSizeTensor),this.anchorsTensor),s=Qe(a,this.doubleInputSizeTensor),i=fe(je(r,s),this.inputSizeTensor),o=fe(De(r,s),this.inputSizeTensor);return ld([i,o],1)})}normalizeLandmarks(t,n){return Ue(()=>{let a=De(Qe(t.reshape([-1,7,2]),this.inputSizeTensor),this.anchors[n]);return fe(a,this.inputSizeTensor)})}async getBoxes(t,n){let a=this.model.predict(t),r=Yn(a);a.dispose();let s=Ue(()=>Sr(Ze(r,[0,0],[-1,1])).squeeze()),i=s.dataSync(),o=Ze(r,[0,1],[-1,4]),l=this.normalizeBoxes(o);o.dispose();let u=await Ye.nonMaxSuppressionAsync(l,i,n.hand.maxDetected,n.hand.iouThreshold,n.hand.minConfidence),d=u.arraySync();s.dispose(),u.dispose();let h=[];for(let p of d)if(i[p]>=n.hand.minConfidence){let c=Ze(l,[p,0],[1,-1]),m=Ze(r,[p,5],[1,14]),f=Ue(()=>this.normalizeLandmarks(m,p).reshape([-1,2]));m.dispose(),h.push({box:c,palmLandmarks:f,confidence:i[p]})}return r.dispose(),l.dispose(),h}async estimateHandBounds(t,n){let a=t.shape[1],r=t.shape[2],s=Ue(()=>t.resizeBilinear([this.inputSize,this.inputSize]).div(127.5).sub(1)),i=await this.getBoxes(s,n);s.dispose();let o=[];if(!i||i.length===0)return o;for(let l of i){let u=l.box.dataSync(),d=u.slice(0,2),h=u.slice(2,4),p=l.palmLandmarks.arraySync();l.box.dispose(),l.palmLandmarks.dispose(),o.push(PM({startPoint:d,endPoint:h,palmLandmarks:p,confidence:l.confidence},[r/this.inputSize,a/this.inputSize]))}return o}};function Zve(e){return e-2*Math.PI*Math.floor((e+Math.PI)/(2*Math.PI))}function WM(e,t){let n=Math.PI/2-Math.atan2(-(t[1]-e[1]),t[0]-e[0]);return Zve(n)}var BM=(e,t)=>[[1,0,e],[0,1,t],[0,0,1]];function ai(e,t){let n=0;for(let a=0;ai[0]),a=t.map(i=>i[1]),r=[Math.min(...n),Math.min(...a)],s=[Math.max(...n),Math.max(...a)];return{startPoint:r,endPoint:s}}getBoxForPalmLandmarks(t,n){let a=t.map(s=>qb([...s,1],n)),r=this.calculateLandmarksBoundingBox(a);return cm(fm(r),Jve)}getBoxForHandLandmarks(t){let n=this.calculateLandmarksBoundingBox(t),a=cm(fm(n),jM);a.palmLandmarks=[];for(let r=0;r[i[0]*(c[0]-this.inputSize/2),i[1]*(c[1]-this.inputSize/2),i[2]*c[2]]),l=Gb(a,[0,0]),u=o.map(c=>[...qb(c,l),c[2]]),d=UM(r),h=[...Sp(n),1],p=[ai(h,d[0]),ai(h,d[1])];return u.map(c=>[Math.trunc(c[0]+p[0]),Math.trunc(c[1]+p[1]),Math.trunc(c[2])])}async estimateHands(t,n){let a=!1,r;(this.skipped===0||this.skipped>n.hand.skipFrames||!n.hand.landmarks||!n.skipFrame)&&(r=await this.handDetector.estimateHandBounds(t,n),this.skipped=0),n.skipFrame&&this.skipped++,r&&r.length>0&&(r.length!==this.detectedHands&&this.detectedHands!==n.hand.maxDetected||!n.hand.landmarks)&&(this.detectedHands=0,this.storedBoxes=[...r],this.storedBoxes.length>0&&(a=!0));let s=[];for(let i=0;i=n.hand.minConfidence){let x=le(y,[-1,3]),v=x.arraySync();y.dispose(),x.dispose();let b=this.transformRawCoords(v,c,l,p),w=this.getBoxForHandLandmarks(b);this.storedBoxes[i]={...w,confidence:A};let I={landmarks:b,confidence:A,box:{topLeft:w.startPoint,bottomRight:w.endPoint}};s.push(I)}else this.storedBoxes[i]=null;y.dispose()}else{let l=cm(fm(o),jM),u={confidence:o.confidence,box:{topLeft:l.startPoint,bottomRight:l.endPoint}};s.push(u)}}return this.storedBoxes=this.storedBoxes.filter(i=>i!==null),this.detectedHands=s.length,s}};var GM={thumb:[1,2,3,4],indexFinger:[5,6,7,8],middleFinger:[9,10,11,12],ringFinger:[13,14,15,16],pinky:[17,18,19,20],palmBase:[0]},ri,si,qM;async function Xb(e,t){let n=await qM.estimateHands(e,t);if(!n)return[];let a=[];for(let r=0;rn[r].landmarks[d]);let i=n[r].landmarks,o=[Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,0,0],l=[0,0,0,0];if(i&&i.length>0){for(let u of i)u[0]o[2]&&(o[2]=u[0]),u[1]>o[3]&&(o[3]=u[1]);o[2]-=o[0],o[3]-=o[1],l=[o[0]/(e.shape[2]||0),o[1]/(e.shape[1]||0),o[2]/(e.shape[2]||0),o[3]/(e.shape[1]||0)]}else o=n[r].box?[Math.trunc(Math.max(0,n[r].box.topLeft[0])),Math.trunc(Math.max(0,n[r].box.topLeft[1])),Math.trunc(Math.min(e.shape[2]||0,n[r].box.bottomRight[0])-Math.max(0,n[r].box.topLeft[0])),Math.trunc(Math.min(e.shape[1]||0,n[r].box.bottomRight[1])-Math.max(0,n[r].box.topLeft[1]))]:[0,0,0,0],l=[n[r].box.topLeft[0]/(e.shape[2]||0),n[r].box.topLeft[1]/(e.shape[1]||0),(n[r].box.bottomRight[0]-n[r].box.topLeft[0])/(e.shape[2]||0),(n[r].box.bottomRight[1]-n[r].box.topLeft[1])/(e.shape[1]||0)];a.push({id:r,score:Math.round(100*n[r].confidence)/100,box:o,boxRaw:l,keypoints:i,annotations:s})}return a}async function Zb(e){!ri||!si?([ri,si]=await Promise.all([e.hand.enabled?Et(Mt(e.modelBasePath,e.hand.detector.modelPath),{fromTFHub:e.hand.detector.modelPath.includes("tfhub.dev")}):null,e.hand.landmarks?Et(Mt(e.modelBasePath,e.hand.skeleton.modelPath),{fromTFHub:e.hand.skeleton.modelPath.includes("tfhub.dev")}):null]),e.hand.enabled&&(!ri||!ri.modelUrl?ge("load model failed:",e.hand.detector.modelPath):e.debug&&ge("load model:",ri.modelUrl),!si||!si.modelUrl?ge("load model failed:",e.hand.skeleton.modelPath):e.debug&&ge("load model:",si.modelUrl))):(e.debug&&ge("cached model:",ri.modelUrl),e.debug&&ge("cached model:",si.modelUrl));let t=new Hb(ri);return qM=new Kb(t,si),[ri,si]}var KM=["nose","leftEyeInside","leftEye","leftEyeOutside","rightEyeInside","rightEye","rightEyeOutside","leftEar","rightEar","leftMouth","rightMouth","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftPalm","rightPalm","leftIndex","rightIndex","leftPinky","rightPinky","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle","leftHeel","rightHeel","leftFoot","rightFoot","midHip","forehead","leftThumb","leftHand","rightThumb","rightHand"],XM=["nose","leftEyeInside","leftEye","leftEyeOutside","rightEyeInside","rightEye","rightEyeOutside","leftEar","rightEar","leftMouth","rightMouth","leftShoulder","rightShoulder","leftElbow","rightElbow","left:15","right:16","left:17","right:18","left:19","right:20","left:21","right:22","leftChest","rightChest","neck","forehead","left:27","right:28","left:29","right:30"];var aa;async function mm(e){return aa?e.debug&&ge("cached model:",aa.modelUrl):(aa=await Et(Mt(e.modelBasePath,e.body.modelPath)),aa.width=parseInt(aa.signature.inputs["input_1:0"].tensorShape.dim[2].size),aa.height=parseInt(aa.signature.inputs["input_1:0"].tensorShape.dim[1].size),!aa||!aa.modelUrl?ge("load model failed:",e.body.modelPath):e.debug&&ge("load model:",aa.modelUrl)),aa}async function Yb(e,t){var f;if(!aa)return[];if(!t.body.enabled)return[];let n={width:e.shape[2]||0,height:e.shape[1]||0},a=Ye.resizeBilinear(e,[aa.width,aa.height],!1),r=Qe(a,[255]);a.dispose();let s=await aa.predict(r),i=((f=s.find(g=>g.size===195||g.size===155))==null?void 0:f.dataSync())||[];s.forEach(g=>g.dispose()),r.dispose();let o=[],l=(i==null?void 0:i.length)===195?KM:XM,u=5;for(let g=0;gg.position[0]),h=o.map(g=>g.position[1]),p=[Math.min(...d),Math.min(...h),Math.max(...d)-Math.min(...d),Math.max(...h)-Math.min(...d)],c=[0,0,0,0],m=o.reduce((g,y)=>y.score>g?y.score:g,0);return[{id:0,score:m,box:p,boxRaw:c,keypoints:o}]}var ra,Wr=[],Jb=[0,0,0,0],Qb=[0,0,0,0],gm=0,e3=Number.MAX_SAFE_INTEGER,twe=["head","neck","rightShoulder","rightElbow","rightWrist","chest","leftShoulder","leftElbow","leftWrist","pelvis","rightHip","rightKnee","rightAnkle","leftHip","leftKnee","leftAnkle"];async function ZM(e){return ra?e.debug&&ge("cached model:",ra.modelUrl):(ra=await Et(Mt(e.modelBasePath,e.body.modelPath)),!ra||!ra.modelUrl?ge("load model failed:",e.body.modelPath):e.debug&&ge("load model:",ra.modelUrl)),ra}function nwe(e,t){let[n,a]=e.shape;return Ue(()=>{let r=(o,l)=>je(o,fe(Qe(o,dt(l,"int32")),dt(l,"int32"))),s=le(e,[a*n]),i=$s(s,0).dataSync()[0];if(i>t){let o=Zy(s,0),l=r(o,n).dataSync()[0],u=Qe(o,dt(n,"int32")).dataSync()[0];return[l,u,i]}return[0,0,i]})}async function t3(e,t){return e30?(e3++,[{id:0,score:gm,box:Jb,boxRaw:Qb,keypoints:Wr}]):(e3=0,new Promise(async n=>{let a=Ue(()=>{if(!ra.inputs[0].shape)return null;let u=Ye.resizeBilinear(e,[ra.inputs[0].shape[2],ra.inputs[0].shape[1]],!1);return fe(u,2).sub(1)}),r;if(t.body.enabled&&(r=await ra.predict(a)),a.dispose(),r){Wr.length=0;let u=r.squeeze();Ve(r);let d=u.unstack(2);Ve(u);for(let h=0;ht.body.minConfidence&&Wr.push({score:Math.round(100*m)/100,part:twe[h],positionRaw:[p/ra.inputs[0].shape[2],c/ra.inputs[0].shape[1]],position:[Math.round(e.shape[2]*p/ra.inputs[0].shape[2]),Math.round(e.shape[1]*c/ra.inputs[0].shape[1])]})}d.forEach(h=>Ve(h))}gm=Wr.reduce((u,d)=>d.score>u?d.score:u,0);let s=Wr.map(u=>u.position[0]),i=Wr.map(u=>u.position[1]);Jb=[Math.min(...s),Math.min(...i),Math.max(...s)-Math.min(...s),Math.max(...i)-Math.min(...i)];let o=Wr.map(u=>u.positionRaw[0]),l=Wr.map(u=>u.positionRaw[1]);Qb=[Math.min(...o),Math.min(...l),Math.max(...o)-Math.min(...o),Math.max(...l)-Math.min(...l)],n([{id:0,score:gm,box:Jb,boxRaw:Qb,keypoints:Wr}])}))}var br,Br=[],n3=[0,0,0,0],a3=[0,0,0,0],$u=0,r3=Number.MAX_SAFE_INTEGER,awe=["nose","leftEye","rightEye","leftEar","rightEar","leftShoulder","rightShoulder","leftElbow","rightElbow","leftWrist","rightWrist","leftHip","rightHip","leftKnee","rightKnee","leftAnkle","rightAnkle"];async function s3(e){return br?e.debug&&ge("cached model:",br.modelUrl):(br=await Et(Mt(e.modelBasePath,e.body.modelPath)),!br||!br.modelUrl?ge("load model failed:",e.body.modelPath):e.debug&&ge("load model:",br.modelUrl)),br}async function i3(e,t){return r30?(r3++,[{id:0,score:$u,box:n3,boxRaw:a3,keypoints:Br}]):(r3=0,new Promise(async n=>{let a=Ue(()=>{if(!br.inputs[0].shape)return null;let u=Ye.resizeBilinear(e,[br.inputs[0].shape[2],br.inputs[0].shape[1]],!1);return zt(u,"int32")}),r;if(t.body.enabled&&(r=await br.predict(a)),a.dispose(),r){Br.length=0;let u=r.arraySync();Ve(r);let d=u[0][0];for(let h=0;ht.body.minConfidence&&Br.push({score:Math.round(100*$u)/100,part:awe[h],positionRaw:[d[h][1],d[h][0]],position:[Math.round((e.shape[2]||0)*d[h][1]),Math.round((e.shape[1]||0)*d[h][0])]})}$u=Br.reduce((u,d)=>d.score>u?d.score:u,0);let s=Br.map(u=>u.position[0]),i=Br.map(u=>u.position[1]);n3=[Math.min(...s),Math.min(...i),Math.max(...s)-Math.min(...s),Math.max(...i)-Math.min(...i)];let o=Br.map(u=>u.positionRaw[0]),l=Br.map(u=>u.positionRaw[1]);a3=[Math.min(...o),Math.min(...l),Math.max(...o)-Math.min(...o),Math.max(...l)-Math.min(...l)],n([{id:0,score:$u,box:n3,boxRaw:a3,keypoints:Br}])}))}var Ru=[{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 ya,o3=[],l3=Number.MAX_SAFE_INTEGER,ym=2.5;async function u3(e){if(ya)e.debug&&ge("cached model:",ya.modelUrl);else{ya=await Et(Mt(e.modelBasePath,e.object.modelPath));let t=Object.values(ya.modelSignature.inputs);if(ya.inputSize=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):null,!ya.inputSize)throw new Error(`Human: Cannot determine model inputSize: ${e.object.modelPath}`);!ya||!ya.modelUrl?ge("load model failed:",e.object.modelPath):e.debug&&ge("load model:",ya.modelUrl)}return ya}async function rwe(e,t,n,a){let r=0,s=[];for(let u of[1,2,4])Ue(()=>{var g,y;let d=u*13,h=(g=e.find(A=>A.shape[1]===d**2&&A.shape[2]===Ru.length))==null?void 0:g.squeeze(),p=(y=e.find(A=>A.shape[1]===d**2&&A.shape[2]a.object.minConfidence&&x!==61){let b=(.5+Math.trunc(A%d))/d,w=(.5+Math.trunc(A/d))/d,I=m[A].map(W=>W*(d/u/t)),[T,C]=[b-ym/u*I[0],w-ym/u*I[1]],[z,$]=[b+ym/u*I[2]-T,w+ym/u*I[3]-C],S=[T,C,z,$];S=S.map(W=>Math.max(0,Math.min(W,1)));let D=[S[0]*n[0],S[1]*n[1],S[2]*n[0],S[3]*n[1]],_={id:r++,score:Math.round(100*v)/100,class:x+1,label:Ru[x].label,box:D.map(W=>Math.trunc(W)),boxRaw:S};s.push(_)}}});e.forEach(u=>Ve(u));let i=s.map(u=>[u.boxRaw[1],u.boxRaw[0],u.boxRaw[3],u.boxRaw[2]]),o=s.map(u=>u.score),l=[];if(i&&i.length>0){let u=await Ye.nonMaxSuppressionAsync(i,o,a.object.maxDetected,a.object.iouThreshold,a.object.minConfidence);l=u.dataSync(),Ve(u)}return s=s.filter((u,d)=>l.includes(d)).sort((u,d)=>d.score-u.score),s}async function d3(e,t){return l30?(l3++,o3):(l3=0,new Promise(async n=>{let a=[e.shape[2],e.shape[1]],r=Ye.resizeBilinear(e,[ya.inputSize,ya.inputSize],!1),s=r.div(255),i=s.transpose([0,3,1,2]);s.dispose(),r.dispose();let o;t.object.enabled&&(o=await ya.predict(i)),i.dispose();let l=await rwe(o,ya.inputSize,a,t);o3=l,n(l)}))}var Aa,h3=[],p3=Number.MAX_SAFE_INTEGER;async function c3(e){if(Aa)e.debug&&ge("cached model:",Aa.modelUrl);else{Aa=await Et(Mt(e.modelBasePath,e.object.modelPath));let t=Object.values(Aa.modelSignature.inputs);if(Aa.inputSize=Array.isArray(t)?parseInt(t[0].tensorShape.dim[2].size):null,!Aa.inputSize)throw new Error(`Human: Cannot determine model inputSize: ${e.object.modelPath}`);!Aa||!Aa.modelUrl?ge("load model failed:",e.object.modelPath):e.debug&&ge("load model:",Aa.modelUrl)}return Aa}async function swe(e,t,n,a){if(!e)return[];let r=[],s=e.arraySync(),i=Yn(e);e.dispose();let o=es(i,6,1);i.dispose();let u=Ii([o[1],o[0],o[3],o[2]],1).squeeze(),d=o[4].squeeze(),h=o[5].squeeze();o.forEach(f=>f.dispose());let p=await Ye.nonMaxSuppressionAsync(u,d,a.object.maxDetected,a.object.iouThreshold,a.object.minConfidence);u.dispose(),d.dispose(),h.dispose();let c=p.dataSync();p.dispose();let m=0;for(let f of c){let g=Math.trunc(100*s[0][f][4])/100,y=s[0][f][5],A=Ru[y].label,x=[s[0][f][0]/t,s[0][f][1]/t,s[0][f][2]/t,s[0][f][3]/t],v=[Math.trunc(x[0]*n[0]),Math.trunc(x[1]*n[1]),Math.trunc(x[2]*n[0]),Math.trunc(x[3]*n[1])];r.push({id:m++,score:g,class:y,label:A,box:v,boxRaw:x})}return r}async function f3(e,t){return p30?(p3++,h3):(p3=0,new Promise(async n=>{let a=[e.shape[2],e.shape[1]],r=Ye.resizeBilinear(e,[Aa.inputSize,Aa.inputSize]),s=t.object.enabled?Aa.execute(r,["tower_0/detections"]):null;r.dispose();let i=await swe(s,Aa.inputSize,a,t);h3=i,n(i)}))}var YM=e=>{if(!e)return[];let t=[];for(let n=0;nl.part==="leftWrist"),r=e[n].keypoints.find(l=>l.part==="rightWrist"),s=e[n].keypoints.find(l=>l.part==="nose");s&&a&&r&&a.position.yl.part==="leftShoulder"),o=e[n].keypoints.find(l=>l.part==="rightShoulder");i&&o&&t.push({body:n,gesture:`leaning ${i.position.y>o.position.y?"left":"right"}`})}return t},JM=e=>{if(!e)return[];let t=[];for(let n=0;n0){let a=e[n].mesh[33][2]-e[n].mesh[263][2];Math.abs(a)<10?t.push({face:n,gesture:"facing center"}):t.push({face:n,gesture:`facing ${a<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 o=e[n].mesh[152][2];Math.abs(o)>10&&t.push({face:n,gesture:`head ${o<0?"up":"down"}`})}return t},QM=e=>{if(!e)return[];let t=[];for(let n=0;n.06||h>.06)&&(u=!1),p>.06&&t.push({iris:n,gesture:"looking right"}),h>.06&&t.push({iris:n,gesture:"looking left"});let c=Math.abs(e[n].mesh[145][1]-e[n].annotations.rightEyeIris[0][1])/e[n].box[3],m=Math.abs(e[n].mesh[374][1]-e[n].annotations.leftEyeIris[0][1])/e[n].box[3];(m<.01||c<.01||m>.022||c>.022)&&(u=!1),(m<.01||c<.01)&&t.push({iris:n,gesture:"looking down"}),(m>.022||c>.022)&&t.push({iris:n,gesture:"looking up"}),u&&t.push({iris:n,gesture:"looking center"})}return t},e$=e=>{if(!e)return[];let t=[];for(let n=0;n0){let r=a.reduce((i,o)=>i.position[2]i.position[1](u[p]=0,h))},r=function(o,l){let u=e.createShader(l);if(e.shaderSource(u,o),e.compileShader(u),!e.getShaderParameter(u,e.COMPILE_STATUS))throw new Error("Filter: GL compile failed",e.getShaderInfoLog(u));return u};this.uniform={},this.attribute={};let s=r(t,e.VERTEX_SHADER),i=r(n,e.FRAGMENT_SHADER);if(this.id=e.createProgram(),e.attachShader(this.id,s),e.attachShader(this.id,i),e.linkProgram(this.id),!e.getProgramParameter(this.id,e.LINK_STATUS))throw new Error("Filter: GL link failed",e.getProgramInfoLog(this.id));e.useProgram(this.id),a(t,"attribute",this.attribute);for(let o in this.attribute)this.attribute[o]=e.getAttribLocation(this.id,o);a(t,"uniform",this.uniform),a(n,"uniform",this.uniform);for(let o in this.uniform)this.uniform[o]=e.getUniformLocation(this.id,o)}function t$(e){e||(e={});let t=0,n=null,a=!1,r=-1,s=[null,null],i=[],o=-1,l=-1,u=null,d=null,h={},p=e.canvas||document.createElement("canvas"),c={},m={INTERMEDIATE:1},f=p.getContext("webgl");if(!f)throw new Error("Filter: getContext() failed");this.addFilter=function(b){let w=Array.prototype.slice.call(arguments,1),I=h[b];i.push({func:I,args:w})},this.reset=function(){i=[]};let g=function(b,w){if(!(b===o&&w===l)){if(p.width=b,o=b,p.height=w,l=w,!u){let I=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]);u=f.createBuffer(),f.bindBuffer(f.ARRAY_BUFFER,u),f.bufferData(f.ARRAY_BUFFER,I,f.STATIC_DRAW),f.pixelStorei(f.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!0)}f.viewport(0,0,o,l),s=[null,null]}},y=function(b,w){let I=f.createFramebuffer();f.bindFramebuffer(f.FRAMEBUFFER,I);let T=f.createRenderbuffer();f.bindRenderbuffer(f.RENDERBUFFER,T);let C=f.createTexture();return f.bindTexture(f.TEXTURE_2D,C),f.texImage2D(f.TEXTURE_2D,0,f.RGBA,b,w,0,f.RGBA,f.UNSIGNED_BYTE,null),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_MAG_FILTER,f.LINEAR),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_MIN_FILTER,f.LINEAR),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_WRAP_S,f.CLAMP_TO_EDGE),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_WRAP_T,f.CLAMP_TO_EDGE),f.framebufferTexture2D(f.FRAMEBUFFER,f.COLOR_ATTACHMENT0,f.TEXTURE_2D,C,0),f.bindTexture(f.TEXTURE_2D,null),f.bindFramebuffer(f.FRAMEBUFFER,null),{fbo:I,texture:C}},A=function(b){return s[b]=s[b]||y(o,l),s[b]},x=function(b=null){var C,z;let w=null,I=null,T=!1;t===0?w=n:w=(C=A(r))==null?void 0:C.texture,t++,a&&!(b&m.INTERMEDIATE)?(I=null,T=t%2==0):(r=(r+1)%2,I=(z=A(r))==null?void 0:z.fbo),f.bindTexture(f.TEXTURE_2D,w),f.bindFramebuffer(f.FRAMEBUFFER,I),f.uniform1f(d.uniform.flipY,T?-1:1),f.drawArrays(f.TRIANGLES,0,6)};this.apply=function(b){if(g(b.width,b.height),t=0,n||(n=f.createTexture()),f.bindTexture(f.TEXTURE_2D,n),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_WRAP_S,f.CLAMP_TO_EDGE),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_WRAP_T,f.CLAMP_TO_EDGE),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_MIN_FILTER,f.NEAREST),f.texParameteri(f.TEXTURE_2D,f.TEXTURE_MAG_FILTER,f.NEAREST),f.texImage2D(f.TEXTURE_2D,0,f.RGBA,f.RGBA,f.UNSIGNED_BYTE,b),i.length===0)return x(),p;for(let w=0;w0,s=e.naturalHeight||e.videoHeight||e.height||e.shape&&e.shape[2]>0;if(!r||!s)return{tensor:null,canvas:_e};let i=r,o=s;if(i>Am&&(i=Am,o=i*s/r),o>Am&&(o=Am,i=o*r/s),t.filter.width>0?i=t.filter.width:t.filter.height>0&&(i=r*(t.filter.height/s)),t.filter.height>0?o=t.filter.height:t.filter.width>0&&(o=s*(t.filter.width/r)),!i||!o)throw new Error("Human: Input cannot determine dimension");(!_e||(_e==null?void 0:_e.width)!==i||(_e==null?void 0:_e.height)!==o)&&(_e=typeof OffscreenCanvas!="undefined"?new OffscreenCanvas(i,o):document.createElement("canvas"),(_e==null?void 0:_e.width)!==i&&(_e.width=i),(_e==null?void 0:_e.height)!==o&&(_e.height=o));let l=_e.getContext("2d");if(e instanceof ImageData?l.putImageData(e,0,0):t.filter.flip&&typeof l.translate!="undefined"?(l.translate(r,0),l.scale(-1,1),l.drawImage(e,0,0,r,s,0,0,_e==null?void 0:_e.width,_e==null?void 0:_e.height),l.setTransform(1,0,0,1,0,0)):l.drawImage(e,0,0,r,s,0,0,_e==null?void 0:_e.width,_e==null?void 0:_e.height),t.filter.enabled){if((!an||!Wt||_e.width!==Wt.width||(_e==null?void 0:_e.height)!==(Wt==null?void 0:Wt.height))&&(Wt=typeof OffscreenCanvas!="undefined"?new OffscreenCanvas(_e==null?void 0:_e.width,_e==null?void 0:_e.height):document.createElement("canvas"),(Wt==null?void 0:Wt.width)!==(_e==null?void 0:_e.width)&&(Wt.width=_e==null?void 0:_e.width),(Wt==null?void 0:Wt.height)!==(_e==null?void 0:_e.height)&&(Wt.height=_e==null?void 0:_e.height),an=ka.flags.IS_BROWSER?new t$({canvas:Wt}):null),!an)return{tensor:null,canvas:_e};an.reset(),an.addFilter("brightness",t.filter.brightness),t.filter.contrast!==0&&an.addFilter("contrast",t.filter.contrast),t.filter.sharpness!==0&&an.addFilter("sharpen",t.filter.sharpness),t.filter.blur!==0&&an.addFilter("blur",t.filter.blur),t.filter.saturation!==0&&an.addFilter("saturation",t.filter.saturation),t.filter.hue!==0&&an.addFilter("hue",t.filter.hue),t.filter.negative&&an.addFilter("negative"),t.filter.sepia&&an.addFilter("sepia"),t.filter.vintage&&an.addFilter("brownie"),t.filter.sepia&&an.addFilter("sepia"),t.filter.kodachrome&&an.addFilter("kodachrome"),t.filter.technicolor&&an.addFilter("technicolor"),t.filter.polaroid&&an.addFilter("polaroid"),t.filter.pixelate!==0&&an.addFilter("pixelate",t.filter.pixelate),an.apply(_e)}else Wt=_e,an&&(an=null);let u;if(Wt.data){let d=[Wt.height,Wt.width,3];u=mc(Wt.data,d,"int32")}else if(Wt instanceof ImageData)u=Ua?Ua.fromPixels(Wt):null;else if(t.backend==="webgl"||t.backend==="humangl"){let d=typeof OffscreenCanvas!="undefined"?new OffscreenCanvas(i,o):document.createElement("canvas");d.width=i,d.height=o;let h=d.getContext("2d");h==null||h.drawImage(Wt,0,0),u=Ua?Ua.fromPixels(d):null}else{let d=typeof OffscreenCanvas!="undefined"?new OffscreenCanvas(i,o):document.createElement("canvas");d.width=i,d.height=o;let h=d.getContext("2d");h==null||h.drawImage(Wt,0,0);let p=h==null?void 0:h.getImageData(0,0,i,o);u=Ua?Ua.fromPixels(p):null}if(u){let d=u.toFloat();n=d.expandDims(0),u.dispose(),d.dispose()}}let a=t.filter.return?Wt:null;return{tensor:n,canvas:a}}var y3={};Qg(y3,{all:()=>uwe,body:()=>r$,canvas:()=>lwe,face:()=>a$,gesture:()=>n$,hand:()=>s$,object:()=>i$,options:()=>ii,person:()=>owe});var ii={color:"rgba(173, 216, 230, 0.6)",labelColor:"rgba(173, 216, 230, 1)",shadowColor:"black",font:'small-caps 14px "Segoe UI"',lineHeight:24,lineWidth:6,pointSize:2,roundRect:28,drawPoints:!1,drawLabels:!0,drawBoxes:!0,drawPolygons:!0,drawGaze:!0,fillPolygons:!1,useDepth:!0,useCurves:!1,bufferedOutput:!0},xm=e=>Math.round(e*180/Math.PI);function m3(e,t,n,a=0,r){e.fillStyle=r.useDepth&&a?`rgba(${127.5+2*a}, ${127.5-2*a}, 255, 0.3)`:r.color,e.beginPath(),e.arc(t,n,r.pointSize,0,2*Math.PI),e.fill()}function Np(e,t,n,a,r,s){if(e.beginPath(),s.useCurves){let i=(t+t+a)/2,o=(n+n+r)/2;e.ellipse(i,o,a/2,r/2,0,0,2*Math.PI)}else e.lineWidth=s.lineWidth,e.moveTo(t+s.roundRect,n),e.lineTo(t+a-s.roundRect,n),e.quadraticCurveTo(t+a,n,t+a,n+s.roundRect),e.lineTo(t+a,n+r-s.roundRect),e.quadraticCurveTo(t+a,n+r,t+a-s.roundRect,n+r),e.lineTo(t+s.roundRect,n+r),e.quadraticCurveTo(t,n+r,t,n+r-s.roundRect),e.lineTo(t,n+s.roundRect),e.quadraticCurveTo(t,n,t+s.roundRect,n),e.closePath();e.stroke()}function g3(e,t=[],n){if(!(t===void 0||t.length===0)){e.beginPath(),e.moveTo(t[0][0],t[0][1]);for(let a of t){let r=a[2]||0;e.strokeStyle=n.useDepth&&r?`rgba(${127.5+2*r}, ${127.5-2*r}, 255, 0.3)`:n.color,e.fillStyle=n.useDepth&&r?`rgba(${127.5+2*r}, ${127.5-2*r}, 255, 0.3)`:n.color,e.lineTo(a[0],Math.round(a[1]))}e.stroke(),n.fillPolygons&&(e.closePath(),e.fill())}}function Tp(e,t=[],n){if(!(t===void 0||t.length===0)){if(!n.useCurves||t.length<=2){g3(e,t,n);return}e.moveTo(t[0][0],t[0][1]);for(let a=0;a1&&l[1].length>0){let u=o[1]>0?`#${o[1]}`:"",d=`${o[0]} ${u}: ${l[1]}`;a.shadowColor&&a.shadowColor!==""&&(r.fillStyle=a.shadowColor,r.fillText(d,8,2+s*a.lineHeight)),r.fillStyle=a.labelColor,r.fillText(d,6,0+s*a.lineHeight),s+=1}}}async function a$(e,t,n){var s,i,o,l;let a=ia(ii,n);if(!t||!e||!(e instanceof HTMLCanvasElement))return;let r=e.getContext("2d");if(!!r)for(let u of t){r.font=a.font,r.strokeStyle=a.color,r.fillStyle=a.color,a.drawBoxes&&Np(r,u.box[0],u.box[1],u.box[2],u.box[3],a);let d=[];if(d.push(`face: ${Math.trunc(100*u.score)}%`),u.genderScore&&d.push(`${u.gender||""} ${Math.trunc(100*u.genderScore)}%`),u.age&&d.push(`age: ${u.age||""}`),u.iris&&d.push(`distance: ${u.iris}`),u.emotion&&u.emotion.length>0){let h=u.emotion.map(p=>`${Math.trunc(100*p.score)}% ${p.emotion}`);h.length>3&&(h.length=3),d.push(h.join(" "))}u.rotation&&u.rotation.angle&&u.rotation.gaze&&(u.rotation.angle.roll&&d.push(`roll: ${xm(u.rotation.angle.roll)}\xB0 yaw:${xm(u.rotation.angle.yaw)}\xB0 pitch:${xm(u.rotation.angle.pitch)}\xB0`),u.rotation.gaze.bearing&&d.push(`gaze: ${xm(u.rotation.gaze.bearing)}\xB0`)),d.length===0&&d.push("face"),r.fillStyle=a.color;for(let h=d.length-1;h>=0;h--){let p=Math.max(u.box[0],0),c=h*a.lineHeight+u.box[1];a.shadowColor&&a.shadowColor!==""&&(r.fillStyle=a.shadowColor,r.fillText(d[h],p+5,c+16)),r.fillStyle=a.labelColor,r.fillText(d[h],p+4,c+15)}if(r.lineWidth=1,u.mesh&&u.mesh.length>0){if(a.drawPoints)for(let h of u.mesh)m3(r,h[0],h[1],h[2],a);if(a.drawPolygons){r.lineWidth=1;for(let h=0;hu.mesh[c]);g3(r,p,a)}if(u.annotations&&u.annotations.leftEyeIris){r.strokeStyle=a.useDepth?"rgba(255, 200, 255, 0.3)":a.color,r.beginPath();let h=Math.abs(u.annotations.leftEyeIris[3][0]-u.annotations.leftEyeIris[1][0])/2,p=Math.abs(u.annotations.leftEyeIris[4][1]-u.annotations.leftEyeIris[2][1])/2;r.ellipse(u.annotations.leftEyeIris[0][0],u.annotations.leftEyeIris[0][1],h,p,0,0,2*Math.PI),r.stroke(),a.fillPolygons&&(r.fillStyle=a.useDepth?"rgba(255, 255, 200, 0.3)":a.color,r.fill())}if(u.annotations&&u.annotations.rightEyeIris){r.strokeStyle=a.useDepth?"rgba(255, 200, 255, 0.3)":a.color,r.beginPath();let h=Math.abs(u.annotations.rightEyeIris[3][0]-u.annotations.rightEyeIris[1][0])/2,p=Math.abs(u.annotations.rightEyeIris[4][1]-u.annotations.rightEyeIris[2][1])/2;r.ellipse(u.annotations.rightEyeIris[0][0],u.annotations.rightEyeIris[0][1],h,p,0,0,2*Math.PI),r.stroke(),a.fillPolygons&&(r.fillStyle=a.useDepth?"rgba(255, 255, 200, 0.3)":a.color,r.fill())}if(a.drawGaze&&((i=(s=u.rotation)==null?void 0:s.gaze)==null?void 0:i.strength)&&((l=(o=u.rotation)==null?void 0:o.gaze)==null?void 0:l.bearing)&&u.annotations.leftEyeIris&&u.annotations.rightEyeIris&&u.annotations.leftEyeIris[0]&&u.annotations.rightEyeIris[0]){r.strokeStyle="pink",r.beginPath();let h=[u.annotations.leftEyeIris[0][0]+Math.sin(u.rotation.gaze.bearing)*u.rotation.gaze.strength*u.box[3],u.annotations.leftEyeIris[0][1]+Math.cos(u.rotation.gaze.bearing)*u.rotation.gaze.strength*u.box[2]];r.moveTo(u.annotations.leftEyeIris[0][0],u.annotations.leftEyeIris[0][1]),r.lineTo(h[0],h[1]);let p=[u.annotations.rightEyeIris[0][0]+Math.sin(u.rotation.gaze.bearing)*u.rotation.gaze.strength*u.box[3],u.annotations.rightEyeIris[0][1]+Math.cos(u.rotation.gaze.bearing)*u.rotation.gaze.strength*u.box[2]];r.moveTo(u.annotations.rightEyeIris[0][0],u.annotations.rightEyeIris[0][1]),r.lineTo(p[0],p[1]),r.stroke()}}}}}async function r$(e,t,n){var s;let a=ia(ii,n);if(!t||!e||!(e instanceof HTMLCanvasElement))return;let r=e.getContext("2d");if(!!r){r.lineJoin="round";for(let i=0;iu.part==="leftShoulder"),o&&l.push([o.position[0],o.position[1]]),o=t[i].keypoints.find(u=>u.part==="rightShoulder"),o&&l.push([o.position[0],o.position[1]]),Tp(r,l,a),l.length=0,o=t[i].keypoints.find(u=>u.part==="rightShoulder"),o&&l.push([o.position[0],o.position[1]]),o=t[i].keypoints.find(u=>u.part==="rightHip"),o&&l.push([o.position[0],o.position[1]]),o=t[i].keypoints.find(u=>u.part==="leftHip"),o&&l.push([o.position[0],o.position[1]]),o=t[i].keypoints.find(u=>u.part==="leftShoulder"),o&&l.push([o.position[0],o.position[1]]),l.length===4&&g3(r,l,a),l.length=0,o=t[i].keypoints.find(u=>u.part==="leftHip"),o&&l.push([o.position[0],o.position[1]]),o=t[i].keypoints.find(u=>u.part==="leftKnee"),o&&l.push([o.position[0],o.position[1]]),o=t[i].keypoints.find(u=>u.part==="leftAnkle"),o&&l.push([o.position[0],o.position[1]]),o=t[i].keypoints.find(u=>u.part==="leftHeel"),o&&l.push([o.position[0],o.position[1]]),o=t[i].keypoints.find(u=>u.part==="leftFoot"),o&&l.push([o.position[0],o.position[1]]),Tp(r,l,a),l.length=0,o=t[i].keypoints.find(u=>u.part==="rightHip"),o&&l.push([o.position[0],o.position[1]]),o=t[i].keypoints.find(u=>u.part==="rightKnee"),o&&l.push([o.position[0],o.position[1]]),o=t[i].keypoints.find(u=>u.part==="rightAnkle"),o&&l.push([o.position[0],o.position[1]]),o=t[i].keypoints.find(u=>u.part==="rightHeel"),o&&l.push([o.position[0],o.position[1]]),o=t[i].keypoints.find(u=>u.part==="rightFoot"),o&&l.push([o.position[0],o.position[1]]),Tp(r,l,a),l.length=0,o=t[i].keypoints.find(u=>u.part==="leftShoulder"),o&&l.push([o.position[0],o.position[1]]),o=t[i].keypoints.find(u=>u.part==="leftElbow"),o&&l.push([o.position[0],o.position[1]]),o=t[i].keypoints.find(u=>u.part==="leftWrist"),o&&l.push([o.position[0],o.position[1]]),o=t[i].keypoints.find(u=>u.part==="leftPalm"),o&&l.push([o.position[0],o.position[1]]),Tp(r,l,a),l.length=0,o=t[i].keypoints.find(u=>u.part==="rightShoulder"),o&&l.push([o.position[0],o.position[1]]),o=t[i].keypoints.find(u=>u.part==="rightElbow"),o&&l.push([o.position[0],o.position[1]]),o=t[i].keypoints.find(u=>u.part==="rightWrist"),o&&l.push([o.position[0],o.position[1]]),o=t[i].keypoints.find(u=>u.part==="rightPalm"),o&&l.push([o.position[0],o.position[1]]),Tp(r,l,a)}}}}async function s$(e,t,n){let a=ia(ii,n);if(!t||!e||!(e instanceof HTMLCanvasElement))return;let r=e.getContext("2d");if(!!r){r.lineJoin="round",r.font=a.font;for(let s of t){if(a.drawBoxes&&(r.strokeStyle=a.color,r.fillStyle=a.color,Np(r,s.box[0],s.box[1],s.box[2],s.box[3],a),a.drawLabels&&(a.shadowColor&&a.shadowColor!==""&&(r.fillStyle=a.shadowColor,r.fillText("hand",s.box[0]+3,1+s.box[1]+a.lineHeight,s.box[2])),r.fillStyle=a.labelColor,r.fillText("hand",s.box[0]+2,0+s.box[1]+a.lineHeight,s.box[2])),r.stroke()),a.drawPoints&&s.keypoints&&s.keypoints.length>0)for(let i of s.keypoints)r.fillStyle=a.useDepth?`rgba(${127.5+2*i[2]}, ${127.5-2*i[2]}, 255, 0.5)`:a.color,m3(r,i[0],i[1],0,a);if(a.drawLabels){let i=(o,l)=>{r.fillStyle=a.useDepth?`rgba(${127.5+2*o[o.length-1][2]}, ${127.5-2*o[o.length-1][2]}, 255, 0.5)`:a.color,r.fillText(l,o[o.length-1][0]+4,o[o.length-1][1]+4)};r.font=a.font,i(s.annotations.indexFinger,"index"),i(s.annotations.middleFinger,"middle"),i(s.annotations.ringFinger,"ring"),i(s.annotations.pinky,"pinky"),i(s.annotations.thumb,"thumb"),i(s.annotations.palmBase,"palm")}if(a.drawPolygons){let i=o=>{if(!!o)for(let l=0;l0?l-1:0][0],o[l>0?l-1:0][1]),r.lineTo(o[l][0],o[l][1]),r.stroke()};r.lineWidth=a.lineWidth,i(s.annotations.indexFinger),i(s.annotations.middleFinger),i(s.annotations.ringFinger),i(s.annotations.pinky),i(s.annotations.thumb)}}}}async function i$(e,t,n){let a=ia(ii,n);if(!t||!e||!(e instanceof HTMLCanvasElement))return;let r=e.getContext("2d");if(!!r){r.lineJoin="round",r.font=a.font;for(let s of t)if(a.drawBoxes){if(r.strokeStyle=a.color,r.fillStyle=a.color,Np(r,s.box[0],s.box[1],s.box[2],s.box[3],a),a.drawLabels){let i=`${Math.round(100*s.score)}% ${s.label}`;a.shadowColor&&a.shadowColor!==""&&(r.fillStyle=a.shadowColor,r.fillText(i,s.box[0]+3,1+s.box[1]+a.lineHeight,s.box[2])),r.fillStyle=a.labelColor,r.fillText(i,s.box[0]+2,0+s.box[1]+a.lineHeight,s.box[2])}r.stroke()}}}async function owe(e,t,n){let a=ia(ii,n);if(!t||!e||!(e instanceof HTMLCanvasElement))return;let r=e.getContext("2d");if(!!r){r.lineJoin="round",r.font=a.font;for(let s=0;s_.box[0]&&I.box[0]<_.box[0]+_.box[2]&&I.box[1]+I.box[3]>_.box[1]&&I.box[1]+I.box[3]<_.box[1]+_.box[3]&&(T.body=_);if(T.body)for(let _ of n)_.box[0]+_.box[2]>T.body.box[0]&&_.box[0]+_.box[2]T.body.box[1]&&_.box[1]+_.box[3]T.body.box[0]&&_.box[1]+_.box[3]>T.body.box[1]&&_.box[1]+_.box[3]{_&&_.length===4&&(C.push(_[0],_[0]+_[2]),z.push(_[1],_[1]+_[3]))};$((y=T.face)==null?void 0:y.box),$((A=T.body)==null?void 0:A.box),$((v=(x=T.hands)==null?void 0:x.left)==null?void 0:v.box),$((w=(b=T.hands)==null?void 0:b.right)==null?void 0:w.box);let S=Math.min(...C),D=Math.min(...z);T.box=[S,D,Math.max(...C)-S,Math.max(...z)-D],r&&r.length===4&&(T.boxRaw=[T.box[0]/r[2],T.box[1]/r[1],T.box[2]/r[2],T.box[3]/r[1]]),i.push(T)}return i}var Le={face:[],body:[],hand:[],gesture:[],object:[],persons:[],performance:{},timestamp:0};function l$(e){var r,s,i,o,l,u,d,h,p,c,m,f,g,y,A,x,v,b,w,I,T;let t=Date.now()-e.timestamp,n=t<1e3?8-Math.log(t):1;if(Le.canvas=e.canvas,!Le.body||e.body.length!==Le.body.length)Le.body=JSON.parse(JSON.stringify(e.body));else for(let C=0;C((n-1)*Le.body[C].box[_]+D)/n),$=e.body[C].boxRaw.map((D,_)=>((n-1)*Le.body[C].boxRaw[_]+D)/n),S=e.body[C].keypoints.map((D,_)=>({score:D.score,part:D.part,position:[Le.body[C].keypoints[_]?((n-1)*Le.body[C].keypoints[_].position[0]+D.position[0])/n:D.position[0],Le.body[C].keypoints[_]?((n-1)*Le.body[C].keypoints[_].position[1]+D.position[1])/n:D.position[1]],positionRaw:[Le.body[C].keypoints[_]?((n-1)*Le.body[C].keypoints[_].positionRaw[0]+D.positionRaw[0])/n:D.position[0],Le.body[C].keypoints[_]?((n-1)*Le.body[C].keypoints[_].positionRaw[1]+D.positionRaw[1])/n:D.position[1]]}));Le.body[C]={...e.body[C],box:z,boxRaw:$,keypoints:S}}if(!Le.hand||e.hand.length!==Le.hand.length)Le.hand=JSON.parse(JSON.stringify(e.hand));else for(let C=0;C((n-1)*Le.hand[C].box[X]+W)/n),$=e.hand[C].boxRaw.map((W,X)=>((n-1)*Le.hand[C].boxRaw[X]+W)/n),S=e.hand[C].keypoints.map((W,X)=>W.map((q,Q)=>((n-1)*Le.hand[C].keypoints[X][Q]+q)/n)),D=Object.keys(e.hand[C].annotations),_={};for(let W of D)_[W]=e.hand[C].annotations[W].map((X,q)=>X.map((Q,ee)=>((n-1)*Le.hand[C].annotations[W][q][ee]+Q)/n));Le.hand[C]={...e.hand[C],box:z,boxRaw:$,keypoints:S,annotations:_}}if(!Le.face||e.face.length!==Le.face.length)Le.face=JSON.parse(JSON.stringify(e.face));else for(let C=0;C((n-1)*Le.face[C].box[_]+D)/n),$=e.face[C].boxRaw.map((D,_)=>((n-1)*Le.face[C].boxRaw[_]+D)/n),S={matrix:[0,0,0,0,0,0,0,0,0],angle:{roll:0,yaw:0,pitch:0},gaze:{bearing:0,strength:0}};S.matrix=(r=e.face[C].rotation)==null?void 0:r.matrix,S.angle={roll:((n-1)*(((i=(s=Le.face[C].rotation)==null?void 0:s.angle)==null?void 0:i.roll)||0)+(((l=(o=e.face[C].rotation)==null?void 0:o.angle)==null?void 0:l.roll)||0))/n,yaw:((n-1)*(((d=(u=Le.face[C].rotation)==null?void 0:u.angle)==null?void 0:d.yaw)||0)+(((p=(h=e.face[C].rotation)==null?void 0:h.angle)==null?void 0:p.yaw)||0))/n,pitch:((n-1)*(((m=(c=Le.face[C].rotation)==null?void 0:c.angle)==null?void 0:m.pitch)||0)+(((g=(f=e.face[C].rotation)==null?void 0:f.angle)==null?void 0:g.pitch)||0))/n},S.gaze={bearing:((n-1)*(((A=(y=Le.face[C].rotation)==null?void 0:y.gaze)==null?void 0:A.bearing)||0)+(((v=(x=e.face[C].rotation)==null?void 0:x.gaze)==null?void 0:v.bearing)||0))/n,strength:((n-1)*(((w=(b=Le.face[C].rotation)==null?void 0:b.gaze)==null?void 0:w.strength)||0)+(((T=(I=e.face[C].rotation)==null?void 0:I.gaze)==null?void 0:T.strength)||0))/n},Le.face[C]={...e.face[C],rotation:S,box:z,boxRaw:$}}if(!Le.object||e.object.length!==Le.object.length)Le.object=JSON.parse(JSON.stringify(e.object));else for(let C=0;C((n-1)*Le.object[C].box[D]+S)/n),$=e.object[C].boxRaw.map((S,D)=>((n-1)*Le.object[C].boxRaw[D]+S)/n);Le.object[C]={...e.object[C],box:z,boxRaw:$}}let a=e.persons;if(!Le.persons||a.length!==Le.persons.length)Le.persons=JSON.parse(JSON.stringify(a));else for(let C=0;C((n-1)*Le.persons[C].box[$]+z)/n);return Le.gesture=e.gesture,Le.performance=e.performance,Le}var La,A3=!1;async function bm(e){return La?e.debug&&ge("cached model:",La.modelUrl):(La=await Et(Mt(e.modelBasePath,e.segmentation.modelPath)),!La||!La.modelUrl?ge("load model failed:",e.segmentation.modelPath):e.debug&&ge("load model:",La.modelUrl)),La}async function x3(e){var m,f;let t=((m=e.tensor)==null?void 0:m.shape[1])||0,n=((f=e.tensor)==null?void 0:f.shape[2])||0;if(!e.tensor||!La||!La.inputs[0].shape)return null;let a=Ye.resizeBilinear(e.tensor,[La.inputs[0].shape[1],La.inputs[0].shape[2]],!1),r=a.div(255),s=La.predict(r);Ve(a),Ve(r);let i=Yn(s,0),o;if(i.shape[2]===2){let g=i.softmax(),[y,A]=fd(g,2),x=A.expandDims(2),v=x.expandDims(0);Ve(g),Ve(y),Ve(A);let b=Ye.cropAndResize(v,[[0,0,.5,.5]],[0],[t,n]);o=b.squeeze(0),Ve(b),Ve(x),Ve(v)}else o=Ye.resizeBilinear(i,[t,n]);if(typeof document=="undefined")return o.dataSync();let l=typeof OffscreenCanvas!="undefined"?new OffscreenCanvas(t,n):document.createElement("canvas");l.width=t,l.height=n,Ua&&await Ua.toPixels(o,l),Ve(o),Ve(i),Ve(s);let u=typeof OffscreenCanvas!="undefined"?new OffscreenCanvas(t,n):document.createElement("canvas");u.width=t,u.height=n;let d=u.getContext("2d");d.filter="blur(8px",await d.drawImage(l,0,0);let h=d.getImageData(0,0,t,n).data,p=typeof OffscreenCanvas!="undefined"?new OffscreenCanvas(t,n):document.createElement("canvas");p.width=t,p.height=n;let c=p.getContext("2d");return e.canvas&&await c.drawImage(e.canvas,0,0),c.globalCompositeOperation="darken",c.filter="blur(8px)",await c.drawImage(l,0,0),c.globalCompositeOperation="source-over",c.filter="none",e.canvas=p,h}async function u$(e,t,n){var s;if(A3)return null;A3=!0,La||await bm(n);let a=wo(e,n),r=await x3(a);if(Ve(a.tensor),t&&r){let i=wo(t,n),o=i.canvas;Ve(i.tensor);let l=a.canvas,u=(s=l.getContext("2d"))==null?void 0:s.getImageData(0,0,l.width,l.height).data,d=typeof OffscreenCanvas!="undefined"?new OffscreenCanvas(l.width,l.height):document.createElement("canvas");d.width=l.width,d.height=l.height;let h=d.getContext("2d");h.globalCompositeOperation="copy",h.drawImage(o,0,0,d.width,d.height);let p=h.getImageData(0,0,d.width,d.height);for(let c=0;c{if(!Fn(this,Ep))return;let n=this.tf.engine().state.numTensors,a=Fn(this,Fu);Ja(this,Fu,n);let r=n-a;r!==0&&ge(...t,r)};wa(this,km,t=>{if(!Fn(this,Cp))return null;if(!t)return"input is not defined";if(this.tf.ENV.flags.IS_NODE&&!(t instanceof St))return"input must be a tensor";try{this.tf.getBackend()}catch(n){return"backend not loaded"}return null});wa(this,Mp,async(t=!1)=>{var n;if(this.config.backend&&this.config.backend.length>0&&t||this.tf.getBackend()!==this.config.backend){let a=st();if(this.state="backend",this.config.backend&&this.config.backend.length>0){if(typeof window=="undefined"&&typeof WorkerGlobalScope!="undefined"&&this.config.debug&&ge("running inside web worker"),this.tf.ENV.flags.IS_BROWSER&&this.config.backend==="tensorflow"&&(this.config.backend="webgl"),this.tf.ENV.flags.IS_NODE&&(this.config.backend==="webgl"||this.config.backend==="humangl")&&(this.config.backend="tensorflow"),this.config.debug&&ge("setting backend:",this.config.backend),this.config.backend==="wasm"){if(this.config.debug&&ge("wasm path:",this.config.wasmPath),typeof((n=this.tf)==null?void 0:n.setWasmPaths)!="undefined")this.tf.setWasmPaths(this.config.wasmPath);else throw new Error("Human: WASM backend is not loaded");let r=await this.tf.env().getAsync("WASM_HAS_SIMD_SUPPORT"),s=await this.tf.env().getAsync("WASM_HAS_MULTITHREAD_SUPPORT");this.config.debug&&ge(`wasm execution: ${r?"SIMD":"no SIMD"} ${s?"multithreaded":"singlethreaded"}`),this.config.debug&&!r&&ge("warning: wasm simd support is not enabled")}this.config.backend==="humangl"&&hM();try{await this.tf.setBackend(this.config.backend)}catch(r){ge("error: cannot set backend:",this.config.backend,r)}}if(this.tf.enableProdMode(),this.tf.getBackend()==="webgl"||this.tf.getBackend()==="humangl"){this.tf.ENV.set("CHECK_COMPUTATION_FOR_ERRORS",!1),this.tf.ENV.set("WEBGL_CPU_FORWARD",!0),this.tf.ENV.set("WEBGL_PACK_DEPTHWISECONV",!0),typeof this.config.deallocate!="undefined"&&this.config.deallocate&&(ge("changing webgl: WEBGL_DELETE_TEXTURE_THRESHOLD:",!0),this.tf.ENV.set("WEBGL_DELETE_TEXTURE_THRESHOLD",0));let r=await this.tf.backend().getGPGPUContext().gl;this.config.debug&&ge(`gl version:${r.getParameter(r.VERSION)} renderer:${r.getParameter(r.RENDERER)}`)}await this.tf.ready(),this.performance.backend=Math.trunc(st()-a)}});this.next=t=>l$(t||this.result);wa(this,Im,async t=>{if(this.config.cacheSensitivity===0)return!1;let n=32,a=t.resizeBilinear([Math.trunc(t.shape[1]/n),Math.trunc(t.shape[2]/n)]),r=a.dataSync(),s=0;for(let l=0;l10*this.config.cacheSensitivity?0:i),o});wa(this,Sm,async()=>{let t=(r,s="application/octet-stream")=>fetch(`data:${s};base64,${r}`).then(i=>i.blob()),n,a;switch(this.config.warmup){case"face":n=await t(vm);break;case"full":n=await t(wm);break;default:n=null}if(n){let r=await createImageBitmap(n);a=await this.detect(r,this.config),r.close()}return a});wa(this,Nm,async()=>new Promise(t=>{let n,a=0;switch(this.config.warmup){case"face":a=256,n="data:image/jpeg;base64,"+vm;break;case"full":case"body":a=1200,n="data:image/jpeg;base64,"+wm;break;default:n=null}let r=new Image;r.onload=async()=>{let s=typeof OffscreenCanvas!="undefined"?new OffscreenCanvas(a,a):document.createElement("canvas");s.width=r.naturalWidth,s.height=r.naturalHeight;let i=s.getContext("2d");i==null||i.drawImage(r,0,0);let o=await this.detect(s,this.config);t(o)},n?r.src=n:t(null)}));wa(this,Tm,async()=>{let t=r=>Buffer.from(r,"base64"),n;if(this.config.warmup==="face"&&(n=t(vm)),(this.config.warmup==="body"||this.config.warmup==="full")&&(n=t(wm)),!n)return null;let a;if(typeof void 0!="undefined"){let r=(void 0).decodeJpeg(n),s=r.expandDims(0);this.tf.dispose(r),a=await this.detect(s,this.config),this.tf.dispose(s)}else this.config.debug&&ge("Warmup tfjs-node not loaded");return a});this.config=ia(F3,t||{}),this.tf=bp,this.draw=y3,this.version=d$,this.state="idle",Ja(this,Fu,0),Ja(this,Ep,!1),Ja(this,Cp,!1),Ja(this,ko,!0),Ja(this,Ou,0),this.performance={backend:0,load:0,image:0,frames:0,cached:0,changed:0,total:0,draw:0},this.models={face:null,posenet:null,blazepose:null,efficientpose:null,movenet:null,handpose:null,age:null,gender:null,emotion:null,embedding:null,nanodet:null,centernet:null,faceres:null,segmentation:null},this.image=n=>wo(n,this.config),this.faceTriangulation=IM,this.faceUVMap=SM,this.sysinfo=O3(),Ja(this,Io,1)}similarity(t,n){return Ob(t,n)}segmentation(t,n){return u$(t,n,this.config)}enhance(t){return Db(t)}match(t,n,a=0){return EM(t,n,a)}async load(t){this.state="load";let n=st();t&&(this.config=ia(this.config,t)),Fn(this,ko)&&(this.config.debug&&ge(`version: ${this.version}`),this.config.debug&&ge(`tfjs version: ${this.tf.version_core}`),this.config.debug&&ge("platform:",this.sysinfo.platform),this.config.debug&&ge("agent:",this.sysinfo.agent),await Fn(this,Mp).call(this,!0),this.tf.ENV.flags.IS_BROWSER&&(this.config.debug&&ge("configuration:",this.config),this.config.debug&&ge("tf flags:",this.tf.ENV.flags))),this.config.async?[this.models.face,this.models.emotion,this.models.handpose,this.models.posenet,this.models.blazepose,this.models.efficientpose,this.models.movenet,this.models.nanodet,this.models.centernet,this.models.faceres,this.models.segmentation]=await Promise.all([this.models.face||(this.config.face.enabled?Tb(this.config):null),this.models.emotion||(this.config.face.enabled&&this.config.face.emotion.enabled?Mb(this.config):null),this.models.handpose||(this.config.hand.enabled?Zb(this.config):null),this.models.posenet||(this.config.body.enabled&&this.config.body.modelPath.includes("posenet")?jb(this.config):null),this.models.blazepose||(this.config.body.enabled&&this.config.body.modelPath.includes("blazepose")?mm(this.config):null),this.models.efficientpose||(this.config.body.enabled&&this.config.body.modelPath.includes("efficientpose")?ZM(this.config):null),this.models.movenet||(this.config.body.enabled&&this.config.body.modelPath.includes("movenet")?s3(this.config):null),this.models.nanodet||(this.config.object.enabled&&this.config.object.modelPath.includes("nanodet")?u3(this.config):null),this.models.centernet||(this.config.object.enabled&&this.config.object.modelPath.includes("centernet")?c3(this.config):null),this.models.faceres||(this.config.face.enabled&&this.config.face.description.enabled?Fb(this.config):null),this.models.segmentation||(this.config.segmentation.enabled?bm(this.config):null)]):(this.config.face.enabled&&!this.models.face&&(this.models.face=await Tb(this.config)),this.config.face.enabled&&this.config.face.emotion.enabled&&!this.models.emotion&&(this.models.emotion=await Mb(this.config)),this.config.hand.enabled&&!this.models.handpose&&(this.models.handpose=await Zb(this.config)),this.config.body.enabled&&!this.models.posenet&&this.config.body.modelPath.includes("posenet")&&(this.models.posenet=await jb(this.config)),this.config.body.enabled&&!this.models.blazepose&&this.config.body.modelPath.includes("blazepose")&&(this.models.blazepose=await mm(this.config)),this.config.body.enabled&&!this.models.efficientpose&&this.config.body.modelPath.includes("efficientpose")&&(this.models.efficientpose=await mm(this.config)),this.config.body.enabled&&!this.models.movenet&&this.config.body.modelPath.includes("movenet")&&(this.models.movenet=await s3(this.config)),this.config.object.enabled&&!this.models.nanodet&&this.config.object.modelPath.includes("nanodet")&&(this.models.nanodet=await u3(this.config)),this.config.object.enabled&&!this.models.centernet&&this.config.object.modelPath.includes("centernet")&&(this.models.centernet=await c3(this.config)),this.config.face.enabled&&this.config.face.description.enabled&&!this.models.faceres&&(this.models.faceres=await Fb(this.config)),this.config.segmentation.enabled&&!this.models.segmentation&&(this.models.segmentation=await bm(this.config))),Fn(this,ko)&&(this.config.debug&&ge("tf engine state:",this.tf.engine().state.numBytes,"bytes",this.tf.engine().state.numTensors,"tensors"),Ja(this,ko,!1));let a=Math.trunc(st()-n);a>(this.performance.load||0)&&(this.performance.load=a)}async detect(t,n){return new Promise(async a=>{this.state="config";let r,s;this.config=ia(this.config,n),this.state="check";let i=Fn(this,km).call(this,t);i&&(ge(i,t),a({error:i}));let o=st();await Fn(this,Mp).call(this),await this.load(),r=st();let l=wo(t,this.config);if(this.performance.image=Math.trunc(st()-r),this.analyze("Get Image:"),this.config.segmentation.enabled&&l&&l.tensor&&(this.analyze("Start Segmentation:"),this.state="run:segmentation",r=st(),await x3(l),s=Math.trunc(st()-r),s>0&&(this.performance.segmentation=s),l.canvas&&(l.tensor.dispose(),l=wo(l.canvas,this.config)),this.analyze("End Segmentation:")),!l||!l.tensor){ge("could not convert input to tensor"),a({error:"could not convert input to tensor"});return}r=st(),this.config.skipFrame=await Fn(this,Im).call(this,l.tensor),this.performance.frames||(this.performance.frames=0),this.performance.cached||(this.performance.cached=0),this.performance.frames++,this.config.skipFrame&&this.performance.cached++,this.performance.changed=Math.trunc(st()-r),this.analyze("Check Changed:");let u,d,h,p;this.config.async?(u=this.config.face.enabled?zb(this,l.tensor):[],this.performance.face&&delete this.performance.face):(this.state="run:face",r=st(),u=this.config.face.enabled?await zb(this,l.tensor):[],s=Math.trunc(st()-r),s>0&&(this.performance.face=s)),this.analyze("Start Body:"),this.config.async?(this.config.body.modelPath.includes("posenet")?d=this.config.body.enabled?Ub(l.tensor,this.config):[]:this.config.body.modelPath.includes("blazepose")?d=this.config.body.enabled?Yb(l.tensor,this.config):[]:this.config.body.modelPath.includes("efficientpose")?d=this.config.body.enabled?t3(l.tensor,this.config):[]:this.config.body.modelPath.includes("movenet")&&(d=this.config.body.enabled?i3(l.tensor,this.config):[]),this.performance.body&&delete this.performance.body):(this.state="run:body",r=st(),this.config.body.modelPath.includes("posenet")?d=this.config.body.enabled?await Ub(l.tensor,this.config):[]:this.config.body.modelPath.includes("blazepose")?d=this.config.body.enabled?await Yb(l.tensor,this.config):[]:this.config.body.modelPath.includes("efficientpose")?d=this.config.body.enabled?await t3(l.tensor,this.config):[]:this.config.body.modelPath.includes("movenet")&&(d=this.config.body.enabled?await i3(l.tensor,this.config):[]),s=Math.trunc(st()-r),s>0&&(this.performance.body=s)),this.analyze("End Body:"),this.analyze("Start Hand:"),this.config.async?(h=this.config.hand.enabled?Xb(l.tensor,this.config):[],this.performance.hand&&delete this.performance.hand):(this.state="run:hand",r=st(),h=this.config.hand.enabled?await Xb(l.tensor,this.config):[],s=Math.trunc(st()-r),s>0&&(this.performance.hand=s)),this.analyze("End Hand:"),this.analyze("Start Object:"),this.config.async?(this.config.object.modelPath.includes("nanodet")?p=this.config.object.enabled?d3(l.tensor,this.config):[]:this.config.object.modelPath.includes("centernet")&&(p=this.config.object.enabled?f3(l.tensor,this.config):[]),this.performance.object&&delete this.performance.object):(this.state="run:object",r=st(),this.config.object.modelPath.includes("nanodet")?p=this.config.object.enabled?await d3(l.tensor,this.config):[]:this.config.object.modelPath.includes("centernet")&&(p=this.config.object.enabled?await f3(l.tensor,this.config):[]),s=Math.trunc(st()-r),s>0&&(this.performance.object=s)),this.analyze("End Object:"),this.config.async&&([u,d,h,p]=await Promise.all([u,d,h,p]));let c=[];this.config.gesture.enabled&&(r=st(),c=[...JM(u),...YM(d),...e$(h),...QM(u)],this.config.async?this.performance.gesture&&delete this.performance.gesture:this.performance.gesture=Math.trunc(st()-r)),this.performance.total=Math.trunc(st()-o),this.state="idle",this.result={face:u,body:d,hand:h,gesture:c,object:p,performance:this.performance,canvas:l.canvas,timestamp:Date.now(),get persons(){var m;return o$(u,d,h,c,(m=l==null?void 0:l.tensor)==null?void 0:m.shape)}},Ve(l.tensor),a(this.result)})}async warmup(t){let n=st();if(t&&(this.config=ia(this.config,t)),!this.config.warmup||this.config.warmup==="none")return{error:"null"};let a;typeof createImageBitmap=="function"?a=await Fn(this,Sm).call(this):typeof Image!="undefined"?a=await Fn(this,Nm).call(this):a=await Fn(this,Tm).call(this);let r=st();return this.config.debug&&ge("Warmup",this.config.warmup,Math.round(r-n),"ms",a),a}};Fu=new WeakMap,Ep=new WeakMap,Cp=new WeakMap,ko=new WeakMap,Io=new WeakMap,Ou=new WeakMap,km=new WeakMap,Mp=new WeakMap,Im=new WeakMap,Sm=new WeakMap,Nm=new WeakMap,Tm=new WeakMap;return hwe;})(); /** * @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 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 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. */